ngram
listlengths 0
67.8k
|
|---|
[
"# clip to mitigate exploding gradients return loss, dW_xh, dW_hh, dW_hy, db_h, db_y,",
"1 ixes.append(ix) return ixes n, p = 0, 0 mW_xh, mW_hh, mW_hy =",
"(H x 1) array of initial hidden state returns the loss, gradients on",
"steps seq_length long) if p + seq_length + 1 >= len(data) or n",
"for next chars loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) print(f'loss: {loss}') #",
"char_to_ix = { ch:i for i,ch in enumerate(chars) } ix_to_char = { i:ch",
"mW_hy, mb_h, mb_y]): mem += dparam * dparam param += -learning_rate * dparam",
"= 0 # go from start of data inputs = [char_to_ix[ch] for ch",
"= np.random.randn(vocab_size, hidden_size) * 0.01 # weight: hidden to output b_h = np.zeros((hidden_size,",
"unique.') # data has 1109177 characters,80 unique. char_to_ix = { ch:i for i,ch",
"vocab_size x 1 hs[-1] = np.copy(hprev) # hs[t] size = hidden_size * 1",
"inputs,targets are both list of integers indicating which unique character. inputs: a seq_length",
"print(ix_to_char) # hyperparameters hidden_size = 256 # size of hidden layer of neurons",
"parameters, and last hidden state \"\"\" xs, hs, ys, ps = {}, {},",
"= np.dot(W_hy.T, dy) + dhnext # backprop into h dhraw = (1 -",
"np.exp(y) / np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size, 1)) x[ix] =",
"lossFun(inputs, targets, hprev): \"\"\" inputs,targets are both list of integers indicating which unique",
"variables for Adagrad smooth_loss = -np.log(1.0 / vocab_size) * seq_length # loss at",
"[char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] # sample from the model now and then",
"encode in 1-of-k representation xs[t][inputs[t]] = 1 # inputs[t] is a index number,",
"to hidden W_hh = np.random.randn(hidden_size, hidden_size) * 0.01 # weight: hidden to hidden",
"number of steps to unroll the RNN for learning_rate = 1e-1 # model",
"1)) # output bias def unicodeToAscii(s): return ''.join( c for c in unicodedata.normalize('NFD',",
"output bias def unicodeToAscii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if",
"* 1 loss = 0 # xs: input line; ys: output line; hs:",
"i,ch in enumerate(chars) } ix_to_char = { i:ch for i,ch in enumerate(chars) }",
"np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h, mb_y = np.zeros_like(b_h), np.zeros_like(b_y) # memory variables for Adagrad smooth_loss",
"dhnext = np.dot(W_hh.T, dhraw) for dparam in [dW_xh, dW_hh, dW_hy, db_h, db_y]: np.clip(dparam,",
"reversed(range(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -= 1 # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad",
"db_y, hprev = lossFun(inputs, targets, hprev) smooth_loss = smooth_loss * 0.999 + loss",
"characters,{vocab_size} unique.') # data has 1109177 characters,80 unique. char_to_ix = { ch:i for",
"# encode in 1-of-k representation xs[t][inputs[t]] = 1 # inputs[t] is a index",
"from start of data inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]] targets =",
"now and then if n % 100 == 0: sample_ix = sample(hprev, inputs[0],",
"{ i:ch for i,ch in enumerate(chars) } print(char_to_ix) print(ix_to_char) # hyperparameters hidden_size =",
"np.sum(np.exp(ys[t])) # (normalized) probabilities for next chars loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy",
"n): \"\"\" sample a sequence of integers from the model h is memory",
"np.random.randn(vocab_size, hidden_size) * 0.01 # weight: hidden to output b_h = np.zeros((hidden_size, 1))",
"b_h, b_y], [dW_xh, dW_hh, dW_hy, db_h, db_y], [mW_xh, mW_hh, mW_hy, mb_h, mb_y]): mem",
"xs[t][inputs[t]] = 1 # inputs[t] is a index number, xs[t] is a vector",
"{} # sx[t] = ys[t] = ps[t] size = vocab_size x 1 hs[-1]",
"-np.log(1.0 / vocab_size) * seq_length # loss at iteration 0 while True: try:",
"h dhraw = (1 - hs[t] * hs[t]) * dh # backprop through",
"= np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) + b_h) y = np.dot(W_hy, h) +",
"np.dot(W_hy.T, dy) + dhnext # backprop into h dhraw = (1 - hs[t]",
"into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here dW_hy += np.dot(dy, hs[t].T) db_y +=",
"clip to mitigate exploding gradients return loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hs[len(inputs)-1]",
"c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c in",
"the net and fetch gradient loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hprev =",
"reset RNN memory p = 0 # go from start of data inputs",
"# hidden bias b_y = np.zeros((vocab_size, 1)) # output bias def unicodeToAscii(s): return",
"data pointer n += 1 # iteration counter except KeyboardInterrupt: sample_ix = sample(hprev,",
"of integers from the model h is memory state, seed_ix is seed letter",
"= [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] # sample from the model now and",
"size list hprev is (H x 1) array of initial hidden state returns",
"# prepare inputs (we're sweeping from left to right in steps seq_length long)",
"{data_size} characters,{vocab_size} unique.') # data has 1109177 characters,80 unique. char_to_ix = { ch:i",
"step i.e. do predictions :) \"\"\" x = np.zeros((vocab_size, 1)) x[seed_ix] = 1",
"state ys[t] = np.dot(W_hy, hs[t]) + b_y # unnormalized log probabilities for next",
"if n % 100 == 0: print(f'iter{n}, loss: {smooth_loss}') # print progress #",
"dW_hy, db_h, db_y], [mW_xh, mW_hh, mW_hy, mb_h, mb_y]): mem += dparam * dparam",
"% (txt, )) # forward seq_length characters through the net and fetch gradient",
"ps = {}, {}, {}, {} # sx[t] = ys[t] = ps[t] size",
"+ loss * 0.001 if n % 100 == 0: print(f'iter{n}, loss: {smooth_loss}')",
"np.copy(ps[t]) dy[targets[t]] -= 1 # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here",
"1 ixes = [] for t in range(n): h = np.tanh(np.dot(W_xh, x) +",
"import string import codecs # data I/O data = codecs.open('data/potter.txt', 'r', encoding='utf8', errors='ignore').read()",
"mW_xh, mW_hh, mW_hy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h, mb_y = np.zeros_like(b_h), np.zeros_like(b_y) #",
"== 0: sample_ix = sample(hprev, inputs[0], 200) txt = ''.join(ix_to_char[ix] for ix in",
"mb_h, mb_y]): mem += dparam * dparam param += -learning_rate * dparam /",
"gradient of b_y, same shape as b_y dhnext = np.zeros_like(hs[0]) for t in",
"the model now and then if n % 100 == 0: sample_ix =",
"for t in range(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation xs[t][inputs[t]]",
"if n % 100 == 0: sample_ix = sample(hprev, inputs[0], 200) txt =",
"= {}, {}, {}, {} # sx[t] = ys[t] = ps[t] size =",
"weight: input to hidden W_hh = np.random.randn(hidden_size, hidden_size) * 0.01 # weight: hidden",
"in 1-of-k representation xs[t][inputs[t]] = 1 # inputs[t] is a index number, xs[t]",
"1 # iteration counter except KeyboardInterrupt: sample_ix = sample(hprev, inputs[0], data_size) txt =",
"enumerate(chars) } print(char_to_ix) print(ix_to_char) # hyperparameters hidden_size = 256 # size of hidden",
"s) if unicodedata.category(c) != 'Mn' and c in all_letters ) def lossFun(inputs, targets,",
"weight: hidden to output b_h = np.zeros((hidden_size, 1)) # hidden bias b_y =",
"RNN model. Written b_y <NAME> (@karpathy) BSD License \"\"\" import numpy as np",
"dW_xh += np.dot(dhraw, xs[t].T) dW_hh += np.dot(dhraw, hs[t-1].T) dhnext = np.dot(W_hh.T, dhraw) for",
"and then if n % 100 == 0: sample_ix = sample(hprev, inputs[0], 200)",
"hidden_size) * 0.01 # weight: hidden to output b_h = np.zeros((hidden_size, 1)) #",
"model h is memory state, seed_ix is seed letter for first time step",
"np.zeros_like(W_hy) # gradient of W_hy, same shape as W_hy db_h = np.zeros_like(b_h) #",
"* hs[t]) * dh # backprop through tanh nonlinearity db_h += dhraw dW_xh",
"with Adagrad for param, dparam, mem in zip([W_xh, W_hh, W_hy, b_h, b_y], [dW_xh,",
"W_xh, same shape as W_xh dW_hh = np.zeros_like(W_hh) # gradient of W_hh, same",
"backprop through tanh nonlinearity db_h += dhraw dW_xh += np.dot(dhraw, xs[t].T) dW_hh +=",
"encoding='utf8') chars = list(set(data)) data_size = len(data) # vocab_size = len(chars) print(f'data has",
"= { i:ch for i,ch in enumerate(chars) } print(char_to_ix) print(ix_to_char) # hyperparameters hidden_size",
"c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c in all_letters )",
"inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]] targets = [char_to_ix[ch] for ch in",
"{loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') # backward pass: compute gradients going backwards",
"- hs[t] * hs[t]) * dh # backprop through tanh nonlinearity db_h +=",
"= (1 - hs[t] * hs[t]) * dh # backprop through tanh nonlinearity",
"= 256 # size of hidden layer of neurons seq_length = 128 #",
"p = 0, 0 mW_xh, mW_hh, mW_hy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h, mb_y",
"= len(data) # vocab_size = len(chars) print(f'data has {data_size} characters,{vocab_size} unique.') # data",
"= codecs.open('data/output.txt', 'w', encoding='utf8') chars = list(set(data)) data_size = len(data) # vocab_size =",
"i,ch in enumerate(chars) } print(char_to_ix) print(ix_to_char) # hyperparameters hidden_size = 256 # size",
"in range(n): h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) + b_h) y =",
"smooth_loss = smooth_loss * 0.999 + loss * 0.001 if n % 100",
"pass: compute gradients going backwards dW_xh = np.zeros_like(W_xh) # gradient of W_xh, same",
"in sample_ix) print('----\\n %s \\n----' % (txt, )) # forward seq_length characters through",
"0.001 if n % 100 == 0: print(f'iter{n}, loss: {smooth_loss}') # print progress",
"start of data inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]] targets = [char_to_ix[ch]",
"= np.copy(ps[t]) dy[targets[t]] -= 1 # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused",
"''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c",
"softmax (cross-entropy loss) print(f'loss: {loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') # backward pass:",
"into h dhraw = (1 - hs[t] * hs[t]) * dh # backprop",
"seq_length + 1 >= len(data) or n == 0: hprev = np.zeros((hidden_size,1)) #",
"= np.zeros((hidden_size,1)) # reset RNN memory p = 0 # go from start",
"+= -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update p +=",
"indicating which unique character. inputs: a seq_length size list hprev is (H x",
"dy[targets[t]] -= 1 # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here dW_hy",
"tanh nonlinearity db_h += dhraw dW_xh += np.dot(dhraw, xs[t].T) dW_hh += np.dot(dhraw, hs[t-1].T)",
"# move data pointer n += 1 # iteration counter except KeyboardInterrupt: sample_ix",
"sample(hprev, inputs[0], 200) txt = ''.join(ix_to_char[ix] for ix in sample_ix) print('----\\n %s \\n----'",
"dW_xh, dW_hh, dW_hy, db_h, db_y, hprev = lossFun(inputs, targets, hprev) smooth_loss = smooth_loss",
"np.zeros_like(W_xh) # gradient of W_xh, same shape as W_xh dW_hh = np.zeros_like(W_hh) #",
"letter for first time step i.e. do predictions :) \"\"\" x = np.zeros((vocab_size,",
"# backprop into h dhraw = (1 - hs[t] * hs[t]) * dh",
"exploding gradients return loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hs[len(inputs)-1] def sample(h, seed_ix,",
"representation xs[t][inputs[t]] = 1 # inputs[t] is a index number, xs[t] is a",
"(we're sweeping from left to right in steps seq_length long) if p +",
"http://cs231n.github.io/neural-networks-case-study/#grad if confused here dW_hy += np.dot(dy, hs[t].T) db_y += dy dh =",
"KeyboardInterrupt: sample_ix = sample(hprev, inputs[0], data_size) txt = ''.join(ix_to_char[ix] for ix in sample_ix)",
"x[seed_ix] = 1 ixes = [] for t in range(n): h = np.tanh(np.dot(W_xh,",
"b_h, same shape as b_h db_y = np.zeros_like(b_y) # gradient of b_y, same",
"= vocab_size x 1 hs[-1] = np.copy(hprev) # hs[t] size = hidden_size *",
"backward pass: compute gradients going backwards dW_xh = np.zeros_like(W_xh) # gradient of W_xh,",
"# sample from the model now and then if n % 100 ==",
"ys[t] = np.dot(W_hy, hs[t]) + b_y # unnormalized log probabilities for next chars",
"hidden_size * 1 loss = 0 # xs: input line; ys: output line;",
"smooth_loss = -np.log(1.0 / vocab_size) * seq_length # loss at iteration 0 while",
"* 0.001 if n % 100 == 0: print(f'iter{n}, loss: {smooth_loss}') # print",
"same shape as W_xh dW_hh = np.zeros_like(W_hh) # gradient of W_hh, same shape",
"states are different from each other. # forward pass for t in range(len(inputs)):",
"} print(char_to_ix) print(ix_to_char) # hyperparameters hidden_size = 256 # size of hidden layer",
"return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and",
"W_hy db_h = np.zeros_like(b_h) # gradient of b_h, same shape as b_h db_y",
"dW_hy += np.dot(dy, hs[t].T) db_y += dy dh = np.dot(W_hy.T, dy) + dhnext",
"seed_ix is seed letter for first time step i.e. do predictions :) \"\"\"",
"in data[p+1:p+seq_length+1]] # sample from the model now and then if n %",
"same shape as W_hh dW_hy = np.zeros_like(W_hy) # gradient of W_hy, same shape",
"dW_hh = np.zeros_like(W_hh) # gradient of W_hh, same shape as W_hh dW_hy =",
"targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] # sample from the model now",
"zip([W_xh, W_hh, W_hy, b_h, b_y], [dW_xh, dW_hh, dW_hy, db_h, db_y], [mW_xh, mW_hh, mW_hy,",
"+= seq_length # move data pointer n += 1 # iteration counter except",
"dhraw) for dparam in [dW_xh, dW_hh, dW_hy, db_h, db_y]: np.clip(dparam, -5, 5, out=dparam)",
"{}, {}, {}, {} # sx[t] = ys[t] = ps[t] size = vocab_size",
"different from each other. # forward pass for t in range(len(inputs)): xs[t] =",
"character-level Vanilla RNN model. Written b_y <NAME> (@karpathy) BSD License \"\"\" import numpy",
"probabilities for next chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # (normalized) probabilities for",
"RNN memory p = 0 # go from start of data inputs =",
"has 1109177 characters,80 unique. char_to_ix = { ch:i for i,ch in enumerate(chars) }",
"bias b_y = np.zeros((vocab_size, 1)) # output bias def unicodeToAscii(s): return ''.join( c",
"hs[t-1].T) dhnext = np.dot(W_hh.T, dhraw) for dparam in [dW_xh, dW_hh, dW_hy, db_h, db_y]:",
"+ b_y # unnormalized log probabilities for next chars ps[t] = np.exp(ys[t]) /",
"1)) # hidden bias b_y = np.zeros((vocab_size, 1)) # output bias def unicodeToAscii(s):",
"-5, 5, out=dparam) # clip to mitigate exploding gradients return loss, dW_xh, dW_hh,",
"{smooth_loss}') # print progress # perform parameter update with Adagrad for param, dparam,",
"shape as b_h db_y = np.zeros_like(b_y) # gradient of b_y, same shape as",
"both list of integers indicating which unique character. inputs: a seq_length size list",
"sample a sequence of integers from the model h is memory state, seed_ix",
"= np.dot(W_hy, hs[t]) + b_y # unnormalized log probabilities for next chars ps[t]",
"= np.dot(W_hh.T, dhraw) for dparam in [dW_xh, dW_hh, dW_hy, db_h, db_y]: np.clip(dparam, -5,",
"for Adagrad smooth_loss = -np.log(1.0 / vocab_size) * seq_length # loss at iteration",
"= sample(hprev, inputs[0], data_size) txt = ''.join(ix_to_char[ix] for ix in sample_ix) fake.write(txt) break",
"= 0 # xs: input line; ys: output line; hs: hidden states, multiple",
"inputs[t] is a index number, xs[t] is a vector hs[t] = np.tanh(np.dot(W_xh, xs[t])",
"same shape as W_hy db_h = np.zeros_like(b_h) # gradient of b_h, same shape",
"if p + seq_length + 1 >= len(data) or n == 0: hprev",
"dW_hh += np.dot(dhraw, hs[t-1].T) dhnext = np.dot(W_hh.T, dhraw) for dparam in [dW_xh, dW_hh,",
"i.e. do predictions :) \"\"\" x = np.zeros((vocab_size, 1)) x[seed_ix] = 1 ixes",
"of W_hh, same shape as W_hh dW_hy = np.zeros_like(W_hy) # gradient of W_hy,",
"sample_ix = sample(hprev, inputs[0], 200) txt = ''.join(ix_to_char[ix] for ix in sample_ix) print('----\\n",
"through the net and fetch gradient loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hprev",
"# weight: hidden to hidden W_hy = np.random.randn(vocab_size, hidden_size) * 0.01 # weight:",
"each other. # forward pass for t in range(len(inputs)): xs[t] = np.zeros((vocab_size,1)) #",
"seed_ix, n): \"\"\" sample a sequence of integers from the model h is",
"hidden W_hy = np.random.randn(vocab_size, hidden_size) * 0.01 # weight: hidden to output b_h",
"/ np.sum(np.exp(ys[t])) # (normalized) probabilities for next chars loss += -np.log(ps[t][targets[t],0]) # softmax",
"as b_h db_y = np.zeros_like(b_y) # gradient of b_y, same shape as b_y",
"pointer n += 1 # iteration counter except KeyboardInterrupt: sample_ix = sample(hprev, inputs[0],",
"them, # even the weights are reused, the states are different from each",
"dy = np.copy(ps[t]) dy[targets[t]] -= 1 # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if",
"first time step i.e. do predictions :) \"\"\" x = np.zeros((vocab_size, 1)) x[seed_ix]",
"W_hh = np.random.randn(hidden_size, hidden_size) * 0.01 # weight: hidden to hidden W_hy =",
"np.dot(dhraw, xs[t].T) dW_hh += np.dot(dhraw, hs[t-1].T) dhnext = np.dot(W_hh.T, dhraw) for dparam in",
"is seed letter for first time step i.e. do predictions :) \"\"\" x",
"loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hs[len(inputs)-1] def sample(h, seed_ix, n): \"\"\" sample",
"probabilities for next chars loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) print(f'loss: {loss}')",
"-learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update p += seq_length",
"sample(h, seed_ix, n): \"\"\" sample a sequence of integers from the model h",
"for i,ch in enumerate(chars) } print(char_to_ix) print(ix_to_char) # hyperparameters hidden_size = 256 #",
"model parameters, and last hidden state \"\"\" xs, hs, ys, ps = {},",
"mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem +",
"predictions :) \"\"\" x = np.zeros((vocab_size, 1)) x[seed_ix] = 1 ixes = []",
"weight: hidden to hidden W_hy = np.random.randn(vocab_size, hidden_size) * 0.01 # weight: hidden",
"# backward pass: compute gradients going backwards dW_xh = np.zeros_like(W_xh) # gradient of",
":) \"\"\" x = np.zeros((vocab_size, 1)) x[seed_ix] = 1 ixes = [] for",
"= np.zeros((vocab_size, 1)) x[seed_ix] = 1 ixes = [] for t in range(n):",
"inputs: a seq_length size list hprev is (H x 1) array of initial",
"np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size, 1)) x[ix] = 1 ixes.append(ix) return ixes n,",
"dW_hy, db_h, db_y, hprev = lossFun(inputs, targets, hprev) smooth_loss = smooth_loss * 0.999",
"# gradient of W_hy, same shape as W_hy db_h = np.zeros_like(b_h) # gradient",
"np.dot(W_hy, hs[t]) + b_y # unnormalized log probabilities for next chars ps[t] =",
"== 0: print(f'iter{n}, loss: {smooth_loss}') # print progress # perform parameter update with",
"multiple of them, # even the weights are reused, the states are different",
"\\n----' % (txt, )) # forward seq_length characters through the net and fetch",
"def lossFun(inputs, targets, hprev): \"\"\" inputs,targets are both list of integers indicating which",
"print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') # backward pass: compute gradients going backwards dW_xh =",
"in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c in all_letters ) def",
"learning_rate = 1e-1 # model parameters W_xh = np.random.randn(hidden_size, vocab_size) * 0.01 #",
"the states are different from each other. # forward pass for t in",
"gradient of b_h, same shape as b_h db_y = np.zeros_like(b_y) # gradient of",
"gradients on model parameters, and last hidden state \"\"\" xs, hs, ys, ps",
"shape as b_y dhnext = np.zeros_like(hs[0]) for t in reversed(range(len(inputs))): dy = np.copy(ps[t])",
"# inputs[t] is a index number, xs[t] is a vector hs[t] = np.tanh(np.dot(W_xh,",
"+ np.dot(W_hh, hs[t-1]) + b_h) # hidden state ys[t] = np.dot(W_hy, hs[t]) +",
"hidden_size) * 0.01 # weight: hidden to hidden W_hy = np.random.randn(vocab_size, hidden_size) *",
"+ np.dot(W_hh, h) + b_h) y = np.dot(W_hy, h) + b_y p =",
"# memory variables for Adagrad smooth_loss = -np.log(1.0 / vocab_size) * seq_length #",
"range(n): h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) + b_h) y = np.dot(W_hy,",
"= ps[t] size = vocab_size x 1 hs[-1] = np.copy(hprev) # hs[t] size",
"print(f'data has {data_size} characters,{vocab_size} unique.') # data has 1109177 characters,80 unique. char_to_ix =",
"= np.zeros_like(W_hy) # gradient of W_hy, same shape as W_hy db_h = np.zeros_like(b_h)",
"compute gradients going backwards dW_xh = np.zeros_like(W_xh) # gradient of W_xh, same shape",
"hs[t] = np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1]) + b_h) # hidden state ys[t]",
"db_y = np.zeros_like(b_y) # gradient of b_y, same shape as b_y dhnext =",
"# softmax (cross-entropy loss) print(f'loss: {loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') # backward",
"= np.zeros((vocab_size, 1)) x[ix] = 1 ixes.append(ix) return ixes n, p = 0,",
"RNN for learning_rate = 1e-1 # model parameters W_xh = np.random.randn(hidden_size, vocab_size) *",
"line; hs: hidden states, multiple of them, # even the weights are reused,",
"unicodeToAscii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'",
"is (H x 1) array of initial hidden state returns the loss, gradients",
"0.01 # weight: hidden to hidden W_hy = np.random.randn(vocab_size, hidden_size) * 0.01 #",
"confused here dW_hy += np.dot(dy, hs[t].T) db_y += dy dh = np.dot(W_hy.T, dy)",
"= np.exp(y) / np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size, 1)) x[ix]",
"[mW_xh, mW_hh, mW_hy, mb_h, mb_y]): mem += dparam * dparam param += -learning_rate",
"+ seq_length + 1 >= len(data) or n == 0: hprev = np.zeros((hidden_size,1))",
"pass for t in range(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation",
"np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1]) + b_h) # hidden state ys[t] = np.dot(W_hy,",
"ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # (normalized) probabilities for next chars loss +=",
"targets, hprev) smooth_loss = smooth_loss * 0.999 + loss * 0.001 if n",
"data[p:p+seq_length]] targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] # sample from the model",
"ix_to_char = { i:ch for i,ch in enumerate(chars) } print(char_to_ix) print(ix_to_char) # hyperparameters",
"sample_ix) print('----\\n %s \\n----' % (txt, )) # forward seq_length characters through the",
"are both list of integers indicating which unique character. inputs: a seq_length size",
"seq_length characters through the net and fetch gradient loss, dW_xh, dW_hh, dW_hy, db_h,",
"h) + b_y p = np.exp(y) / np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel()) x",
"\"\"\" import numpy as np import unicodedata import string import codecs # data",
"1 hs[-1] = np.copy(hprev) # hs[t] size = hidden_size * 1 loss =",
"of hidden layer of neurons seq_length = 128 # number of steps to",
"going backwards dW_xh = np.zeros_like(W_xh) # gradient of W_xh, same shape as W_xh",
"np.random.randn(hidden_size, vocab_size) * 0.01 # weight: input to hidden W_hh = np.random.randn(hidden_size, hidden_size)",
"db_h = np.zeros_like(b_h) # gradient of b_h, same shape as b_h db_y =",
"in reversed(range(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -= 1 # backprop into y. see",
"W_hh, W_hy, b_h, b_y], [dW_xh, dW_hh, dW_hy, db_h, db_y], [mW_xh, mW_hh, mW_hy, mb_h,",
"gradients return loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hs[len(inputs)-1] def sample(h, seed_ix, n):",
"# print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') # backward pass: compute gradients going backwards dW_xh",
"+= np.dot(dhraw, hs[t-1].T) dhnext = np.dot(W_hh.T, dhraw) for dparam in [dW_xh, dW_hh, dW_hy,",
"# gradient of b_y, same shape as b_y dhnext = np.zeros_like(hs[0]) for t",
"= { ch:i for i,ch in enumerate(chars) } ix_to_char = { i:ch for",
"c in all_letters ) def lossFun(inputs, targets, hprev): \"\"\" inputs,targets are both list",
"hs[t]) * dh # backprop through tanh nonlinearity db_h += dhraw dW_xh +=",
"dW_hh, dW_hy, db_h, db_y], [mW_xh, mW_hh, mW_hy, mb_h, mb_y]): mem += dparam *",
"to right in steps seq_length long) if p + seq_length + 1 >=",
"reused, the states are different from each other. # forward pass for t",
"np.dot(W_hh, hs[t-1]) + b_h) # hidden state ys[t] = np.dot(W_hy, hs[t]) + b_y",
"== 0: hprev = np.zeros((hidden_size,1)) # reset RNN memory p = 0 #",
"array of initial hidden state returns the loss, gradients on model parameters, and",
"in range(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation xs[t][inputs[t]] = 1",
"db_y += dy dh = np.dot(W_hy.T, dy) + dhnext # backprop into h",
"input to hidden W_hh = np.random.randn(hidden_size, hidden_size) * 0.01 # weight: hidden to",
"+= dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8)",
"for learning_rate = 1e-1 # model parameters W_xh = np.random.randn(hidden_size, vocab_size) * 0.01",
"# reset RNN memory p = 0 # go from start of data",
"gradients going backwards dW_xh = np.zeros_like(W_xh) # gradient of W_xh, same shape as",
"b_h = np.zeros((hidden_size, 1)) # hidden bias b_y = np.zeros((vocab_size, 1)) # output",
"% 100 == 0: print(f'iter{n}, loss: {smooth_loss}') # print progress # perform parameter",
"except KeyboardInterrupt: sample_ix = sample(hprev, inputs[0], data_size) txt = ''.join(ix_to_char[ix] for ix in",
"{}, {}, {} # sx[t] = ys[t] = ps[t] size = vocab_size x",
"hprev = lossFun(inputs, targets, hprev) smooth_loss = smooth_loss * 0.999 + loss *",
"= len(chars) print(f'data has {data_size} characters,{vocab_size} unique.') # data has 1109177 characters,80 unique.",
"np.dot(dy, hs[t].T) db_y += dy dh = np.dot(W_hy.T, dy) + dhnext # backprop",
"n, p = 0, 0 mW_xh, mW_hh, mW_hy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h,",
"p = np.exp(y) / np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size, 1))",
"for first time step i.e. do predictions :) \"\"\" x = np.zeros((vocab_size, 1))",
"def unicodeToAscii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) !=",
"for t in reversed(range(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -= 1 # backprop into",
"# print progress # perform parameter update with Adagrad for param, dparam, mem",
"unicodedata import string import codecs # data I/O data = codecs.open('data/potter.txt', 'r', encoding='utf8',",
"0.999 + loss * 0.001 if n % 100 == 0: print(f'iter{n}, loss:",
"\"\"\" Minimal character-level Vanilla RNN model. Written b_y <NAME> (@karpathy) BSD License \"\"\"",
"# model parameters W_xh = np.random.randn(hidden_size, vocab_size) * 0.01 # weight: input to",
"b_y], [dW_xh, dW_hh, dW_hy, db_h, db_y], [mW_xh, mW_hh, mW_hy, mb_h, mb_y]): mem +=",
"unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c in all_letters ) def lossFun(inputs,",
"100 == 0: print(f'iter{n}, loss: {smooth_loss}') # print progress # perform parameter update",
"# output bias def unicodeToAscii(s): return ''.join( c for c in unicodedata.normalize('NFD', s)",
"= ''.join(ix_to_char[ix] for ix in sample_ix) print('----\\n %s \\n----' % (txt, )) #",
"= codecs.open('data/potter.txt', 'r', encoding='utf8', errors='ignore').read() fake = codecs.open('data/output.txt', 'w', encoding='utf8') chars = list(set(data))",
"256 # size of hidden layer of neurons seq_length = 128 # number",
"long) if p + seq_length + 1 >= len(data) or n == 0:",
"np.zeros_like(b_y) # memory variables for Adagrad smooth_loss = -np.log(1.0 / vocab_size) * seq_length",
"state returns the loss, gradients on model parameters, and last hidden state \"\"\"",
"+= dhraw dW_xh += np.dot(dhraw, xs[t].T) dW_hh += np.dot(dhraw, hs[t-1].T) dhnext = np.dot(W_hh.T,",
"ixes n, p = 0, 0 mW_xh, mW_hh, mW_hy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy)",
"t in range(n): h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) + b_h) y",
"\"\"\" inputs,targets are both list of integers indicating which unique character. inputs: a",
"h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) + b_h) y = np.dot(W_hy, h)",
"character. inputs: a seq_length size list hprev is (H x 1) array of",
"0 # go from start of data inputs = [char_to_ix[ch] for ch in",
"as np import unicodedata import string import codecs # data I/O data =",
"0 mW_xh, mW_hh, mW_hy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h, mb_y = np.zeros_like(b_h), np.zeros_like(b_y)",
"* 0.01 # weight: hidden to hidden W_hy = np.random.randn(vocab_size, hidden_size) * 0.01",
"= np.exp(ys[t]) / np.sum(np.exp(ys[t])) # (normalized) probabilities for next chars loss += -np.log(ps[t][targets[t],0])",
"backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here dW_hy += np.dot(dy, hs[t].T) db_y",
"W_xh dW_hh = np.zeros_like(W_hh) # gradient of W_hh, same shape as W_hh dW_hy",
"b_y dhnext = np.zeros_like(hs[0]) for t in reversed(range(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -=",
"xs: input line; ys: output line; hs: hidden states, multiple of them, #",
"loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hprev = lossFun(inputs, targets, hprev) smooth_loss =",
"x = np.zeros((vocab_size, 1)) x[ix] = 1 ixes.append(ix) return ixes n, p =",
"\"\"\" x = np.zeros((vocab_size, 1)) x[seed_ix] = 1 ixes = [] for t",
"all_letters ) def lossFun(inputs, targets, hprev): \"\"\" inputs,targets are both list of integers",
"here dW_hy += np.dot(dy, hs[t].T) db_y += dy dh = np.dot(W_hy.T, dy) +",
"= np.zeros_like(b_y) # gradient of b_y, same shape as b_y dhnext = np.zeros_like(hs[0])",
"memory state, seed_ix is seed letter for first time step i.e. do predictions",
"update p += seq_length # move data pointer n += 1 # iteration",
"'Mn' and c in all_letters ) def lossFun(inputs, targets, hprev): \"\"\" inputs,targets are",
"hs: hidden states, multiple of them, # even the weights are reused, the",
"b_y = np.zeros((vocab_size, 1)) # output bias def unicodeToAscii(s): return ''.join( c for",
"codecs # data I/O data = codecs.open('data/potter.txt', 'r', encoding='utf8', errors='ignore').read() fake = codecs.open('data/output.txt',",
"list(set(data)) data_size = len(data) # vocab_size = len(chars) print(f'data has {data_size} characters,{vocab_size} unique.')",
"# vocab_size = len(chars) print(f'data has {data_size} characters,{vocab_size} unique.') # data has 1109177",
"# sx[t] = ys[t] = ps[t] size = vocab_size x 1 hs[-1] =",
"output b_h = np.zeros((hidden_size, 1)) # hidden bias b_y = np.zeros((vocab_size, 1)) #",
"gradient of W_xh, same shape as W_xh dW_hh = np.zeros_like(W_hh) # gradient of",
"lossFun(inputs, targets, hprev) smooth_loss = smooth_loss * 0.999 + loss * 0.001 if",
"number, xs[t] is a vector hs[t] = np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1]) +",
"shape as W_xh dW_hh = np.zeros_like(W_hh) # gradient of W_hh, same shape as",
"np.zeros_like(b_h), np.zeros_like(b_y) # memory variables for Adagrad smooth_loss = -np.log(1.0 / vocab_size) *",
"has {data_size} characters,{vocab_size} unique.') # data has 1109177 characters,80 unique. char_to_ix = {",
"parameters W_xh = np.random.randn(hidden_size, vocab_size) * 0.01 # weight: input to hidden W_hh",
"W_hh, same shape as W_hh dW_hy = np.zeros_like(W_hy) # gradient of W_hy, same",
"unique character. inputs: a seq_length size list hprev is (H x 1) array",
"np.dot(W_hh, h) + b_h) y = np.dot(W_hy, h) + b_y p = np.exp(y)",
"np.sqrt(mem + 1e-8) # adagrad update p += seq_length # move data pointer",
"+= np.dot(dy, hs[t].T) db_y += dy dh = np.dot(W_hy.T, dy) + dhnext #",
"for i,ch in enumerate(chars) } ix_to_char = { i:ch for i,ch in enumerate(chars)",
"# forward pass for t in range(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode in",
"from each other. # forward pass for t in range(len(inputs)): xs[t] = np.zeros((vocab_size,1))",
"[] for t in range(n): h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) +",
"np.zeros_like(W_hy) mb_h, mb_y = np.zeros_like(b_h), np.zeros_like(b_y) # memory variables for Adagrad smooth_loss =",
"# backprop through tanh nonlinearity db_h += dhraw dW_xh += np.dot(dhraw, xs[t].T) dW_hh",
"dparam, mem in zip([W_xh, W_hh, W_hy, b_h, b_y], [dW_xh, dW_hh, dW_hy, db_h, db_y],",
"return ixes n, p = 0, 0 mW_xh, mW_hh, mW_hy = np.zeros_like(W_xh), np.zeros_like(W_hh),",
"on model parameters, and last hidden state \"\"\" xs, hs, ys, ps =",
"in [dW_xh, dW_hh, dW_hy, db_h, db_y]: np.clip(dparam, -5, 5, out=dparam) # clip to",
"of neurons seq_length = 128 # number of steps to unroll the RNN",
"data = codecs.open('data/potter.txt', 'r', encoding='utf8', errors='ignore').read() fake = codecs.open('data/output.txt', 'w', encoding='utf8') chars =",
"and c in all_letters ) def lossFun(inputs, targets, hprev): \"\"\" inputs,targets are both",
"nonlinearity db_h += dhraw dW_xh += np.dot(dhraw, xs[t].T) dW_hh += np.dot(dhraw, hs[t-1].T) dhnext",
"mW_hh, mW_hy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h, mb_y = np.zeros_like(b_h), np.zeros_like(b_y) # memory",
"ch in data[p+1:p+seq_length+1]] # sample from the model now and then if n",
"if confused here dW_hy += np.dot(dy, hs[t].T) db_y += dy dh = np.dot(W_hy.T,",
"n += 1 # iteration counter except KeyboardInterrupt: sample_ix = sample(hprev, inputs[0], data_size)",
"dW_hh, dW_hy, db_h, db_y]: np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding",
"# number of steps to unroll the RNN for learning_rate = 1e-1 #",
"dW_hy, db_h, db_y]: np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients",
"fetch gradient loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hprev = lossFun(inputs, targets, hprev)",
"np.zeros_like(W_hh) # gradient of W_hh, same shape as W_hh dW_hy = np.zeros_like(W_hy) #",
"dy) + dhnext # backprop into h dhraw = (1 - hs[t] *",
"for param, dparam, mem in zip([W_xh, W_hh, W_hy, b_h, b_y], [dW_xh, dW_hh, dW_hy,",
"dhraw = (1 - hs[t] * hs[t]) * dh # backprop through tanh",
"dparam in [dW_xh, dW_hh, dW_hy, db_h, db_y]: np.clip(dparam, -5, 5, out=dparam) # clip",
"} ix_to_char = { i:ch for i,ch in enumerate(chars) } print(char_to_ix) print(ix_to_char) #",
"''.join(ix_to_char[ix] for ix in sample_ix) print('----\\n %s \\n----' % (txt, )) # forward",
"of them, # even the weights are reused, the states are different from",
"<NAME> (@karpathy) BSD License \"\"\" import numpy as np import unicodedata import string",
"dhnext # backprop into h dhraw = (1 - hs[t] * hs[t]) *",
"= np.zeros_like(W_hh) # gradient of W_hh, same shape as W_hh dW_hy = np.zeros_like(W_hy)",
"np.dot(dhraw, hs[t-1].T) dhnext = np.dot(W_hh.T, dhraw) for dparam in [dW_xh, dW_hh, dW_hy, db_h,",
"unroll the RNN for learning_rate = 1e-1 # model parameters W_xh = np.random.randn(hidden_size,",
"list of integers indicating which unique character. inputs: a seq_length size list hprev",
"for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c in all_letters",
"chars loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) print(f'loss: {loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n",
"dW_xh = np.zeros_like(W_xh) # gradient of W_xh, same shape as W_xh dW_hh =",
"hidden_size = 256 # size of hidden layer of neurons seq_length = 128",
"hs[t] size = hidden_size * 1 loss = 0 # xs: input line;",
"# data I/O data = codecs.open('data/potter.txt', 'r', encoding='utf8', errors='ignore').read() fake = codecs.open('data/output.txt', 'w',",
"the model h is memory state, seed_ix is seed letter for first time",
"hidden state returns the loss, gradients on model parameters, and last hidden state",
"'w', encoding='utf8') chars = list(set(data)) data_size = len(data) # vocab_size = len(chars) print(f'data",
"vocab_size) * seq_length # loss at iteration 0 while True: try: # prepare",
"np.zeros((hidden_size, 1)) # hidden bias b_y = np.zeros((vocab_size, 1)) # output bias def",
"0.01 # weight: input to hidden W_hh = np.random.randn(hidden_size, hidden_size) * 0.01 #",
"of integers indicating which unique character. inputs: a seq_length size list hprev is",
"state \"\"\" xs, hs, ys, ps = {}, {}, {}, {} # sx[t]",
"hs[-1] = np.copy(hprev) # hs[t] size = hidden_size * 1 loss = 0",
"# weight: input to hidden W_hh = np.random.randn(hidden_size, hidden_size) * 0.01 # weight:",
"through tanh nonlinearity db_h += dhraw dW_xh += np.dot(dhraw, xs[t].T) dW_hh += np.dot(dhraw,",
"enumerate(chars) } ix_to_char = { i:ch for i,ch in enumerate(chars) } print(char_to_ix) print(ix_to_char)",
"Adagrad for param, dparam, mem in zip([W_xh, W_hh, W_hy, b_h, b_y], [dW_xh, dW_hh,",
"print(f'loss: {loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') # backward pass: compute gradients going",
"for ix in sample_ix) print('----\\n %s \\n----' % (txt, )) # forward seq_length",
"= np.random.randn(hidden_size, hidden_size) * 0.01 # weight: hidden to hidden W_hy = np.random.randn(vocab_size,",
"return loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hs[len(inputs)-1] def sample(h, seed_ix, n): \"\"\"",
"dhnext = np.zeros_like(hs[0]) for t in reversed(range(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -= 1",
"vocab_size = len(chars) print(f'data has {data_size} characters,{vocab_size} unique.') # data has 1109177 characters,80",
"200) txt = ''.join(ix_to_char[ix] for ix in sample_ix) print('----\\n %s \\n----' % (txt,",
"model. Written b_y <NAME> (@karpathy) BSD License \"\"\" import numpy as np import",
"smooth_loss * 0.999 + loss * 0.001 if n % 100 == 0:",
"dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update",
"seq_length # move data pointer n += 1 # iteration counter except KeyboardInterrupt:",
"forward pass for t in range(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k",
"(1 - hs[t] * hs[t]) * dh # backprop through tanh nonlinearity db_h",
"np.zeros((vocab_size, 1)) x[ix] = 1 ixes.append(ix) return ixes n, p = 0, 0",
"+ b_h) # hidden state ys[t] = np.dot(W_hy, hs[t]) + b_y # unnormalized",
"n == 0: hprev = np.zeros((hidden_size,1)) # reset RNN memory p = 0",
"= lossFun(inputs, targets, hprev) smooth_loss = smooth_loss * 0.999 + loss * 0.001",
"np.zeros_like(hs[0]) for t in reversed(range(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -= 1 # backprop",
"\"\"\" sample a sequence of integers from the model h is memory state,",
"iteration 0 while True: try: # prepare inputs (we're sweeping from left to",
"of b_y, same shape as b_y dhnext = np.zeros_like(hs[0]) for t in reversed(range(len(inputs))):",
"db_y, hs[len(inputs)-1] def sample(h, seed_ix, n): \"\"\" sample a sequence of integers from",
"memory variables for Adagrad smooth_loss = -np.log(1.0 / vocab_size) * seq_length # loss",
"# gradient of W_hh, same shape as W_hh dW_hy = np.zeros_like(W_hy) # gradient",
"seq_length = 128 # number of steps to unroll the RNN for learning_rate",
"= 1e-1 # model parameters W_xh = np.random.randn(hidden_size, vocab_size) * 0.01 # weight:",
"vector hs[t] = np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1]) + b_h) # hidden state",
"hyperparameters hidden_size = 256 # size of hidden layer of neurons seq_length =",
"to output b_h = np.zeros((hidden_size, 1)) # hidden bias b_y = np.zeros((vocab_size, 1))",
"index number, xs[t] is a vector hs[t] = np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1])",
"+ b_y p = np.exp(y) / np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel()) x =",
"= ys[t] = ps[t] size = vocab_size x 1 hs[-1] = np.copy(hprev) #",
"hidden to output b_h = np.zeros((hidden_size, 1)) # hidden bias b_y = np.zeros((vocab_size,",
"= np.zeros((vocab_size, 1)) # output bias def unicodeToAscii(s): return ''.join( c for c",
"db_h += dhraw dW_xh += np.dot(dhraw, xs[t].T) dW_hh += np.dot(dhraw, hs[t-1].T) dhnext =",
"hidden to hidden W_hy = np.random.randn(vocab_size, hidden_size) * 0.01 # weight: hidden to",
"x 1) array of initial hidden state returns the loss, gradients on model",
"the weights are reused, the states are different from each other. # forward",
"is a vector hs[t] = np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1]) + b_h) #",
"db_y]: np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients return loss,",
"= np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size, 1)) x[ix] = 1 ixes.append(ix) return ixes",
"sample_ix = sample(hprev, inputs[0], data_size) txt = ''.join(ix_to_char[ix] for ix in sample_ix) fake.write(txt)",
"are different from each other. # forward pass for t in range(len(inputs)): xs[t]",
"a vector hs[t] = np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1]) + b_h) # hidden",
"np.zeros((hidden_size,1)) # reset RNN memory p = 0 # go from start of",
"try: # prepare inputs (we're sweeping from left to right in steps seq_length",
"[char_to_ix[ch] for ch in data[p:p+seq_length]] targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] #",
"import codecs # data I/O data = codecs.open('data/potter.txt', 'r', encoding='utf8', errors='ignore').read() fake =",
"* 0.01 # weight: input to hidden W_hh = np.random.randn(hidden_size, hidden_size) * 0.01",
"integers indicating which unique character. inputs: a seq_length size list hprev is (H",
"counter except KeyboardInterrupt: sample_ix = sample(hprev, inputs[0], data_size) txt = ''.join(ix_to_char[ix] for ix",
"+ b_h) y = np.dot(W_hy, h) + b_y p = np.exp(y) / np.sum(np.exp(y))",
"1)) x[ix] = 1 ixes.append(ix) return ixes n, p = 0, 0 mW_xh,",
"or n == 0: hprev = np.zeros((hidden_size,1)) # reset RNN memory p =",
"xs[t]) + np.dot(W_hh, hs[t-1]) + b_h) # hidden state ys[t] = np.dot(W_hy, hs[t])",
"dW_hh, dW_hy, db_h, db_y, hprev = lossFun(inputs, targets, hprev) smooth_loss = smooth_loss *",
"in all_letters ) def lossFun(inputs, targets, hprev): \"\"\" inputs,targets are both list of",
"while True: try: # prepare inputs (we're sweeping from left to right in",
"+= 1 # iteration counter except KeyboardInterrupt: sample_ix = sample(hprev, inputs[0], data_size) txt",
"1 # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here dW_hy += np.dot(dy,",
"\"\"\" xs, hs, ys, ps = {}, {}, {}, {} # sx[t] =",
"a sequence of integers from the model h is memory state, seed_ix is",
"from the model h is memory state, seed_ix is seed letter for first",
"# data has 1109177 characters,80 unique. char_to_ix = { ch:i for i,ch in",
"np.copy(hprev) # hs[t] size = hidden_size * 1 loss = 0 # xs:",
"-= 1 # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here dW_hy +=",
"np.exp(ys[t]) / np.sum(np.exp(ys[t])) # (normalized) probabilities for next chars loss += -np.log(ps[t][targets[t],0]) #",
"hidden state \"\"\" xs, hs, ys, ps = {}, {}, {}, {} #",
"same shape as b_y dhnext = np.zeros_like(hs[0]) for t in reversed(range(len(inputs))): dy =",
"loss at iteration 0 while True: try: # prepare inputs (we're sweeping from",
"see http://cs231n.github.io/neural-networks-case-study/#grad if confused here dW_hy += np.dot(dy, hs[t].T) db_y += dy dh",
"= np.random.randn(hidden_size, vocab_size) * 0.01 # weight: input to hidden W_hh = np.random.randn(hidden_size,",
"input line; ys: output line; hs: hidden states, multiple of them, # even",
"# perform parameter update with Adagrad for param, dparam, mem in zip([W_xh, W_hh,",
"chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # (normalized) probabilities for next chars loss",
"= np.zeros_like(W_xh) # gradient of W_xh, same shape as W_xh dW_hh = np.zeros_like(W_hh)",
"even the weights are reused, the states are different from each other. #",
"steps to unroll the RNN for learning_rate = 1e-1 # model parameters W_xh",
"shape as W_hy db_h = np.zeros_like(b_h) # gradient of b_h, same shape as",
"backprop into h dhraw = (1 - hs[t] * hs[t]) * dh #",
"at iteration 0 while True: try: # prepare inputs (we're sweeping from left",
"W_xh = np.random.randn(hidden_size, vocab_size) * 0.01 # weight: input to hidden W_hh =",
"weights are reused, the states are different from each other. # forward pass",
"next chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # (normalized) probabilities for next chars",
"/ np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size, 1)) x[ix] = 1",
"memory p = 0 # go from start of data inputs = [char_to_ix[ch]",
"= np.dot(W_hy, h) + b_y p = np.exp(y) / np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size),",
"= 128 # number of steps to unroll the RNN for learning_rate =",
"txt = ''.join(ix_to_char[ix] for ix in sample_ix) print('----\\n %s \\n----' % (txt, ))",
"'r', encoding='utf8', errors='ignore').read() fake = codecs.open('data/output.txt', 'w', encoding='utf8') chars = list(set(data)) data_size =",
"hs[len(inputs)-1] def sample(h, seed_ix, n): \"\"\" sample a sequence of integers from the",
"for t in range(n): h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) + b_h)",
"hs, ys, ps = {}, {}, {}, {} # sx[t] = ys[t] =",
"p + seq_length + 1 >= len(data) or n == 0: hprev =",
"# hidden state ys[t] = np.dot(W_hy, hs[t]) + b_y # unnormalized log probabilities",
"np.dot(W_hh.T, dhraw) for dparam in [dW_xh, dW_hh, dW_hy, db_h, db_y]: np.clip(dparam, -5, 5,",
"(normalized) probabilities for next chars loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) print(f'loss:",
"mW_hy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h, mb_y = np.zeros_like(b_h), np.zeros_like(b_y) # memory variables",
"errors='ignore').read() fake = codecs.open('data/output.txt', 'w', encoding='utf8') chars = list(set(data)) data_size = len(data) #",
"list hprev is (H x 1) array of initial hidden state returns the",
"= np.zeros_like(hs[0]) for t in reversed(range(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -= 1 #",
"import unicodedata import string import codecs # data I/O data = codecs.open('data/potter.txt', 'r',",
"forward seq_length characters through the net and fetch gradient loss, dW_xh, dW_hh, dW_hy,",
"move data pointer n += 1 # iteration counter except KeyboardInterrupt: sample_ix =",
"W_hy, same shape as W_hy db_h = np.zeros_like(b_h) # gradient of b_h, same",
"ix = np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size, 1)) x[ix] = 1 ixes.append(ix) return",
"# backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here dW_hy += np.dot(dy, hs[t].T)",
"0 while True: try: # prepare inputs (we're sweeping from left to right",
"other. # forward pass for t in range(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode",
"size = hidden_size * 1 loss = 0 # xs: input line; ys:",
"x = np.zeros((vocab_size, 1)) x[seed_ix] = 1 ixes = [] for t in",
"update with Adagrad for param, dparam, mem in zip([W_xh, W_hh, W_hy, b_h, b_y],",
"x) + np.dot(W_hh, h) + b_h) y = np.dot(W_hy, h) + b_y p",
"sample from the model now and then if n % 100 == 0:",
"1e-1 # model parameters W_xh = np.random.randn(hidden_size, vocab_size) * 0.01 # weight: input",
"# even the weights are reused, the states are different from each other.",
"db_h, db_y, hs[len(inputs)-1] def sample(h, seed_ix, n): \"\"\" sample a sequence of integers",
"ys, ps = {}, {}, {}, {} # sx[t] = ys[t] = ps[t]",
"db_y], [mW_xh, mW_hh, mW_hy, mb_h, mb_y]): mem += dparam * dparam param +=",
"1 loss = 0 # xs: input line; ys: output line; hs: hidden",
"# adagrad update p += seq_length # move data pointer n += 1",
"b_h) # hidden state ys[t] = np.dot(W_hy, hs[t]) + b_y # unnormalized log",
"numpy as np import unicodedata import string import codecs # data I/O data",
"1) array of initial hidden state returns the loss, gradients on model parameters,",
"= np.zeros((hidden_size, 1)) # hidden bias b_y = np.zeros((vocab_size, 1)) # output bias",
"data inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]] targets = [char_to_ix[ch] for ch",
"= [char_to_ix[ch] for ch in data[p:p+seq_length]] targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]]",
"# loss at iteration 0 while True: try: # prepare inputs (we're sweeping",
"integers from the model h is memory state, seed_ix is seed letter for",
"then if n % 100 == 0: sample_ix = sample(hprev, inputs[0], 200) txt",
"% 100 == 0: sample_ix = sample(hprev, inputs[0], 200) txt = ''.join(ix_to_char[ix] for",
"of data inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]] targets = [char_to_ix[ch] for",
"chars = list(set(data)) data_size = len(data) # vocab_size = len(chars) print(f'data has {data_size}",
"b_y, same shape as b_y dhnext = np.zeros_like(hs[0]) for t in reversed(range(len(inputs))): dy",
"db_h, db_y], [mW_xh, mW_hh, mW_hy, mb_h, mb_y]): mem += dparam * dparam param",
"of steps to unroll the RNN for learning_rate = 1e-1 # model parameters",
"b_y <NAME> (@karpathy) BSD License \"\"\" import numpy as np import unicodedata import",
"for next chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # (normalized) probabilities for next",
"range(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation xs[t][inputs[t]] = 1 #",
"dy dh = np.dot(W_hy.T, dy) + dhnext # backprop into h dhraw =",
"True: try: # prepare inputs (we're sweeping from left to right in steps",
"ix in sample_ix) print('----\\n %s \\n----' % (txt, )) # forward seq_length characters",
"gradient of W_hh, same shape as W_hh dW_hy = np.zeros_like(W_hy) # gradient of",
"data[p+1:p+seq_length+1]] # sample from the model now and then if n % 100",
"fake = codecs.open('data/output.txt', 'w', encoding='utf8') chars = list(set(data)) data_size = len(data) # vocab_size",
"y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here dW_hy += np.dot(dy, hs[t].T) db_y += dy",
"dh = np.dot(W_hy.T, dy) + dhnext # backprop into h dhraw = (1",
"ixes = [] for t in range(n): h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh,",
"(txt, )) # forward seq_length characters through the net and fetch gradient loss,",
"data_size = len(data) # vocab_size = len(chars) print(f'data has {data_size} characters,{vocab_size} unique.') #",
"inputs[0], 200) txt = ''.join(ix_to_char[ix] for ix in sample_ix) print('----\\n %s \\n----' %",
"hidden state ys[t] = np.dot(W_hy, hs[t]) + b_y # unnormalized log probabilities for",
"= sample(hprev, inputs[0], 200) txt = ''.join(ix_to_char[ix] for ix in sample_ix) print('----\\n %s",
"# weight: hidden to output b_h = np.zeros((hidden_size, 1)) # hidden bias b_y",
"x 1 hs[-1] = np.copy(hprev) # hs[t] size = hidden_size * 1 loss",
"+ 1 >= len(data) or n == 0: hprev = np.zeros((hidden_size,1)) # reset",
"and last hidden state \"\"\" xs, hs, ys, ps = {}, {}, {},",
"0: hprev = np.zeros((hidden_size,1)) # reset RNN memory p = 0 # go",
"from the model now and then if n % 100 == 0: sample_ix",
"initial hidden state returns the loss, gradients on model parameters, and last hidden",
"ch in data[p:p+seq_length]] targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] # sample from",
"= np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1]) + b_h) # hidden state ys[t] =",
"for dparam in [dW_xh, dW_hh, dW_hy, db_h, db_y]: np.clip(dparam, -5, 5, out=dparam) #",
"* dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad",
"and fetch gradient loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hprev = lossFun(inputs, targets,",
"the loss, gradients on model parameters, and last hidden state \"\"\" xs, hs,",
"np.dot(W_hy, h) + b_y p = np.exp(y) / np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel())",
"for ch in data[p+1:p+seq_length+1]] # sample from the model now and then if",
"dh # backprop through tanh nonlinearity db_h += dhraw dW_xh += np.dot(dhraw, xs[t].T)",
"t in reversed(range(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -= 1 # backprop into y.",
"of W_xh, same shape as W_xh dW_hh = np.zeros_like(W_hh) # gradient of W_hh,",
"of W_hy, same shape as W_hy db_h = np.zeros_like(b_h) # gradient of b_h,",
"1-of-k representation xs[t][inputs[t]] = 1 # inputs[t] is a index number, xs[t] is",
"Vanilla RNN model. Written b_y <NAME> (@karpathy) BSD License \"\"\" import numpy as",
"# gradient of b_h, same shape as b_h db_y = np.zeros_like(b_y) # gradient",
"are reused, the states are different from each other. # forward pass for",
"+= np.dot(dhraw, xs[t].T) dW_hh += np.dot(dhraw, hs[t-1].T) dhnext = np.dot(W_hh.T, dhraw) for dparam",
"sweeping from left to right in steps seq_length long) if p + seq_length",
"I/O data = codecs.open('data/potter.txt', 'r', encoding='utf8', errors='ignore').read() fake = codecs.open('data/output.txt', 'w', encoding='utf8') chars",
"characters through the net and fetch gradient loss, dW_xh, dW_hh, dW_hy, db_h, db_y,",
"5, out=dparam) # clip to mitigate exploding gradients return loss, dW_xh, dW_hh, dW_hy,",
"from left to right in steps seq_length long) if p + seq_length +",
"np.zeros((vocab_size, 1)) x[seed_ix] = 1 ixes = [] for t in range(n): h",
"of initial hidden state returns the loss, gradients on model parameters, and last",
"seed letter for first time step i.e. do predictions :) \"\"\" x =",
"loss, gradients on model parameters, and last hidden state \"\"\" xs, hs, ys,",
"Minimal character-level Vanilla RNN model. Written b_y <NAME> (@karpathy) BSD License \"\"\" import",
"in enumerate(chars) } print(char_to_ix) print(ix_to_char) # hyperparameters hidden_size = 256 # size of",
"model parameters W_xh = np.random.randn(hidden_size, vocab_size) * 0.01 # weight: input to hidden",
"backwards dW_xh = np.zeros_like(W_xh) # gradient of W_xh, same shape as W_xh dW_hh",
"hidden layer of neurons seq_length = 128 # number of steps to unroll",
"t in range(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation xs[t][inputs[t]] =",
"hidden bias b_y = np.zeros((vocab_size, 1)) # output bias def unicodeToAscii(s): return ''.join(",
"dW_hy, db_h, db_y, hs[len(inputs)-1] def sample(h, seed_ix, n): \"\"\" sample a sequence of",
"dW_xh, dW_hh, dW_hy, db_h, db_y, hs[len(inputs)-1] def sample(h, seed_ix, n): \"\"\" sample a",
"the RNN for learning_rate = 1e-1 # model parameters W_xh = np.random.randn(hidden_size, vocab_size)",
"time step i.e. do predictions :) \"\"\" x = np.zeros((vocab_size, 1)) x[seed_ix] =",
"np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h) + b_h) y = np.dot(W_hy, h) + b_y",
"xs, hs, ys, ps = {}, {}, {}, {} # sx[t] = ys[t]",
"= np.copy(hprev) # hs[t] size = hidden_size * 1 loss = 0 #",
"def sample(h, seed_ix, n): \"\"\" sample a sequence of integers from the model",
"loss = 0 # xs: input line; ys: output line; hs: hidden states,",
"for ch in data[p:p+seq_length]] targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] # sample",
"hidden states, multiple of them, # even the weights are reused, the states",
"in steps seq_length long) if p + seq_length + 1 >= len(data) or",
"W_hy = np.random.randn(vocab_size, hidden_size) * 0.01 # weight: hidden to output b_h =",
"np.zeros((vocab_size,1)) # encode in 1-of-k representation xs[t][inputs[t]] = 1 # inputs[t] is a",
"# hyperparameters hidden_size = 256 # size of hidden layer of neurons seq_length",
"output line; hs: hidden states, multiple of them, # even the weights are",
"hs[t]) + b_y # unnormalized log probabilities for next chars ps[t] = np.exp(ys[t])",
"np.zeros_like(b_h) # gradient of b_h, same shape as b_h db_y = np.zeros_like(b_y) #",
"%s \\n----' % (txt, )) # forward seq_length characters through the net and",
"* dh # backprop through tanh nonlinearity db_h += dhraw dW_xh += np.dot(dhraw,",
"hs[t-1]) + b_h) # hidden state ys[t] = np.dot(W_hy, hs[t]) + b_y #",
"param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update p",
"states, multiple of them, # even the weights are reused, the states are",
"0: print(f'iter{n}, loss: {smooth_loss}') # print progress # perform parameter update with Adagrad",
"param, dparam, mem in zip([W_xh, W_hh, W_hy, b_h, b_y], [dW_xh, dW_hh, dW_hy, db_h,",
"string import codecs # data I/O data = codecs.open('data/potter.txt', 'r', encoding='utf8', errors='ignore').read() fake",
"sequence of integers from the model h is memory state, seed_ix is seed",
"np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h, mb_y = np.zeros_like(b_h), np.zeros_like(b_y) # memory variables for Adagrad",
"gradient of W_hy, same shape as W_hy db_h = np.zeros_like(b_h) # gradient of",
"inputs (we're sweeping from left to right in steps seq_length long) if p",
"# unnormalized log probabilities for next chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) #",
"returns the loss, gradients on model parameters, and last hidden state \"\"\" xs,",
"# (normalized) probabilities for next chars loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss)",
"= np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h, mb_y = np.zeros_like(b_h), np.zeros_like(b_y) # memory variables for",
"as W_hy db_h = np.zeros_like(b_h) # gradient of b_h, same shape as b_h",
"mW_hh, mW_hy, mb_h, mb_y]): mem += dparam * dparam param += -learning_rate *",
"hidden W_hh = np.random.randn(hidden_size, hidden_size) * 0.01 # weight: hidden to hidden W_hy",
"BSD License \"\"\" import numpy as np import unicodedata import string import codecs",
"* seq_length # loss at iteration 0 while True: try: # prepare inputs",
"print(f'iter{n}, loss: {smooth_loss}') # print progress # perform parameter update with Adagrad for",
"as W_hh dW_hy = np.zeros_like(W_hy) # gradient of W_hy, same shape as W_hy",
"b_h) y = np.dot(W_hy, h) + b_y p = np.exp(y) / np.sum(np.exp(y)) ix",
"W_hh dW_hy = np.zeros_like(W_hy) # gradient of W_hy, same shape as W_hy db_h",
"ps:{len(ps[t])}->{ps[t]}') # backward pass: compute gradients going backwards dW_xh = np.zeros_like(W_xh) # gradient",
"hs[t] * hs[t]) * dh # backprop through tanh nonlinearity db_h += dhraw",
"xs[t].T) dW_hh += np.dot(dhraw, hs[t-1].T) dhnext = np.dot(W_hh.T, dhraw) for dparam in [dW_xh,",
"size = vocab_size x 1 hs[-1] = np.copy(hprev) # hs[t] size = hidden_size",
"np import unicodedata import string import codecs # data I/O data = codecs.open('data/potter.txt',",
"p = 0 # go from start of data inputs = [char_to_ix[ch] for",
"ys: output line; hs: hidden states, multiple of them, # even the weights",
"= 1 ixes = [] for t in range(n): h = np.tanh(np.dot(W_xh, x)",
"/ np.sqrt(mem + 1e-8) # adagrad update p += seq_length # move data",
"np.zeros_like(b_y) # gradient of b_y, same shape as b_y dhnext = np.zeros_like(hs[0]) for",
"128 # number of steps to unroll the RNN for learning_rate = 1e-1",
"dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) #",
"data I/O data = codecs.open('data/potter.txt', 'r', encoding='utf8', errors='ignore').read() fake = codecs.open('data/output.txt', 'w', encoding='utf8')",
"mb_h, mb_y = np.zeros_like(b_h), np.zeros_like(b_y) # memory variables for Adagrad smooth_loss = -np.log(1.0",
"mb_y = np.zeros_like(b_h), np.zeros_like(b_y) # memory variables for Adagrad smooth_loss = -np.log(1.0 /",
"y = np.dot(W_hy, h) + b_y p = np.exp(y) / np.sum(np.exp(y)) ix =",
"[dW_xh, dW_hh, dW_hy, db_h, db_y], [mW_xh, mW_hh, mW_hy, mb_h, mb_y]): mem += dparam",
"iteration counter except KeyboardInterrupt: sample_ix = sample(hprev, inputs[0], data_size) txt = ''.join(ix_to_char[ix] for",
"characters,80 unique. char_to_ix = { ch:i for i,ch in enumerate(chars) } ix_to_char =",
"hprev): \"\"\" inputs,targets are both list of integers indicating which unique character. inputs:",
"100 == 0: sample_ix = sample(hprev, inputs[0], 200) txt = ''.join(ix_to_char[ix] for ix",
"unnormalized log probabilities for next chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # (normalized)",
"np.zeros((vocab_size, 1)) # output bias def unicodeToAscii(s): return ''.join( c for c in",
"0, 0 mW_xh, mW_hh, mW_hy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h, mb_y = np.zeros_like(b_h),",
"np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients return loss, dW_xh,",
"net and fetch gradient loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hprev = lossFun(inputs,",
"perform parameter update with Adagrad for param, dparam, mem in zip([W_xh, W_hh, W_hy,",
"targets, hprev): \"\"\" inputs,targets are both list of integers indicating which unique character.",
"ch:i for i,ch in enumerate(chars) } ix_to_char = { i:ch for i,ch in",
"ys[t] = ps[t] size = vocab_size x 1 hs[-1] = np.copy(hprev) # hs[t]",
"i:ch for i,ch in enumerate(chars) } print(char_to_ix) print(ix_to_char) # hyperparameters hidden_size = 256",
"ixes.append(ix) return ixes n, p = 0, 0 mW_xh, mW_hh, mW_hy = np.zeros_like(W_xh),",
"next chars loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) print(f'loss: {loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n",
"len(chars) print(f'data has {data_size} characters,{vocab_size} unique.') # data has 1109177 characters,80 unique. char_to_ix",
"= 0, 0 mW_xh, mW_hh, mW_hy = np.zeros_like(W_xh), np.zeros_like(W_hh), np.zeros_like(W_hy) mb_h, mb_y =",
"print progress # perform parameter update with Adagrad for param, dparam, mem in",
"License \"\"\" import numpy as np import unicodedata import string import codecs #",
"line; ys: output line; hs: hidden states, multiple of them, # even the",
"db_h, db_y, hprev = lossFun(inputs, targets, hprev) smooth_loss = smooth_loss * 0.999 +",
"import numpy as np import unicodedata import string import codecs # data I/O",
"seq_length long) if p + seq_length + 1 >= len(data) or n ==",
"shape as W_hh dW_hy = np.zeros_like(W_hy) # gradient of W_hy, same shape as",
"loss: {smooth_loss}') # print progress # perform parameter update with Adagrad for param,",
"in enumerate(chars) } ix_to_char = { i:ch for i,ch in enumerate(chars) } print(char_to_ix)",
"# size of hidden layer of neurons seq_length = 128 # number of",
"log probabilities for next chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # (normalized) probabilities",
"loss * 0.001 if n % 100 == 0: print(f'iter{n}, loss: {smooth_loss}') #",
"dhraw dW_xh += np.dot(dhraw, xs[t].T) dW_hh += np.dot(dhraw, hs[t-1].T) dhnext = np.dot(W_hh.T, dhraw)",
"+ dhnext # backprop into h dhraw = (1 - hs[t] * hs[t])",
"np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size, 1)) x[ix] = 1 ixes.append(ix)",
"1)) x[seed_ix] = 1 ixes = [] for t in range(n): h =",
"ps[t] size = vocab_size x 1 hs[-1] = np.copy(hprev) # hs[t] size =",
"Written b_y <NAME> (@karpathy) BSD License \"\"\" import numpy as np import unicodedata",
"in data[p:p+seq_length]] targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] # sample from the",
"+ 1e-8) # adagrad update p += seq_length # move data pointer n",
"b_y p = np.exp(y) / np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size,",
">= len(data) or n == 0: hprev = np.zeros((hidden_size,1)) # reset RNN memory",
"data has 1109177 characters,80 unique. char_to_ix = { ch:i for i,ch in enumerate(chars)",
"encoding='utf8', errors='ignore').read() fake = codecs.open('data/output.txt', 'w', encoding='utf8') chars = list(set(data)) data_size = len(data)",
"is memory state, seed_ix is seed letter for first time step i.e. do",
")) # forward seq_length characters through the net and fetch gradient loss, dW_xh,",
"hprev) smooth_loss = smooth_loss * 0.999 + loss * 0.001 if n %",
"W_hy, b_h, b_y], [dW_xh, dW_hh, dW_hy, db_h, db_y], [mW_xh, mW_hh, mW_hy, mb_h, mb_y]):",
"as W_xh dW_hh = np.zeros_like(W_hh) # gradient of W_hh, same shape as W_hh",
"adagrad update p += seq_length # move data pointer n += 1 #",
"a index number, xs[t] is a vector hs[t] = np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh,",
"loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) print(f'loss: {loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n",
"hprev = np.zeros((hidden_size,1)) # reset RNN memory p = 0 # go from",
"as b_y dhnext = np.zeros_like(hs[0]) for t in reversed(range(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]]",
"[dW_xh, dW_hh, dW_hy, db_h, db_y]: np.clip(dparam, -5, 5, out=dparam) # clip to mitigate",
"dW_hh, dW_hy, db_h, db_y, hs[len(inputs)-1] def sample(h, seed_ix, n): \"\"\" sample a sequence",
"last hidden state \"\"\" xs, hs, ys, ps = {}, {}, {}, {}",
"b_h db_y = np.zeros_like(b_y) # gradient of b_y, same shape as b_y dhnext",
"= list(set(data)) data_size = len(data) # vocab_size = len(chars) print(f'data has {data_size} characters,{vocab_size}",
"# gradient of W_xh, same shape as W_xh dW_hh = np.zeros_like(W_hh) # gradient",
"0 # xs: input line; ys: output line; hs: hidden states, multiple of",
"out=dparam) # clip to mitigate exploding gradients return loss, dW_xh, dW_hh, dW_hy, db_h,",
"mem in zip([W_xh, W_hh, W_hy, b_h, b_y], [dW_xh, dW_hh, dW_hy, db_h, db_y], [mW_xh,",
"hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') # backward pass: compute gradients going backwards dW_xh = np.zeros_like(W_xh)",
"mb_y]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem",
"* dparam / np.sqrt(mem + 1e-8) # adagrad update p += seq_length #",
"* 0.999 + loss * 0.001 if n % 100 == 0: print(f'iter{n},",
"sx[t] = ys[t] = ps[t] size = vocab_size x 1 hs[-1] = np.copy(hprev)",
"= np.zeros_like(b_h) # gradient of b_h, same shape as b_h db_y = np.zeros_like(b_y)",
"= np.zeros_like(b_h), np.zeros_like(b_y) # memory variables for Adagrad smooth_loss = -np.log(1.0 / vocab_size)",
"0: sample_ix = sample(hprev, inputs[0], 200) txt = ''.join(ix_to_char[ix] for ix in sample_ix)",
"# xs: input line; ys: output line; hs: hidden states, multiple of them,",
"ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') # backward pass: compute gradients going backwards dW_xh = np.zeros_like(W_xh) #",
"(cross-entropy loss) print(f'loss: {loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') # backward pass: compute",
"left to right in steps seq_length long) if p + seq_length + 1",
"gradient loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hprev = lossFun(inputs, targets, hprev) smooth_loss",
"to hidden W_hy = np.random.randn(vocab_size, hidden_size) * 0.01 # weight: hidden to output",
"dW_hy = np.zeros_like(W_hy) # gradient of W_hy, same shape as W_hy db_h =",
"len(data) or n == 0: hprev = np.zeros((hidden_size,1)) # reset RNN memory p",
"1 >= len(data) or n == 0: hprev = np.zeros((hidden_size,1)) # reset RNN",
"= smooth_loss * 0.999 + loss * 0.001 if n % 100 ==",
"dparam / np.sqrt(mem + 1e-8) # adagrad update p += seq_length # move",
"sample(hprev, inputs[0], data_size) txt = ''.join(ix_to_char[ix] for ix in sample_ix) fake.write(txt) break fake.close()",
"to mitigate exploding gradients return loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hs[len(inputs)-1] def",
"# go from start of data inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]]",
"n % 100 == 0: sample_ix = sample(hprev, inputs[0], 200) txt = ''.join(ix_to_char[ix]",
"h is memory state, seed_ix is seed letter for first time step i.e.",
"hs[t].T) db_y += dy dh = np.dot(W_hy.T, dy) + dhnext # backprop into",
"hprev is (H x 1) array of initial hidden state returns the loss,",
"1 # inputs[t] is a index number, xs[t] is a vector hs[t] =",
"do predictions :) \"\"\" x = np.zeros((vocab_size, 1)) x[seed_ix] = 1 ixes =",
"* 0.01 # weight: hidden to output b_h = np.zeros((hidden_size, 1)) # hidden",
"0.01 # weight: hidden to output b_h = np.zeros((hidden_size, 1)) # hidden bias",
"print(char_to_ix) print(ix_to_char) # hyperparameters hidden_size = 256 # size of hidden layer of",
"{}, {} # sx[t] = ys[t] = ps[t] size = vocab_size x 1",
"a seq_length size list hprev is (H x 1) array of initial hidden",
"if unicodedata.category(c) != 'Mn' and c in all_letters ) def lossFun(inputs, targets, hprev):",
"!= 'Mn' and c in all_letters ) def lossFun(inputs, targets, hprev): \"\"\" inputs,targets",
"= hidden_size * 1 loss = 0 # xs: input line; ys: output",
"-np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) print(f'loss: {loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') #",
"codecs.open('data/potter.txt', 'r', encoding='utf8', errors='ignore').read() fake = codecs.open('data/output.txt', 'w', encoding='utf8') chars = list(set(data)) data_size",
"= [] for t in range(n): h = np.tanh(np.dot(W_xh, x) + np.dot(W_hh, h)",
"p=p.ravel()) x = np.zeros((vocab_size, 1)) x[ix] = 1 ixes.append(ix) return ixes n, p",
"b_y # unnormalized log probabilities for next chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t]))",
"unique. char_to_ix = { ch:i for i,ch in enumerate(chars) } ix_to_char = {",
"x[ix] = 1 ixes.append(ix) return ixes n, p = 0, 0 mW_xh, mW_hh,",
"print('----\\n %s \\n----' % (txt, )) # forward seq_length characters through the net",
"in zip([W_xh, W_hh, W_hy, b_h, b_y], [dW_xh, dW_hh, dW_hy, db_h, db_y], [mW_xh, mW_hh,",
"# iteration counter except KeyboardInterrupt: sample_ix = sample(hprev, inputs[0], data_size) txt = ''.join(ix_to_char[ix]",
"+= -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) print(f'loss: {loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}')",
"{ ch:i for i,ch in enumerate(chars) } ix_to_char = { i:ch for i,ch",
"vocab_size) * 0.01 # weight: input to hidden W_hh = np.random.randn(hidden_size, hidden_size) *",
"= 1 # inputs[t] is a index number, xs[t] is a vector hs[t]",
"to unroll the RNN for learning_rate = 1e-1 # model parameters W_xh =",
"prepare inputs (we're sweeping from left to right in steps seq_length long) if",
"(@karpathy) BSD License \"\"\" import numpy as np import unicodedata import string import",
"np.random.randn(hidden_size, hidden_size) * 0.01 # weight: hidden to hidden W_hy = np.random.randn(vocab_size, hidden_size)",
"parameter update with Adagrad for param, dparam, mem in zip([W_xh, W_hh, W_hy, b_h,",
"seq_length size list hprev is (H x 1) array of initial hidden state",
"xs[t] is a vector hs[t] = np.tanh(np.dot(W_xh, xs[t]) + np.dot(W_hh, hs[t-1]) + b_h)",
"= 1 ixes.append(ix) return ixes n, p = 0, 0 mW_xh, mW_hh, mW_hy",
"right in steps seq_length long) if p + seq_length + 1 >= len(data)",
"# forward seq_length characters through the net and fetch gradient loss, dW_xh, dW_hh,",
"n % 100 == 0: print(f'iter{n}, loss: {smooth_loss}') # print progress # perform",
"neurons seq_length = 128 # number of steps to unroll the RNN for",
"p += seq_length # move data pointer n += 1 # iteration counter",
"go from start of data inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]] targets",
"h) + b_h) y = np.dot(W_hy, h) + b_y p = np.exp(y) /",
"of b_h, same shape as b_h db_y = np.zeros_like(b_y) # gradient of b_y,",
"which unique character. inputs: a seq_length size list hprev is (H x 1)",
"is a index number, xs[t] is a vector hs[t] = np.tanh(np.dot(W_xh, xs[t]) +",
"len(data) # vocab_size = len(chars) print(f'data has {data_size} characters,{vocab_size} unique.') # data has",
"layer of neurons seq_length = 128 # number of steps to unroll the",
"+= dy dh = np.dot(W_hy.T, dy) + dhnext # backprop into h dhraw",
"state, seed_ix is seed letter for first time step i.e. do predictions :)",
"model now and then if n % 100 == 0: sample_ix = sample(hprev,",
"seq_length # loss at iteration 0 while True: try: # prepare inputs (we're",
"mitigate exploding gradients return loss, dW_xh, dW_hh, dW_hy, db_h, db_y, hs[len(inputs)-1] def sample(h,",
"codecs.open('data/output.txt', 'w', encoding='utf8') chars = list(set(data)) data_size = len(data) # vocab_size = len(chars)",
"bias def unicodeToAscii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c)",
"/ vocab_size) * seq_length # loss at iteration 0 while True: try: #",
"1109177 characters,80 unique. char_to_ix = { ch:i for i,ch in enumerate(chars) } ix_to_char",
"progress # perform parameter update with Adagrad for param, dparam, mem in zip([W_xh,",
"= -np.log(1.0 / vocab_size) * seq_length # loss at iteration 0 while True:",
") def lossFun(inputs, targets, hprev): \"\"\" inputs,targets are both list of integers indicating",
"same shape as b_h db_y = np.zeros_like(b_y) # gradient of b_y, same shape",
"unicodedata.category(c) != 'Mn' and c in all_letters ) def lossFun(inputs, targets, hprev): \"\"\"",
"xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation xs[t][inputs[t]] = 1 # inputs[t]",
"db_h, db_y]: np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients return",
"loss) print(f'loss: {loss}') # print(f'xs:{len(xs[t])}->{xs[t]}\\n hs:{len(hs[t])}->{hs[t]}\\n ys:{len(ys[t])}->{ys[t]}\\n ps:{len(ps[t])}->{ps[t]}') # backward pass: compute gradients",
"1e-8) # adagrad update p += seq_length # move data pointer n +=",
"= np.zeros((vocab_size,1)) # encode in 1-of-k representation xs[t][inputs[t]] = 1 # inputs[t] is",
"size of hidden layer of neurons seq_length = 128 # number of steps",
"# hs[t] size = hidden_size * 1 loss = 0 # xs: input",
"Adagrad smooth_loss = -np.log(1.0 / vocab_size) * seq_length # loss at iteration 0"
] |
[
"(UTILITIES) DESCRIPTION ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION Series of functions",
"FLYCOP run (configuration) as a single str line - extract_ratios ANALYSIS OF BIOMASS",
"row[0] = Index Number ref_variable = dataframe.loc[row[0], ref_column] for i in range(1, len(rank_limits_set)+1):",
"----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE FITNESS RANKS",
":'fitness' - frac_dataframe: fraction of a particular dataframe - descr_columns: columns to be",
"rank_tuple = rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"] = int(i)",
"3) Ec_init = float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) NH4_Ec =",
"float(list_line[5]) NH4_Ec_KT = round(NH4_Ec/NH4_KT, 3) # Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7])",
"# ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) #",
"Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # Sucrose/ fructose uptake rates",
"TWO LAST FUNCTIONS # 1. Obtains every single fitness rank # 2. Makes",
"to E.coli_iEC1364-P.putida_KT2440 configuration: # Sucrose/ fructose uptake rates ratio # E.coli/ P.putida KT",
"rank_tuple[1]: dataframe.loc[row[0], new_column] = str(rank_tuple) break return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- #",
"def extract_baseConfig_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[3]) Ec_init =",
"# FUNCTION TO: obtain the initial cycle for death effect, from the dataframe",
"----------------------------------------------------------------------------- # EXTRACT INPUT PARAMETERS FOR FLYCOP run (configuration) as a single str",
"utf-8 -*- \"\"\" Created on Sun Feb 21 21:20:59 2021 @author: <NAME> \"\"\"",
"= 0 for row in dataframe.itertuples(): DT_cycles = dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init = DT_cycles[0]",
"rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\")",
"scripts related to Statistical Analysis). - obtain_fitness_rank - stats_description - describe_fitness_ranks: combination of",
"ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION Series of functions to define",
"Default :'fitness' - frac_dataframe: fraction of a particular dataframe - descr_columns: columns to",
"of the dataframe. Default :'fitness' - frac_dataframe: fraction of a particular dataframe -",
"fraction of the dataframe. Default :'fitness' - frac_dataframe: fraction of a particular dataframe",
".describe()) - string_line_config. Example: -8.0,0.3,-12.0,0.05 OUTPUT See each particular function NOTE THAT: Script",
"Sun Feb 21 21:20:59 2021 @author: <NAME> \"\"\" \"\"\" OUTPUT ANALYSIS AFTER FLYCOP",
"run) # ----------------------------------------------------------------------------- # DEFINE FITNESS RANKS (new column 'FitRank') for the Individual",
"ANALYSIS AFTER FLYCOP (UTILITIES) DESCRIPTION ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION",
"dataframe.itertuples(): # row[0] = Index Number ref_variable = dataframe.loc[row[0], ref_column] for i in",
"ratios of each fitness rank in FLYCOP output tables def organize_fitness_ranks(dataframe, rank_limits_set, ref_column):",
"2. Makes the subsequent statistical description def describe_fitness_ranks(rank_limits_set, dataframe, descr_columns, ref_column): # 'SAVE",
"# ----------------------------------------------------------------------------- # FUNCTION TO: obtain the initial cycle for death effect, from",
"range(1, len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"]",
"dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\" # 'PRINT' version for rank_limits_tuple",
"\"\"\" # 'PRINT' version for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column)",
"LIMITACIONES # ------------ # Limitación: el primero de los rangos, hay que pasarle",
"3) NH4_Ec = float(list_line[4]) NH4_KT = float(list_line[5]) NH4_Ec_KT = round(NH4_Ec/NH4_KT, 3) # Pi_Ec",
"STATISTICAL DESCRIPTION for the selected fitness rank, columns selected # descr_columns are those",
"would \"sum 0\" (to the numerator) # TO-DO: further implementation / reorganization of",
"# RETURNS FRACTION OF INTEREST (fitness rank, all columns) OF THE DATAFRAME #",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on Sun Feb 21",
"(configuration) as a single str line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440",
"# account (in the denominator) and those with no biomass loss would \"sum",
"rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"] = int(i) break elif",
"fitness interval itself def organize_ranks(dataframe, rank_limits_set, ref_column, new_column): for row in dataframe.itertuples(): #",
"= float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur, 3) Ec_init = float(list_line[1]) KT_init",
"input parameters) - organize_fitness_ranks EXTRACT INPUT PARAMETERS FOR A FLYCOP run (configuration) as",
"else: dataframe.loc[row[0] , \"FitRank\"] = -1 return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- #",
"a given simulation) EXPECTED INPUT - Dataframe: dataframe to be processed - rank_limits_set:",
"-4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio",
"round(Ec_init/KT_init, 3) return uptake_ratio, initbiomass_ratio # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF",
"intervals) - rank_limits: smaller tuple (fitness rank individual interval) - ref_colum: reference column",
"if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"] = int(i) break elif ref_variable",
"# The ranks are defined based on the desired 'ref_column' in the given",
"ASSOCIATED STATS DESCRIPTION # ----------------------------------------------------------------------------- # RETURNS FRACTION OF INTEREST (fitness rank, all",
"- frac_dataframe: fraction of a particular dataframe - descr_columns: columns to be described",
"Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) # Pi_Ec_KT = round(Pi_Ec/Pi_KT, 3) return",
"related information (rest of the parameters) def obtain_fitness_rank(rank_limits, dataframe, ref_colum): frac_dataframe = dataframe[dataframe[ref_colum]",
"as stats_file: for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr =",
"particular dataframe - descr_columns: columns to be described with 'Pandas' statistical description (method",
"estadístico a archivo para posterior 'ComparativeAnalysis' entre configuraciones # Array 3D # -----------------------------------------------------------------------------",
"within each FLYCOP run # The ranks are defined based on the desired",
"# Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def",
"(to the numerator) # TO-DO: further implementation / reorganization of code lines #",
"Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config):",
"every single fitness rank # 2. Makes the subsequent statistical description def describe_fitness_ranks(rank_limits_set,",
"'Pandas' statistical description (method .describe()) - string_line_config. Example: -8.0,0.3,-12.0,0.05 OUTPUT See each particular",
"KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) return uptake_ratio, initbiomass_ratio # ----------------------------------------------------------------------------- #",
"if wanted to be stored in a file \"\"\" filename = \"stats_description.txt\" #",
"ConfigError == 0: dataframe.loc[row[0] , \"FitRank\"] = 0 else: dataframe.loc[row[0] , \"FitRank\"] =",
"where to operate (pandas dataframe) # OUTPUT: same dataframe with new column: #",
"Script in development (...) \"\"\" # import re # import pandas as pd",
"= DT_cycles[0] if DT_cycles_init != \"NoDeadTracking\": dataframe.loc[row[0], \"DT_cycles_init\"] = int(DT_cycles_init) return dataframe #",
"def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] = 0 for row in dataframe.itertuples(): DT_cycles = dataframe.loc[row[0], \"DT_cycles\"].split(\"-\")",
"# NUEVA IDEA: llevar análisis estadístico a archivo para posterior 'ComparativeAnalysis' entre configuraciones",
"selected # descr_columns are those columns (parameters) for which the statistical description is",
"ranks # Instead of a number, the fitness interval itself def organize_ranks(dataframe, rank_limits_set,",
"# descr_columns are those columns (parameters) for which the statistical description is required",
"ASSOCIATED STATS DESCRIPTION Series of functions to define and process fitness ranks (utility",
"ratio # EXAMPLE: -8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur",
"INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE RANKS (new column) for",
"obtain_fitness_rank - stats_description - describe_fitness_ranks: combination of the last two functions INDIVIDUAL COMPARATIVE",
"KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) NH4_Ec = float(list_line[4]) NH4_KT = float(list_line[5])",
"of code lines # ----------------------------------------------------------------------------- def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] = 0 for row in",
"Pi uptake ratio (E.coli/P.putida) # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur",
"0 for row in dataframe.itertuples(): DT_cycles = dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init = DT_cycles[0] if",
"rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) print(f\"{ref_column}",
"statistical description def describe_fitness_ranks(rank_limits_set, dataframe, descr_columns, ref_column): # 'SAVE STATS' version, if wanted",
"NH4_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # FUNCTION TO: obtain the initial cycle for",
"effect (initial cycle) was computed, all configurations would be taken into # account",
"obtain the initial cycle for death effect, from the dataframe where it has",
"(method .describe()) - string_line_config. Example: -8.0,0.3,-12.0,0.05 OUTPUT See each particular function NOTE THAT:",
"ratio (E.coli/P.putida) # Pi uptake ratio (E.coli/P.putida) # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config): list_line",
"archivo para posterior 'ComparativeAnalysis' entre configuraciones # Array 3D # ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------",
"in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) print(f\"{ref_column} rank:",
"= string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[3]) Ec_init = float(list_line[1]) # Ec_init_glyc",
"the death effect (initial cycle) was computed, all configurations would be taken into",
"if ConfigError == 0: dataframe.loc[row[0] , \"FitRank\"] = 0 else: dataframe.loc[row[0] , \"FitRank\"]",
"of values, depending on the established ranks # Instead of a number, the",
"TO: obtain the initial cycle for death effect, from the dataframe where it",
"is no death effect, thus the value for 'DT_cycles_init' is 0. # If",
"Pi_KT = float(list_line[7]) # Pi_Ec_KT = round(Pi_Ec/Pi_KT, 3) return uptake_ratio, initbiomass_ratio, NH4_Ec_KT #",
"of a particular dataframe - descr_columns: columns to be described with 'Pandas' statistical",
"with no biomass loss would \"sum 0\" (to the numerator) # TO-DO: further",
"= float(list_line[7]) # Pi_Ec_KT = round(Pi_Ec/Pi_KT, 3) return uptake_ratio, initbiomass_ratio, NH4_Ec_KT # -----------------------------------------------------------------------------",
"= -1 return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP",
"E.coli_iEC1364-P.putida_KT2440 configuration: # Sucrose/ fructose uptake rates ratio # E.coli/ P.putida KT initial",
"print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print() # LIMITACIONES # ------------ # Limitación: el primero",
"'DT_cycles_init': cycle when dead effect starts # NOTE THAT: \"NoDeadTracking\" means there is",
"PARAMETERS FOR A FLYCOP run (configuration) as a single str line - extract_ratios",
"with open(filename, \"w\") as stats_file: for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe,",
"tuples (fitness rank intervals) - rank_limits: smaller tuple (fitness rank individual interval) -",
"def extract_ratios_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio =",
"and process fitness ranks (utility for scripts related to Statistical Analysis). - obtain_fitness_rank",
"are defined based on the desired 'ref_column' in the given dataframe # 'New_column'",
"'SAVE STATS' version, if wanted to be stored in a file \"\"\" filename",
"# EXTRACT INPUT PARAMETERS FOR FLYCOP run (configuration) as a single str line",
"str(rank_tuple) break return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT",
"description is required def stats_description(frac_dataframe, descr_columns): stat_description = frac_dataframe[descr_columns].describe() return stat_description # COMBINES",
"those columns (parameters) for which the statistical description is required def stats_description(frac_dataframe, descr_columns):",
"where it has previously registered # INPUT: dataframe where to operate (pandas dataframe)",
"import os.path # ----------------------------------------------------------------------------- # ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION",
"NOTE THAT: \"NoDeadTracking\" means there is no death effect, thus the value for",
"Set con tuplas para los rangos # NUEVA IDEA: llevar análisis estadístico a",
"de los fitness # Limitación: ¿cómo haríamos cálculos individuales de un único parámetro",
"- descr_columns: columns to be described with 'Pandas' statistical description (method .describe()) -",
"rank # 2. Makes the subsequent statistical description def describe_fitness_ranks(rank_limits_set, dataframe, descr_columns, ref_column):",
"for the Individual Comparative Analysis within each FLYCOP run # Utility required for",
"\"FitRank\"] = -1 return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS",
"this effect is first registered in a given simulation) EXPECTED INPUT - Dataframe:",
"IDEA: llevar análisis estadístico a archivo para posterior 'ComparativeAnalysis' entre configuraciones # Array",
"contains the categorical classification of values, depending on the established ranks # Instead",
"tuple (fitness rank individual interval) - ref_colum: reference column to extract the fraction",
"dataframe, ref_colum): frac_dataframe = dataframe[dataframe[ref_colum] < rank_limits[1]] # Higher limit final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum]",
"descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\" # 'PRINT' version for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple,",
"fraction of a particular dataframe - descr_columns: columns to be described with 'Pandas'",
"a single str line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with",
"OUTPUT: same dataframe with new column: # 'DT_cycles_init': cycle when dead effect starts",
"ref_variable < rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"] = int(i) break elif ref_variable == 0: ConfigError",
"# Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # Sucrose/ fructose uptake",
"float(list_line[7]) return sucr_ur, frc_ur, Ec_init, KT_init, NH4_Ec, NH4_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- #",
"dataframe.loc[row[0] , \"FitRank\"] = -1 return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL",
"operate (pandas dataframe) # OUTPUT: same dataframe with new column: # 'DT_cycles_init': cycle",
"- Dataframe: dataframe to be processed - rank_limits_set: tuple with a series of",
"(parameters) for which the statistical description is required def stats_description(frac_dataframe, descr_columns): stat_description =",
"the established ranks # Instead of a number, the fitness interval itself def",
"the initial cycle for death effect, from the dataframe where it has previously",
"'PRINT' version for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr =",
"# -*- coding: utf-8 -*- \"\"\" Created on Sun Feb 21 21:20:59 2021",
"DEFINE RANKS (new column) for the Individual Comparative Analysis within each FLYCOP run",
"INPUT PARAMETERS FOR A FLYCOP run (configuration) as a single str line -",
"initial biomass ratio # NH4 uptake ratio (E.coli/P.putida) # Pi uptake ratio (E.coli/P.putida)",
"DEFINE FITNESS RANKS (new column 'FitRank') for the Individual Comparative Analysis within each",
"the denominator) and those with no biomass loss would \"sum 0\" (to the",
"single fitness rank # 2. Makes the subsequent statistical description def describe_fitness_ranks(rank_limits_set, dataframe,",
"# Pi_KT = float(list_line[7]) return sucr_ur, frc_ur, Ec_init, KT_init, NH4_Ec, NH4_KT # -----------------------------------------------------------------------------",
"(...) \"\"\" # import re # import pandas as pd # import os.path",
"ref_variable = dataframe.loc[row[0], ref_column] for i in range(1, len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if",
"there is no death effect, thus the value for 'DT_cycles_init' is 0. #",
"for the selected fitness rank, columns selected # descr_columns are those columns (parameters)",
"is first registered in a given simulation) EXPECTED INPUT - Dataframe: dataframe to",
"# INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE RANKS (new column)",
"= dataframe.loc[row[0], ref_column] for i in range(1, len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if rank_tuple[0]",
"float(list_line[5]) NH4_KT = float(list_line[6]) # Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) return",
"as a single str line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration:",
"# EXAMPLE: -8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur =",
"ANALYSIS (FLYCOP run) Define fitness ranks for the Individual Comparative Analysis (FLYCOP run,",
"Dataframe: dataframe to be processed - rank_limits_set: tuple with a series of inner",
"tuple with a series of inner tuples (fitness rank intervals) - rank_limits: smaller",
"un límite superior más alto que el mejor de los fitness # Limitación:",
"numerator) # TO-DO: further implementation / reorganization of code lines # ----------------------------------------------------------------------------- def",
"len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"] =",
"required def stats_description(frac_dataframe, descr_columns): stat_description = frac_dataframe[descr_columns].describe() return stat_description # COMBINES THE TWO",
"be processed - rank_limits_set: tuple with a series of inner tuples (fitness rank",
"ref_variable < rank_tuple[1]: dataframe.loc[row[0], new_column] = str(rank_tuple) break return dataframe # ----------------------------------------------------------------------------- #",
"análisis estadístico a archivo para posterior 'ComparativeAnalysis' entre configuraciones # Array 3D #",
"the Individual Comparative Analysis within each FLYCOP run # Utility required for further",
"combination of the last two functions INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) Define fitness",
"INTEREST (fitness rank, all columns) OF THE DATAFRAME # For a fitness interval,",
"ranks are defined based on the desired 'ref_column' in the given dataframe #",
"median() (individualmente) # AUTOMATIZAR # ------------------------------- # Set con tuplas para los rangos",
"def organize_fitness_ranks(dataframe, rank_limits_set, ref_column): for row in dataframe.itertuples(): # row[0] = Index Number",
"specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config): list_line",
"= dataframe[dataframe[ref_colum] < rank_limits[1]] # Higher limit final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]] #",
"Sucrose/ fructose uptake rates ratio # E.coli/ P.putida KT initial biomass ratio #",
"DESCRIPTION for the selected fitness rank, columns selected # descr_columns are those columns",
"ratio # NH4 uptake ratio (E.coli/P.putida) # Pi uptake ratio (E.coli/P.putida) # EXAMPLE:",
"a particular dataframe - descr_columns: columns to be described with 'Pandas' statistical description",
"rangos, hay que pasarle un límite superior más alto que el mejor de",
"rank_limits_set, ref_column): for row in dataframe.itertuples(): # row[0] = Index Number ref_variable =",
"el mejor de los fitness # Limitación: ¿cómo haríamos cálculos individuales de un",
"# DEFINE FITNESS RANKS (new column 'FitRank') for the Individual Comparative Analysis within",
"sucr_ur = float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur, 3) Ec_init = float(list_line[1])",
"and those with no biomass loss would \"sum 0\" (to the numerator) #",
"string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur, 3) Ec_init =",
"----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT INPUT PARAMETERS FOR FLYCOP run (configuration) as a",
"single str line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration: # Sucrose/",
"version, if wanted to be stored in a file \"\"\" filename = \"stats_description.txt\"",
"# STATISTICAL DESCRIPTION for the selected fitness rank, columns selected # descr_columns are",
"starts # NOTE THAT: \"NoDeadTracking\" means there is no death effect, thus the",
"= dataframe.loc[row[0] , \"ZeroDivisionError\"] if ConfigError == 0: dataframe.loc[row[0] , \"FitRank\"] = 0",
"file \"\"\" filename = \"stats_description.txt\" # Which name? with open(filename, \"w\") as stats_file:",
"in a file \"\"\" filename = \"stats_description.txt\" # Which name? with open(filename, \"w\")",
"con tuplas para los rangos # NUEVA IDEA: llevar análisis estadístico a archivo",
"STATS' version, if wanted to be stored in a file \"\"\" filename =",
"fitness ranks for the Individual Comparative Analysis (FLYCOP run, input parameters) - organize_fitness_ranks",
"information (rest of the parameters) def obtain_fitness_rank(rank_limits, dataframe, ref_colum): frac_dataframe = dataframe[dataframe[ref_colum] <",
"rangos # NUEVA IDEA: llevar análisis estadístico a archivo para posterior 'ComparativeAnalysis' entre",
"E.coli/ P.putida KT initial biomass ratio # EXAMPLE: -8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config): list_line =",
"que pasarle un límite superior más alto que el mejor de los fitness",
"interval) - ref_colum: reference column to extract the fraction of the dataframe. Default",
"< ref_variable < rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"] = int(i) break elif ref_variable == 0:",
"<NAME> \"\"\" \"\"\" OUTPUT ANALYSIS AFTER FLYCOP (UTILITIES) DESCRIPTION ORGANIZATION OF FITNESS RANKS",
"columns selected # descr_columns are those columns (parameters) for which the statistical description",
"\"ZeroDivisionError\"] if ConfigError == 0: dataframe.loc[row[0] , \"FitRank\"] = 0 else: dataframe.loc[row[0] ,",
"column to extract the fraction of the dataframe. Default :'fitness' - frac_dataframe: fraction",
"Véase mean(), median() (individualmente) # AUTOMATIZAR # ------------------------------- # Set con tuplas para",
"INPUT: dataframe where to operate (pandas dataframe) # OUTPUT: same dataframe with new",
"based on the desired 'ref_column' in the given dataframe # 'New_column' contains the",
"if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], new_column] = str(rank_tuple) break return dataframe",
"E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # Sucrose/ fructose uptake rates ratio # E.coli/",
"ConfigError = dataframe.loc[row[0] , \"ZeroDivisionError\"] if ConfigError == 0: dataframe.loc[row[0] , \"FitRank\"] =",
"rank, all columns) OF THE DATAFRAME # For a fitness interval, retrieves all",
"= str(rank_tuple) break return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF",
"float(list_line[3]) Ec_init = float(list_line[1]) # Ec_init_glyc = float(list_line[2]) KT_init = float(list_line[4]) NH4_Ec =",
"entre configuraciones # Array 3D # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------",
"If the mean for the death effect (initial cycle) was computed, all configurations",
"& ASSOCIATED STATS DESCRIPTION Series of functions to define and process fitness ranks",
"of inner tuples (fitness rank intervals) - rank_limits: smaller tuple (fitness rank individual",
"for row in dataframe.itertuples(): DT_cycles = dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init = DT_cycles[0] if DT_cycles_init",
"----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25",
"dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT PARAMETERS FOR FLYCOP",
"= float(list_line[1]) # Ec_init_glyc = float(list_line[2]) KT_init = float(list_line[4]) NH4_Ec = float(list_line[5]) NH4_KT",
"to extract the fraction of the dataframe. Default :'fitness' - frac_dataframe: fraction of",
"rates ratio # E.coli/ P.putida KT initial biomass ratio # EXAMPLE: -8.0,0.3,-12.0,0.05 def",
"for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns)",
"the categorical classification of values, depending on the established ranks # Instead of",
"(in the denominator) and those with no biomass loss would \"sum 0\" (to",
"OUTPUT See each particular function NOTE THAT: Script in development (...) \"\"\" #",
"uptake_ratio = round(sucr_ur/frc_ur, 3) Ec_init = float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init,",
"str line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates",
"to be processed - rank_limits_set: tuple with a series of inner tuples (fitness",
"rank intervals) - rank_limits: smaller tuple (fitness rank individual interval) - ref_colum: reference",
"# Utility required for further comparison of parameter ratios of each fitness rank",
"death effect (initial cycle) was computed, all configurations would be taken into #",
"# row[0] = Index Number ref_variable = dataframe.loc[row[0], ref_column] for i in range(1,",
"(new column) for the Individual Comparative Analysis within each FLYCOP run # The",
"= stats_description(fitness_rank, descr_columns) print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print() # LIMITACIONES # ------------ #",
"Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration: # Sucrose/ fructose uptake rates ratio # E.coli/",
"float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) return uptake_ratio, initbiomass_ratio # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- #",
", \"ZeroDivisionError\"] if ConfigError == 0: dataframe.loc[row[0] , \"FitRank\"] = 0 else: dataframe.loc[row[0]",
"ref_column): # 'SAVE STATS' version, if wanted to be stored in a file",
"> rank_limits[0]] # Lower limit return final_frac_dataframe # STATISTICAL DESCRIPTION for the selected",
"primero de los rangos, hay que pasarle un límite superior más alto que",
"RANKS & ASSOCIATED STATS DESCRIPTION Series of functions to define and process fitness",
"EXPECTED INPUT - Dataframe: dataframe to be processed - rank_limits_set: tuple with a",
"in dataframe.itertuples(): DT_cycles = dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init = DT_cycles[0] if DT_cycles_init != \"NoDeadTracking\":",
"registered in a given simulation) EXPECTED INPUT - Dataframe: dataframe to be processed",
"obtain_fitness_rank(rank_limits, dataframe, ref_colum): frac_dataframe = dataframe[dataframe[ref_colum] < rank_limits[1]] # Higher limit final_frac_dataframe =",
"filename = \"stats_description.txt\" # Which name? with open(filename, \"w\") as stats_file: for rank_limits_tuple",
"OF THE DATAFRAME # For a fitness interval, retrieves all related information (rest",
"extract_baseConfig_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[3]) Ec_init = float(list_line[1])",
"AUTOMATIZAR # ------------------------------- # Set con tuplas para los rangos # NUEVA IDEA:",
"dataframe[\"DT_cycles_init\"] = 0 for row in dataframe.itertuples(): DT_cycles = dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init =",
"dataframe.loc[row[0] , \"ZeroDivisionError\"] if ConfigError == 0: dataframe.loc[row[0] , \"FitRank\"] = 0 else:",
"0: ConfigError = dataframe.loc[row[0] , \"ZeroDivisionError\"] if ConfigError == 0: dataframe.loc[row[0] , \"FitRank\"]",
"= stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\" # 'PRINT' version for rank_limits_tuple in rank_limits_set: fitness_rank",
"fitness ranks (utility for scripts related to Statistical Analysis). - obtain_fitness_rank - stats_description",
"float(list_line[4]) NH4_KT = float(list_line[5]) NH4_Ec_KT = round(NH4_Ec/NH4_KT, 3) # Pi_Ec = float(list_line[6]) #",
"inner tuples (fitness rank intervals) - rank_limits: smaller tuple (fitness rank individual interval)",
"dataframe.loc[row[0], ref_column] for i in range(1, len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if rank_tuple[0] <",
"< rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"] = int(i) break elif ref_variable == 0: ConfigError =",
"posterior 'ComparativeAnalysis' entre configuraciones # Array 3D # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------",
"# ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE RANKS",
"RANKS (new column 'FitRank') for the Individual Comparative Analysis within each FLYCOP run",
"effect, from the dataframe where it has previously registered # INPUT: dataframe where",
"----------------------------------------------------------------------------- def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] = 0 for row in dataframe.itertuples(): DT_cycles = dataframe.loc[row[0],",
"descr_columns) print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print() # LIMITACIONES # ------------ # Limitación: el",
"the value for 'DT_cycles_init' is 0. # If the mean for the death",
"obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print() #",
"(initial cycle) was computed, all configurations would be taken into # account (in",
"be stored in a file \"\"\" filename = \"stats_description.txt\" # Which name? with",
"------------ # Limitación: el primero de los rangos, hay que pasarle un límite",
"column 'FitRank') for the Individual Comparative Analysis within each FLYCOP run # Utility",
"EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2])",
"configuration, with NP_uptake rates # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur",
"-*- coding: utf-8 -*- \"\"\" Created on Sun Feb 21 21:20:59 2021 @author:",
"NH4_Ec, NH4_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # FUNCTION TO: obtain the initial cycle",
"dataframe - descr_columns: columns to be described with 'Pandas' statistical description (method .describe())",
"- rank_limits: smaller tuple (fitness rank individual interval) - ref_colum: reference column to",
"each FLYCOP run # Utility required for further comparison of parameter ratios of",
"# Instead of a number, the fitness interval itself def organize_ranks(dataframe, rank_limits_set, ref_column,",
"a number, the fitness interval itself def organize_ranks(dataframe, rank_limits_set, ref_column, new_column): for row",
"computed, all configurations would be taken into # account (in the denominator) and",
"FUNCTIONS # 1. Obtains every single fitness rank # 2. Makes the subsequent",
"organize_fitness_ranks(dataframe, rank_limits_set, ref_column): for row in dataframe.itertuples(): # row[0] = Index Number ref_variable",
"initbiomass_ratio, NH4_Ec_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT INPUT PARAMETERS FOR FLYCOP run",
"Individual Comparative Analysis within each FLYCOP run # Utility required for further comparison",
"version for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank,",
"= string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur, 3) Ec_init",
"reorganization of code lines # ----------------------------------------------------------------------------- def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] = 0 for row",
"the subsequent statistical description def describe_fitness_ranks(rank_limits_set, dataframe, descr_columns, ref_column): # 'SAVE STATS' version,",
"desired 'ref_column' in the given dataframe # 'New_column' contains the categorical classification of",
"those with no biomass loss would \"sum 0\" (to the numerator) # TO-DO:",
"dataframe where it has previously registered # INPUT: dataframe where to operate (pandas",
"described with 'Pandas' statistical description (method .describe()) - string_line_config. Example: -8.0,0.3,-12.0,0.05 OUTPUT See",
"configuration, with NP_uptake rates # Sucrose/ fructose uptake rates ratio # E.coli/ P.putida",
"each fitness rank in FLYCOP output tables def organize_fitness_ranks(dataframe, rank_limits_set, ref_column): for row",
"\"w\") as stats_file: for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr",
"run) # ----------------------------------------------------------------------------- # DEFINE RANKS (new column) for the Individual Comparative Analysis",
"round(sucr_ur/frc_ur, 3) Ec_init = float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) NH4_Ec",
"Analysis). - obtain_fitness_rank - stats_description - describe_fitness_ranks: combination of the last two functions",
"ref_column] for i in range(1, len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if rank_tuple[0] < ref_variable",
"are those columns (parameters) for which the statistical description is required def stats_description(frac_dataframe,",
"INPUT - Dataframe: dataframe to be processed - rank_limits_set: tuple with a series",
"for row in dataframe.itertuples(): # row[0] = Index Number ref_variable = dataframe.loc[row[0], ref_column]",
"Analysis (FLYCOP run, input parameters) - organize_fitness_ranks EXTRACT INPUT PARAMETERS FOR A FLYCOP",
"dataframe with new column: # 'DT_cycles_init': cycle when dead effect starts # NOTE",
"Comparative Analysis within each FLYCOP run # Utility required for further comparison of",
"haríamos cálculos individuales de un único parámetro estadístico? Véase mean(), median() (individualmente) #",
"stats_description(fitness_rank, descr_columns) print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print() # LIMITACIONES # ------------ # Limitación:",
"único parámetro estadístico? Véase mean(), median() (individualmente) # AUTOMATIZAR # ------------------------------- # Set",
"# EXTRACT RATIOS OF INPUT PARAMETERS FOR FLYCOP run (configuration) as a single",
"line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration: # Sucrose/ fructose uptake",
"(E.coli/P.putida) # Pi uptake ratio (E.coli/P.putida) # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config): list_line =",
"DESCRIPTION # ----------------------------------------------------------------------------- # RETURNS FRACTION OF INTEREST (fitness rank, all columns) OF",
"# Limitación: el primero de los rangos, hay que pasarle un límite superior",
"OF INTEREST (fitness rank, all columns) OF THE DATAFRAME # For a fitness",
"break elif ref_variable == 0: ConfigError = dataframe.loc[row[0] , \"ZeroDivisionError\"] if ConfigError ==",
"to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # Sucrose/ fructose uptake rates ratio #",
"value for 'DT_cycles_init' is 0. # If the mean for the death effect",
"# NH4 uptake ratio (E.coli/P.putida) # Pi uptake ratio (E.coli/P.putida) # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25",
"describe_fitness_ranks: combination of the last two functions INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) Define",
"= 0 else: dataframe.loc[row[0] , \"FitRank\"] = -1 return dataframe # ----------------------------------------------------------------------------- #",
"NH4_KT = float(list_line[5]) NH4_Ec_KT = round(NH4_Ec/NH4_KT, 3) # Pi_Ec = float(list_line[6]) # Pi_KT",
"frac_dataframe[descr_columns].describe() return stat_description # COMBINES THE TWO LAST FUNCTIONS # 1. Obtains every",
"= float(list_line[7]) return sucr_ur, frc_ur, Ec_init, KT_init, NH4_Ec, NH4_KT # ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------",
"/ reorganization of code lines # ----------------------------------------------------------------------------- def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] = 0 for",
"# E.coli/ P.putida KT initial biomass ratio # EXAMPLE: -8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config): list_line",
"the fraction of the dataframe. Default :'fitness' - frac_dataframe: fraction of a particular",
"rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], new_column] = str(rank_tuple) break return",
"float(list_line[6]) # Pi_KT = float(list_line[7]) return sucr_ur, frc_ur, Ec_init, KT_init, NH4_Ec, NH4_KT #",
"the given dataframe # 'New_column' contains the categorical classification of values, depending on",
"\"NoDeadTracking\" means there is no death effect, thus the value for 'DT_cycles_init' is",
"# ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION # ----------------------------------------------------------------------------- # RETURNS",
"for the death effect (initial cycle) was computed, all configurations would be taken",
"as pd # import os.path # ----------------------------------------------------------------------------- # ORGANIZATION OF FITNESS RANKS &",
"# ------------------------------- # Set con tuplas para los rangos # NUEVA IDEA: llevar",
"Limitación: el primero de los rangos, hay que pasarle un límite superior más",
"return final_frac_dataframe # STATISTICAL DESCRIPTION for the selected fitness rank, columns selected #",
"# ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE FITNESS",
"# 2. Makes the subsequent statistical description def describe_fitness_ranks(rank_limits_set, dataframe, descr_columns, ref_column): #",
"(new column 'FitRank') for the Individual Comparative Analysis within each FLYCOP run #",
"for death effect, from the dataframe where it has previously registered # INPUT:",
"< ref_variable < rank_tuple[1]: dataframe.loc[row[0], new_column] = str(rank_tuple) break return dataframe # -----------------------------------------------------------------------------",
"STATS DESCRIPTION # ----------------------------------------------------------------------------- # RETURNS FRACTION OF INTEREST (fitness rank, all columns)",
"# Pi uptake ratio (E.coli/P.putida) # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config): list_line = string_line_config.split(\",\")",
"means there is no death effect, thus the value for 'DT_cycles_init' is 0.",
"organize_ranks(dataframe, rank_limits_set, ref_column, new_column): for row in dataframe.itertuples(): # row[0] = Index Number",
"obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\" # 'PRINT' version for",
"return uptake_ratio, initbiomass_ratio, NH4_Ec_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT INPUT PARAMETERS FOR",
"0. # If the mean for the death effect (initial cycle) was computed,",
"ranks (utility for scripts related to Statistical Analysis). - obtain_fitness_rank - stats_description -",
"to Statistical Analysis). - obtain_fitness_rank - stats_description - describe_fitness_ranks: combination of the last",
"a archivo para posterior 'ComparativeAnalysis' entre configuraciones # Array 3D # ----------------------------------------------------------------------------- #",
"= int(i) break elif ref_variable == 0: ConfigError = dataframe.loc[row[0] , \"ZeroDivisionError\"] if",
"column: # 'DT_cycles_init': cycle when dead effect starts # NOTE THAT: \"NoDeadTracking\" means",
"ranks for the Individual Comparative Analysis (FLYCOP run, input parameters) - organize_fitness_ranks EXTRACT",
"Created on Sun Feb 21 21:20:59 2021 @author: <NAME> \"\"\" \"\"\" OUTPUT ANALYSIS",
"extract_ratios(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur,",
"loss would \"sum 0\" (to the numerator) # TO-DO: further implementation / reorganization",
"single str line - extract_ratios ANALYSIS OF BIOMASS LOSS - when_death_starts (when this",
"new_column] = str(rank_tuple) break return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS",
"float(list_line[2]) KT_init = float(list_line[4]) NH4_Ec = float(list_line[5]) NH4_KT = float(list_line[6]) # Pi_Ec =",
"death effect, thus the value for 'DT_cycles_init' is 0. # If the mean",
"OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION # ----------------------------------------------------------------------------- # RETURNS FRACTION OF",
"uptake rates ratio # E.coli/ P.putida KT initial biomass ratio # EXAMPLE: -8.0,0.3,-12.0,0.05",
"E.coli/ P.putida KT initial biomass ratio # NH4 uptake ratio (E.coli/P.putida) # Pi",
"thus the value for 'DT_cycles_init' is 0. # If the mean for the",
"dataframe where to operate (pandas dataframe) # OUTPUT: same dataframe with new column:",
"in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\"",
"process fitness ranks (utility for scripts related to Statistical Analysis). - obtain_fitness_rank -",
"effect is first registered in a given simulation) EXPECTED INPUT - Dataframe: dataframe",
"comparison of parameter ratios of each fitness rank in FLYCOP output tables def",
"function NOTE THAT: Script in development (...) \"\"\" # import re # import",
"break return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT PARAMETERS",
"# 'SAVE STATS' version, if wanted to be stored in a file \"\"\"",
"OF BIOMASS LOSS - when_death_starts (when this effect is first registered in a",
"account (in the denominator) and those with no biomass loss would \"sum 0\"",
"PARAMETERS FOR FLYCOP run (configuration) as a single str line # ----------------------------------------------------------------------------- #",
"uptake_ratio, initbiomass_ratio # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT PARAMETERS FOR",
"-8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio",
"= rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], new_column] = str(rank_tuple) break",
"round(NH4_Ec/NH4_KT, 3) # Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) # Pi_Ec_KT =",
"dataframe, descr_columns, ref_column): # 'SAVE STATS' version, if wanted to be stored in",
"'ComparativeAnalysis' entre configuraciones # Array 3D # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- #",
"frc_ur = float(list_line[3]) Ec_init = float(list_line[1]) # Ec_init_glyc = float(list_line[2]) KT_init = float(list_line[4])",
"required for further comparison of parameter ratios of each fitness rank in FLYCOP",
"for scripts related to Statistical Analysis). - obtain_fitness_rank - stats_description - describe_fitness_ranks: combination",
"with a series of inner tuples (fitness rank intervals) - rank_limits: smaller tuple",
"rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print() # LIMITACIONES # ------------ # Limitación: el primero de",
"# If the mean for the death effect (initial cycle) was computed, all",
"# Array 3D # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL",
"EXTRACT RATIOS OF INPUT PARAMETERS FOR FLYCOP run (configuration) as a single str",
"# Sucrose/ fructose uptake rates ratio # E.coli/ P.putida KT initial biomass ratio",
"def describe_fitness_ranks(rank_limits_set, dataframe, descr_columns, ref_column): # 'SAVE STATS' version, if wanted to be",
"(pandas dataframe) # OUTPUT: same dataframe with new column: # 'DT_cycles_init': cycle when",
"functions INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) Define fitness ranks for the Individual Comparative",
"fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\" # 'PRINT'",
"\"FitRank\"] = 0 else: dataframe.loc[row[0] , \"FitRank\"] = -1 return dataframe # -----------------------------------------------------------------------------",
"NP_uptake rates # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0])",
"los rangos, hay que pasarle un límite superior más alto que el mejor",
"line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates #",
"# import pandas as pd # import os.path # ----------------------------------------------------------------------------- # ORGANIZATION OF",
"E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config): list_line = string_line_config.split(\",\")",
"\"\"\" Created on Sun Feb 21 21:20:59 2021 @author: <NAME> \"\"\" \"\"\" OUTPUT",
"processed - rank_limits_set: tuple with a series of inner tuples (fitness rank intervals)",
"# NOTE THAT: \"NoDeadTracking\" means there is no death effect, thus the value",
"Statistical Analysis). - obtain_fitness_rank - stats_description - describe_fitness_ranks: combination of the last two",
"code lines # ----------------------------------------------------------------------------- def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] = 0 for row in dataframe.itertuples():",
"def extract_ratios(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio =",
"subsequent statistical description def describe_fitness_ranks(rank_limits_set, dataframe, descr_columns, ref_column): # 'SAVE STATS' version, if",
"dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # -----------------------------------------------------------------------------",
"effect starts # NOTE THAT: \"NoDeadTracking\" means there is no death effect, thus",
"parameters) def obtain_fitness_rank(rank_limits, dataframe, ref_colum): frac_dataframe = dataframe[dataframe[ref_colum] < rank_limits[1]] # Higher limit",
"EXAMPLE: -8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2])",
"all columns) OF THE DATAFRAME # For a fitness interval, retrieves all related",
"pd # import os.path # ----------------------------------------------------------------------------- # ORGANIZATION OF FITNESS RANKS & ASSOCIATED",
"ratio # E.coli/ P.putida KT initial biomass ratio # NH4 uptake ratio (E.coli/P.putida)",
"For a fitness interval, retrieves all related information (rest of the parameters) def",
"with NP_uptake rates # Sucrose/ fructose uptake rates ratio # E.coli/ P.putida KT",
"in development (...) \"\"\" # import re # import pandas as pd #",
"open(filename, \"w\") as stats_file: for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column)",
"KT initial biomass ratio # NH4 uptake ratio (E.coli/P.putida) # Pi uptake ratio",
"== 0: dataframe.loc[row[0] , \"FitRank\"] = 0 else: dataframe.loc[row[0] , \"FitRank\"] = -1",
"rank_limits_set: tuple with a series of inner tuples (fitness rank intervals) - rank_limits:",
"cálculos individuales de un único parámetro estadístico? Véase mean(), median() (individualmente) # AUTOMATIZAR",
"Array 3D # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE",
"the dataframe where it has previously registered # INPUT: dataframe where to operate",
"def stats_description(frac_dataframe, descr_columns): stat_description = frac_dataframe[descr_columns].describe() return stat_description # COMBINES THE TWO LAST",
"float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur, 3) Ec_init = float(list_line[1]) KT_init =",
"development (...) \"\"\" # import re # import pandas as pd # import",
"run (configuration) as a single str line - extract_ratios ANALYSIS OF BIOMASS LOSS",
"- extract_ratios ANALYSIS OF BIOMASS LOSS - when_death_starts (when this effect is first",
"float(list_line[4]) NH4_Ec = float(list_line[5]) NH4_KT = float(list_line[6]) # Pi_Ec = float(list_line[6]) # Pi_KT",
"to be described with 'Pandas' statistical description (method .describe()) - string_line_config. Example: -8.0,0.3,-12.0,0.05",
"specific to E.coli_iEC1364-P.putida_KT2440 configuration: # Sucrose/ fructose uptake rates ratio # E.coli/ P.putida",
"3) Ec_init = float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) return uptake_ratio,",
"FLYCOP (UTILITIES) DESCRIPTION ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION Series of",
"Instead of a number, the fitness interval itself def organize_ranks(dataframe, rank_limits_set, ref_column, new_column):",
"rank individual interval) - ref_colum: reference column to extract the fraction of the",
"# COMBINES THE TWO LAST FUNCTIONS # 1. Obtains every single fitness rank",
"rank_tuple = rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], new_column] = str(rank_tuple)",
"# EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur =",
"# ------------ # Limitación: el primero de los rangos, hay que pasarle un",
"in the given dataframe # 'New_column' contains the categorical classification of values, depending",
"depending on the established ranks # Instead of a number, the fitness interval",
"of parameter ratios of each fitness rank in FLYCOP output tables def organize_fitness_ranks(dataframe,",
"Utility required for further comparison of parameter ratios of each fitness rank in",
"rank in FLYCOP output tables def organize_fitness_ranks(dataframe, rank_limits_set, ref_column): for row in dataframe.itertuples():",
"¿cómo haríamos cálculos individuales de un único parámetro estadístico? Véase mean(), median() (individualmente)",
"Individual Comparative Analysis (FLYCOP run, input parameters) - organize_fitness_ranks EXTRACT INPUT PARAMETERS FOR",
"last two functions INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) Define fitness ranks for the",
"fructose uptake rates ratio # E.coli/ P.putida KT initial biomass ratio # EXAMPLE:",
"descr_columns): stat_description = frac_dataframe[descr_columns].describe() return stat_description # COMBINES THE TWO LAST FUNCTIONS #",
"FITNESS RANKS & ASSOCIATED STATS DESCRIPTION # ----------------------------------------------------------------------------- # RETURNS FRACTION OF INTEREST",
"\"\"\" \"\"\" OUTPUT ANALYSIS AFTER FLYCOP (UTILITIES) DESCRIPTION ORGANIZATION OF FITNESS RANKS &",
"string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[3]) Ec_init = float(list_line[1]) # Ec_init_glyc =",
"series of inner tuples (fitness rank intervals) - rank_limits: smaller tuple (fitness rank",
"import re # import pandas as pd # import os.path # ----------------------------------------------------------------------------- #",
"que el mejor de los fitness # Limitación: ¿cómo haríamos cálculos individuales de",
"uptake ratio (E.coli/P.putida) # Pi uptake ratio (E.coli/P.putida) # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config):",
"round(Ec_init/KT_init, 3) NH4_Ec = float(list_line[4]) NH4_KT = float(list_line[5]) NH4_Ec_KT = round(NH4_Ec/NH4_KT, 3) #",
"< rank_limits[1]] # Higher limit final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]] # Lower limit",
"rank_limits: smaller tuple (fitness rank individual interval) - ref_colum: reference column to extract",
"los rangos # NUEVA IDEA: llevar análisis estadístico a archivo para posterior 'ComparativeAnalysis'",
"----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run)",
"rates ratio # E.coli/ P.putida KT initial biomass ratio # NH4 uptake ratio",
"to operate (pandas dataframe) # OUTPUT: same dataframe with new column: # 'DT_cycles_init':",
"rank_limits_set, ref_column, new_column): for row in dataframe.itertuples(): # row[0] = Index Number ref_variable",
"fitness interval, retrieves all related information (rest of the parameters) def obtain_fitness_rank(rank_limits, dataframe,",
"- ref_colum: reference column to extract the fraction of the dataframe. Default :'fitness'",
"extract the fraction of the dataframe. Default :'fitness' - frac_dataframe: fraction of a",
"of functions to define and process fitness ranks (utility for scripts related to",
"= obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print()",
"NUEVA IDEA: llevar análisis estadístico a archivo para posterior 'ComparativeAnalysis' entre configuraciones #",
"LOSS - when_death_starts (when this effect is first registered in a given simulation)",
"AFTER FLYCOP (UTILITIES) DESCRIPTION ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION Series",
"for the Individual Comparative Analysis (FLYCOP run, input parameters) - organize_fitness_ranks EXTRACT INPUT",
"frc_ur = float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur, 3) Ec_init = float(list_line[1]) KT_init = float(list_line[3])",
"P.putida KT initial biomass ratio # EXAMPLE: -8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config): list_line = string_line_config.split(\",\")",
"# Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) # Pi_Ec_KT = round(Pi_Ec/Pi_KT, 3)",
"# Higher limit final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]] # Lower limit return final_frac_dataframe",
"ref_column): for row in dataframe.itertuples(): # row[0] = Index Number ref_variable = dataframe.loc[row[0],",
"0: dataframe.loc[row[0] , \"FitRank\"] = 0 else: dataframe.loc[row[0] , \"FitRank\"] = -1 return",
"dataframe to be processed - rank_limits_set: tuple with a series of inner tuples",
"\"\"\" # import re # import pandas as pd # import os.path #",
"FRACTION OF INTEREST (fitness rank, all columns) OF THE DATAFRAME # For a",
"\"sum 0\" (to the numerator) # TO-DO: further implementation / reorganization of code",
"----------------------------------------------------------------------------- # ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION # ----------------------------------------------------------------------------- #",
"same dataframe with new column: # 'DT_cycles_init': cycle when dead effect starts #",
"stored in a file \"\"\" filename = \"stats_description.txt\" # Which name? with open(filename,",
"frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]] # Lower limit return final_frac_dataframe # STATISTICAL DESCRIPTION for the",
"stats_description - describe_fitness_ranks: combination of the last two functions INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP",
"= frac_dataframe[descr_columns].describe() return stat_description # COMBINES THE TWO LAST FUNCTIONS # 1. Obtains",
"DT_cycles[0] if DT_cycles_init != \"NoDeadTracking\": dataframe.loc[row[0], \"DT_cycles_init\"] = int(DT_cycles_init) return dataframe # -----------------------------------------------------------------------------",
"ref_column) stat_descr = stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\" # 'PRINT' version for rank_limits_tuple in",
"Obtains every single fitness rank # 2. Makes the subsequent statistical description def",
"# ----------------------------------------------------------------------------- # DEFINE RANKS (new column) for the Individual Comparative Analysis within",
"initial cycle for death effect, from the dataframe where it has previously registered",
"COMPARATIVE ANALYSIS (FLYCOP run) Define fitness ranks for the Individual Comparative Analysis (FLYCOP",
"stats_file.write(stat_descr+\"\\n\") \"\"\" # 'PRINT' version for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe,",
"Ec_init = float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) NH4_Ec = float(list_line[4])",
"'DT_cycles_init' is 0. # If the mean for the death effect (initial cycle)",
"for the Individual Comparative Analysis within each FLYCOP run # The ranks are",
"classification of values, depending on the established ranks # Instead of a number,",
"dataframe.loc[row[0] , \"FitRank\"] = 0 else: dataframe.loc[row[0] , \"FitRank\"] = -1 return dataframe",
"= float(list_line[6]) # Pi_KT = float(list_line[7]) # Pi_Ec_KT = round(Pi_Ec/Pi_KT, 3) return uptake_ratio,",
"(FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE FITNESS RANKS (new column 'FitRank') for the",
"string_line_config. Example: -8.0,0.3,-12.0,0.05 OUTPUT See each particular function NOTE THAT: Script in development",
"FITNESS RANKS (new column 'FitRank') for the Individual Comparative Analysis within each FLYCOP",
"= float(list_line[4]) NH4_Ec = float(list_line[5]) NH4_KT = float(list_line[6]) # Pi_Ec = float(list_line[6]) #",
"KT_init, NH4_Ec, NH4_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # FUNCTION TO: obtain the initial",
"(utility for scripts related to Statistical Analysis). - obtain_fitness_rank - stats_description - describe_fitness_ranks:",
"number, the fitness interval itself def organize_ranks(dataframe, rank_limits_set, ref_column, new_column): for row in",
"columns to be described with 'Pandas' statistical description (method .describe()) - string_line_config. Example:",
"FITNESS RANKS & ASSOCIATED STATS DESCRIPTION Series of functions to define and process",
"FLYCOP run # The ranks are defined based on the desired 'ref_column' in",
"NP_uptake rates # Sucrose/ fructose uptake rates ratio # E.coli/ P.putida KT initial",
"----------------------------------------------------------------------------- # DEFINE FITNESS RANKS (new column 'FitRank') for the Individual Comparative Analysis",
"biomass loss would \"sum 0\" (to the numerator) # TO-DO: further implementation /",
"# 'New_column' contains the categorical classification of values, depending on the established ranks",
"Series of functions to define and process fitness ranks (utility for scripts related",
"= round(NH4_Ec/NH4_KT, 3) # Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) # Pi_Ec_KT",
"# import re # import pandas as pd # import os.path # -----------------------------------------------------------------------------",
"str line - extract_ratios ANALYSIS OF BIOMASS LOSS - when_death_starts (when this effect",
"# Which name? with open(filename, \"w\") as stats_file: for rank_limits_tuple in rank_limits_set: fitness_rank",
"from the dataframe where it has previously registered # INPUT: dataframe where to",
"3) return uptake_ratio, initbiomass_ratio # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT",
"the Individual Comparative Analysis (FLYCOP run, input parameters) - organize_fitness_ranks EXTRACT INPUT PARAMETERS",
"in FLYCOP output tables def organize_fitness_ranks(dataframe, rank_limits_set, ref_column): for row in dataframe.itertuples(): #",
"# ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT PARAMETERS FOR FLYCOP run",
"rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], new_column] = str(rank_tuple) break return dataframe #",
"limit return final_frac_dataframe # STATISTICAL DESCRIPTION for the selected fitness rank, columns selected",
"established ranks # Instead of a number, the fitness interval itself def organize_ranks(dataframe,",
"# 1. Obtains every single fitness rank # 2. Makes the subsequent statistical",
"Which name? with open(filename, \"w\") as stats_file: for rank_limits_tuple in rank_limits_set: fitness_rank =",
"ratio # E.coli/ P.putida KT initial biomass ratio # EXAMPLE: -8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config):",
"return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT PARAMETERS FOR",
"= float(list_line[5]) NH4_Ec_KT = round(NH4_Ec/NH4_KT, 3) # Pi_Ec = float(list_line[6]) # Pi_KT =",
"------------------------------- # Set con tuplas para los rangos # NUEVA IDEA: llevar análisis",
"line - extract_ratios ANALYSIS OF BIOMASS LOSS - when_death_starts (when this effect is",
"smaller tuple (fitness rank individual interval) - ref_colum: reference column to extract the",
"A FLYCOP run (configuration) as a single str line - extract_ratios ANALYSIS OF",
"rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"] = int(i) break elif ref_variable ==",
"description (method .describe()) - string_line_config. Example: -8.0,0.3,-12.0,0.05 OUTPUT See each particular function NOTE",
"the selected fitness rank, columns selected # descr_columns are those columns (parameters) for",
"parameter ratios of each fitness rank in FLYCOP output tables def organize_fitness_ranks(dataframe, rank_limits_set,",
"Pi_Ec_KT = round(Pi_Ec/Pi_KT, 3) return uptake_ratio, initbiomass_ratio, NH4_Ec_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- #",
"run) Define fitness ranks for the Individual Comparative Analysis (FLYCOP run, input parameters)",
"pasarle un límite superior más alto que el mejor de los fitness #",
"= dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init = DT_cycles[0] if DT_cycles_init != \"NoDeadTracking\": dataframe.loc[row[0], \"DT_cycles_init\"] =",
"- stats_description - describe_fitness_ranks: combination of the last two functions INDIVIDUAL COMPARATIVE ANALYSIS",
"THAT: Script in development (...) \"\"\" # import re # import pandas as",
"parámetro estadístico? Véase mean(), median() (individualmente) # AUTOMATIZAR # ------------------------------- # Set con",
"RANKS (new column) for the Individual Comparative Analysis within each FLYCOP run #",
"on Sun Feb 21 21:20:59 2021 @author: <NAME> \"\"\" \"\"\" OUTPUT ANALYSIS AFTER",
"rank, columns selected # descr_columns are those columns (parameters) for which the statistical",
"# Ec_init_glyc = float(list_line[2]) KT_init = float(list_line[4]) NH4_Ec = float(list_line[5]) NH4_KT = float(list_line[6])",
"further implementation / reorganization of code lines # ----------------------------------------------------------------------------- def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] =",
"21:20:59 2021 @author: <NAME> \"\"\" \"\"\" OUTPUT ANALYSIS AFTER FLYCOP (UTILITIES) DESCRIPTION ORGANIZATION",
"range(1, len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], new_column]",
"(fitness rank, all columns) OF THE DATAFRAME # For a fitness interval, retrieves",
"define and process fitness ranks (utility for scripts related to Statistical Analysis). -",
"(configuration) as a single str line - extract_ratios ANALYSIS OF BIOMASS LOSS -",
"(fitness rank intervals) - rank_limits: smaller tuple (fitness rank individual interval) - ref_colum:",
"categorical classification of values, depending on the established ranks # Instead of a",
"de un único parámetro estadístico? Véase mean(), median() (individualmente) # AUTOMATIZAR # -------------------------------",
"'ref_column' in the given dataframe # 'New_column' contains the categorical classification of values,",
"cycle for death effect, from the dataframe where it has previously registered #",
"the Individual Comparative Analysis within each FLYCOP run # The ranks are defined",
"limit final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]] # Lower limit return final_frac_dataframe # STATISTICAL",
"the parameters) def obtain_fitness_rank(rank_limits, dataframe, ref_colum): frac_dataframe = dataframe[dataframe[ref_colum] < rank_limits[1]] # Higher",
"list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur, 3)",
"= round(Pi_Ec/Pi_KT, 3) return uptake_ratio, initbiomass_ratio, NH4_Ec_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT",
"list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[3]) Ec_init = float(list_line[1]) #",
"registered # INPUT: dataframe where to operate (pandas dataframe) # OUTPUT: same dataframe",
"for further comparison of parameter ratios of each fitness rank in FLYCOP output",
"# AUTOMATIZAR # ------------------------------- # Set con tuplas para los rangos # NUEVA",
"\"\"\" OUTPUT ANALYSIS AFTER FLYCOP (UTILITIES) DESCRIPTION ORGANIZATION OF FITNESS RANKS & ASSOCIATED",
"RANKS & ASSOCIATED STATS DESCRIPTION # ----------------------------------------------------------------------------- # RETURNS FRACTION OF INTEREST (fitness",
"descr_columns are those columns (parameters) for which the statistical description is required def",
"when dead effect starts # NOTE THAT: \"NoDeadTracking\" means there is no death",
"DT_cycles_init = DT_cycles[0] if DT_cycles_init != \"NoDeadTracking\": dataframe.loc[row[0], \"DT_cycles_init\"] = int(DT_cycles_init) return dataframe",
"with NP_uptake rates # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur =",
"str line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration: # Sucrose/ fructose",
"initial biomass ratio # EXAMPLE: -8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config): list_line = string_line_config.split(\",\") sucr_ur =",
"# TO-DO: further implementation / reorganization of code lines # ----------------------------------------------------------------------------- def when_death_starts(dataframe):",
"final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]] # Lower limit return final_frac_dataframe # STATISTICAL DESCRIPTION",
"= frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]] # Lower limit return final_frac_dataframe # STATISTICAL DESCRIPTION for",
"a series of inner tuples (fitness rank intervals) - rank_limits: smaller tuple (fitness",
"float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) return uptake_ratio, initbiomass_ratio # -----------------------------------------------------------------------------",
"== 0: ConfigError = dataframe.loc[row[0] , \"ZeroDivisionError\"] if ConfigError == 0: dataframe.loc[row[0] ,",
"Lower limit return final_frac_dataframe # STATISTICAL DESCRIPTION for the selected fitness rank, columns",
"float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) NH4_Ec = float(list_line[4]) NH4_KT = float(list_line[5]) NH4_Ec_KT =",
"fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr)",
"stat_descr = stats_description(fitness_rank, descr_columns) print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print() # LIMITACIONES # ------------",
"< rank_tuple[1]: dataframe.loc[row[0], new_column] = str(rank_tuple) break return dataframe # ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------",
"INPUT PARAMETERS FOR FLYCOP run (configuration) as a single str line # -----------------------------------------------------------------------------",
"of a number, the fitness interval itself def organize_ranks(dataframe, rank_limits_set, ref_column, new_column): for",
"print(stat_descr) print() # LIMITACIONES # ------------ # Limitación: el primero de los rangos,",
"OF INPUT PARAMETERS FOR FLYCOP run (configuration) as a single str line #",
"Comparative Analysis within each FLYCOP run # The ranks are defined based on",
"# INPUT: dataframe where to operate (pandas dataframe) # OUTPUT: same dataframe with",
"descr_columns: columns to be described with 'Pandas' statistical description (method .describe()) - string_line_config.",
"# OUTPUT: same dataframe with new column: # 'DT_cycles_init': cycle when dead effect",
"final_frac_dataframe # STATISTICAL DESCRIPTION for the selected fitness rank, columns selected # descr_columns",
"# INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE FITNESS RANKS (new",
"death effect, from the dataframe where it has previously registered # INPUT: dataframe",
"two functions INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) Define fitness ranks for the Individual",
"Limitación: ¿cómo haríamos cálculos individuales de un único parámetro estadístico? Véase mean(), median()",
"(rest of the parameters) def obtain_fitness_rank(rank_limits, dataframe, ref_colum): frac_dataframe = dataframe[dataframe[ref_colum] < rank_limits[1]]",
"# ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP",
"new_column): for row in dataframe.itertuples(): # row[0] = Index Number ref_variable = dataframe.loc[row[0],",
"was computed, all configurations would be taken into # account (in the denominator)",
"stat_description = frac_dataframe[descr_columns].describe() return stat_description # COMBINES THE TWO LAST FUNCTIONS # 1.",
"{rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print() # LIMITACIONES # ------------ # Limitación: el primero de los",
"= float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) return uptake_ratio, initbiomass_ratio #",
"# ----------------------------------------------------------------------------- # DEFINE FITNESS RANKS (new column 'FitRank') for the Individual Comparative",
"para posterior 'ComparativeAnalysis' entre configuraciones # Array 3D # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- #",
"of each fitness rank in FLYCOP output tables def organize_fitness_ranks(dataframe, rank_limits_set, ref_column): for",
"ref_variable == 0: ConfigError = dataframe.loc[row[0] , \"ZeroDivisionError\"] if ConfigError == 0: dataframe.loc[row[0]",
"values, depending on the established ranks # Instead of a number, the fitness",
"KT_init = float(list_line[4]) NH4_Ec = float(list_line[5]) NH4_KT = float(list_line[6]) # Pi_Ec = float(list_line[6])",
"THE DATAFRAME # For a fitness interval, retrieves all related information (rest of",
"float(list_line[6]) # Pi_KT = float(list_line[7]) # Pi_Ec_KT = round(Pi_Ec/Pi_KT, 3) return uptake_ratio, initbiomass_ratio,",
"of the last two functions INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) Define fitness ranks",
"tuplas para los rangos # NUEVA IDEA: llevar análisis estadístico a archivo para",
"in dataframe.itertuples(): # row[0] = Index Number ref_variable = dataframe.loc[row[0], ref_column] for i",
"stat_description # COMBINES THE TWO LAST FUNCTIONS # 1. Obtains every single fitness",
"configuration: # Sucrose/ fructose uptake rates ratio # E.coli/ P.putida KT initial biomass",
"INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE FITNESS RANKS (new column",
"fitness rank, columns selected # descr_columns are those columns (parameters) for which the",
"FOR FLYCOP run (configuration) as a single str line # ----------------------------------------------------------------------------- # Currently:",
"= round(sucr_ur/frc_ur, 3) Ec_init = float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3)",
"denominator) and those with no biomass loss would \"sum 0\" (to the numerator)",
"más alto que el mejor de los fitness # Limitación: ¿cómo haríamos cálculos",
"FOR A FLYCOP run (configuration) as a single str line - extract_ratios ANALYSIS",
"stats_file: for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank,",
"= float(list_line[3]) Ec_init = float(list_line[1]) # Ec_init_glyc = float(list_line[2]) KT_init = float(list_line[4]) NH4_Ec",
"(individualmente) # AUTOMATIZAR # ------------------------------- # Set con tuplas para los rangos #",
", \"FitRank\"] = -1 return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE",
"selected fitness rank, columns selected # descr_columns are those columns (parameters) for which",
"each FLYCOP run # The ranks are defined based on the desired 'ref_column'",
"TO-DO: further implementation / reorganization of code lines # ----------------------------------------------------------------------------- def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"]",
"output tables def organize_fitness_ranks(dataframe, rank_limits_set, ref_column): for row in dataframe.itertuples(): # row[0] =",
"ratio (E.coli/P.putida) # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0])",
"para los rangos # NUEVA IDEA: llevar análisis estadístico a archivo para posterior",
"# ----------------------------------------------------------------------------- # EXTRACT INPUT PARAMETERS FOR FLYCOP run (configuration) as a single",
"= float(list_line[6]) # Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) return sucr_ur, frc_ur,",
"each particular function NOTE THAT: Script in development (...) \"\"\" # import re",
"----------------------------------------------------------------------------- # DEFINE RANKS (new column) for the Individual Comparative Analysis within each",
"coding: utf-8 -*- \"\"\" Created on Sun Feb 21 21:20:59 2021 @author: <NAME>",
"int(i) break elif ref_variable == 0: ConfigError = dataframe.loc[row[0] , \"ZeroDivisionError\"] if ConfigError",
"given simulation) EXPECTED INPUT - Dataframe: dataframe to be processed - rank_limits_set: tuple",
"(FLYCOP run, input parameters) - organize_fitness_ranks EXTRACT INPUT PARAMETERS FOR A FLYCOP run",
"float(list_line[0]) frc_ur = float(list_line[3]) Ec_init = float(list_line[1]) # Ec_init_glyc = float(list_line[2]) KT_init =",
"rates # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur",
"of the parameters) def obtain_fitness_rank(rank_limits, dataframe, ref_colum): frac_dataframe = dataframe[dataframe[ref_colum] < rank_limits[1]] #",
"superior más alto que el mejor de los fitness # Limitación: ¿cómo haríamos",
"(fitness rank individual interval) - ref_colum: reference column to extract the fraction of",
"run # Utility required for further comparison of parameter ratios of each fitness",
"column) for the Individual Comparative Analysis within each FLYCOP run # The ranks",
"round(sucr_ur/frc_ur, 3) Ec_init = float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) return",
"uptake_ratio, initbiomass_ratio, NH4_Ec_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT INPUT PARAMETERS FOR FLYCOP",
"Analysis within each FLYCOP run # The ranks are defined based on the",
"3) # Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) # Pi_Ec_KT = round(Pi_Ec/Pi_KT,",
"= float(list_line[5]) NH4_KT = float(list_line[6]) # Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7])",
"NOTE THAT: Script in development (...) \"\"\" # import re # import pandas",
"implementation / reorganization of code lines # ----------------------------------------------------------------------------- def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] = 0",
"defined based on the desired 'ref_column' in the given dataframe # 'New_column' contains",
"i in range(1, len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]:",
"on the desired 'ref_column' in the given dataframe # 'New_column' contains the categorical",
"LAST FUNCTIONS # 1. Obtains every single fitness rank # 2. Makes the",
"Example: -8.0,0.3,-12.0,0.05 OUTPUT See each particular function NOTE THAT: Script in development (...)",
"NH4_Ec = float(list_line[5]) NH4_KT = float(list_line[6]) # Pi_Ec = float(list_line[6]) # Pi_KT =",
"os.path # ----------------------------------------------------------------------------- # ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION #",
"# ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # FUNCTION TO: obtain the initial cycle for death",
"rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\")",
"ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE FITNESS RANKS (new column 'FitRank') for",
"Ec_init = float(list_line[1]) # Ec_init_glyc = float(list_line[2]) KT_init = float(list_line[4]) NH4_Ec = float(list_line[5])",
"fitness # Limitación: ¿cómo haríamos cálculos individuales de un único parámetro estadístico? Véase",
"with new column: # 'DT_cycles_init': cycle when dead effect starts # NOTE THAT:",
"cycle) was computed, all configurations would be taken into # account (in the",
"RETURNS FRACTION OF INTEREST (fitness rank, all columns) OF THE DATAFRAME # For",
"stats_description(frac_dataframe, descr_columns): stat_description = frac_dataframe[descr_columns].describe() return stat_description # COMBINES THE TWO LAST FUNCTIONS",
"(FLYCOP run) Define fitness ranks for the Individual Comparative Analysis (FLYCOP run, input",
"COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE RANKS (new column) for the",
"= float(list_line[0]) frc_ur = float(list_line[3]) Ec_init = float(list_line[1]) # Ec_init_glyc = float(list_line[2]) KT_init",
"----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # FUNCTION TO: obtain the initial cycle for death effect,",
"- organize_fitness_ranks EXTRACT INPUT PARAMETERS FOR A FLYCOP run (configuration) as a single",
"3D # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS",
"Ec_init = float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) return uptake_ratio, initbiomass_ratio",
"dead effect starts # NOTE THAT: \"NoDeadTracking\" means there is no death effect,",
"Ec_init, KT_init, NH4_Ec, NH4_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # FUNCTION TO: obtain the",
"float(list_line[6]) # Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) return sucr_ur, frc_ur, Ec_init,",
"NH4_Ec_KT = round(NH4_Ec/NH4_KT, 3) # Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) #",
"sucr_ur, frc_ur, Ec_init, KT_init, NH4_Ec, NH4_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # FUNCTION TO:",
"\"\"\" filename = \"stats_description.txt\" # Which name? with open(filename, \"w\") as stats_file: for",
"Define fitness ranks for the Individual Comparative Analysis (FLYCOP run, input parameters) -",
"in a given simulation) EXPECTED INPUT - Dataframe: dataframe to be processed -",
"further comparison of parameter ratios of each fitness rank in FLYCOP output tables",
"dataframe. Default :'fitness' - frac_dataframe: fraction of a particular dataframe - descr_columns: columns",
"statistical description is required def stats_description(frac_dataframe, descr_columns): stat_description = frac_dataframe[descr_columns].describe() return stat_description #",
"extract_ratios_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur,",
"----------------------------------------------------------------------------- # RETURNS FRACTION OF INTEREST (fitness rank, all columns) OF THE DATAFRAME",
"= \"stats_description.txt\" # Which name? with open(filename, \"w\") as stats_file: for rank_limits_tuple in",
"-4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[3]) Ec_init",
"def obtain_fitness_rank(rank_limits, dataframe, ref_colum): frac_dataframe = dataframe[dataframe[ref_colum] < rank_limits[1]] # Higher limit final_frac_dataframe",
"- rank_limits_set: tuple with a series of inner tuples (fitness rank intervals) -",
"previously registered # INPUT: dataframe where to operate (pandas dataframe) # OUTPUT: same",
"FLYCOP output tables def organize_fitness_ranks(dataframe, rank_limits_set, ref_column): for row in dataframe.itertuples(): # row[0]",
"which the statistical description is required def stats_description(frac_dataframe, descr_columns): stat_description = frac_dataframe[descr_columns].describe() return",
"rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\" #",
"----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT PARAMETERS FOR FLYCOP run (configuration)",
"límite superior más alto que el mejor de los fitness # Limitación: ¿cómo",
"when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] = 0 for row in dataframe.itertuples(): DT_cycles = dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init",
"-1 return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run)",
"# Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) return sucr_ur, frc_ur, Ec_init, KT_init,",
"related to Statistical Analysis). - obtain_fitness_rank - stats_description - describe_fitness_ranks: combination of the",
"ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE RANKS (new column) for the Individual",
"INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) Define fitness ranks for the Individual Comparative Analysis",
"# E.coli/ P.putida KT initial biomass ratio # NH4 uptake ratio (E.coli/P.putida) #",
"# EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur =",
"= float(list_line[2]) KT_init = float(list_line[4]) NH4_Ec = float(list_line[5]) NH4_KT = float(list_line[6]) # Pi_Ec",
"THAT: \"NoDeadTracking\" means there is no death effect, thus the value for 'DT_cycles_init'",
"\"stats_description.txt\" # Which name? with open(filename, \"w\") as stats_file: for rank_limits_tuple in rank_limits_set:",
"FLYCOP run (configuration) as a single str line # ----------------------------------------------------------------------------- # Currently: specific",
"effect, thus the value for 'DT_cycles_init' is 0. # If the mean for",
"# ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT PARAMETERS FOR FLYCOP run (configuration) as",
"BIOMASS LOSS - when_death_starts (when this effect is first registered in a given",
"in range(1, len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0],",
"# For a fitness interval, retrieves all related information (rest of the parameters)",
"1. Obtains every single fitness rank # 2. Makes the subsequent statistical description",
"as a single str line - extract_ratios ANALYSIS OF BIOMASS LOSS - when_death_starts",
"# ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- #",
"- when_death_starts (when this effect is first registered in a given simulation) EXPECTED",
"0\" (to the numerator) # TO-DO: further implementation / reorganization of code lines",
"it has previously registered # INPUT: dataframe where to operate (pandas dataframe) #",
"a single str line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration: #",
"# Pi_KT = float(list_line[7]) # Pi_Ec_KT = round(Pi_Ec/Pi_KT, 3) return uptake_ratio, initbiomass_ratio, NH4_Ec_KT",
"on the established ranks # Instead of a number, the fitness interval itself",
"a single str line - extract_ratios ANALYSIS OF BIOMASS LOSS - when_death_starts (when",
"RATIOS OF INPUT PARAMETERS FOR FLYCOP run (configuration) as a single str line",
"would be taken into # account (in the denominator) and those with no",
"(FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE RANKS (new column) for the Individual Comparative",
"# ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration: # Sucrose/ fructose uptake rates",
"initbiomass_ratio # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT PARAMETERS FOR FLYCOP",
"los fitness # Limitación: ¿cómo haríamos cálculos individuales de un único parámetro estadístico?",
"dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init = DT_cycles[0] if DT_cycles_init != \"NoDeadTracking\": dataframe.loc[row[0], \"DT_cycles_init\"] = int(DT_cycles_init)",
"with 'Pandas' statistical description (method .describe()) - string_line_config. Example: -8.0,0.3,-12.0,0.05 OUTPUT See each",
"ref_colum): frac_dataframe = dataframe[dataframe[ref_colum] < rank_limits[1]] # Higher limit final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum] >",
"NH4_Ec = float(list_line[4]) NH4_KT = float(list_line[5]) NH4_Ec_KT = round(NH4_Ec/NH4_KT, 3) # Pi_Ec =",
"----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE",
"no biomass loss would \"sum 0\" (to the numerator) # TO-DO: further implementation",
"within each FLYCOP run # Utility required for further comparison of parameter ratios",
"description def describe_fitness_ranks(rank_limits_set, dataframe, descr_columns, ref_column): # 'SAVE STATS' version, if wanted to",
"organize_fitness_ranks EXTRACT INPUT PARAMETERS FOR A FLYCOP run (configuration) as a single str",
"to define and process fitness ranks (utility for scripts related to Statistical Analysis).",
"interval itself def organize_ranks(dataframe, rank_limits_set, ref_column, new_column): for row in dataframe.itertuples(): # row[0]",
"= float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) return uptake_ratio, initbiomass_ratio # ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------",
"single str line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake",
"no death effect, thus the value for 'DT_cycles_init' is 0. # If the",
"has previously registered # INPUT: dataframe where to operate (pandas dataframe) # OUTPUT:",
"extract_ratios ANALYSIS OF BIOMASS LOSS - when_death_starts (when this effect is first registered",
"Number ref_variable = dataframe.loc[row[0], ref_column] for i in range(1, len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1]",
"cycle when dead effect starts # NOTE THAT: \"NoDeadTracking\" means there is no",
"- string_line_config. Example: -8.0,0.3,-12.0,0.05 OUTPUT See each particular function NOTE THAT: Script in",
"----------------------------------------------------------------------------- # FUNCTION TO: obtain the initial cycle for death effect, from the",
"all configurations would be taken into # account (in the denominator) and those",
"rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"] = int(i) break elif ref_variable == 0: ConfigError = dataframe.loc[row[0]",
"parameters) - organize_fitness_ranks EXTRACT INPUT PARAMETERS FOR A FLYCOP run (configuration) as a",
"frac_dataframe: fraction of a particular dataframe - descr_columns: columns to be described with",
"# Pi_Ec_KT = round(Pi_Ec/Pi_KT, 3) return uptake_ratio, initbiomass_ratio, NH4_Ec_KT # ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------",
"FUNCTION TO: obtain the initial cycle for death effect, from the dataframe where",
"uptake rates ratio # E.coli/ P.putida KT initial biomass ratio # NH4 uptake",
"biomass ratio # NH4 uptake ratio (E.coli/P.putida) # Pi uptake ratio (E.coli/P.putida) #",
"python3 # -*- coding: utf-8 -*- \"\"\" Created on Sun Feb 21 21:20:59",
"uptake ratio (E.coli/P.putida) # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur =",
"float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur, 3) Ec_init = float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio =",
"retrieves all related information (rest of the parameters) def obtain_fitness_rank(rank_limits, dataframe, ref_colum): frac_dataframe",
"DESCRIPTION Series of functions to define and process fitness ranks (utility for scripts",
"= float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) NH4_Ec = float(list_line[4]) NH4_KT = float(list_line[5]) NH4_Ec_KT",
"Ec_init_glyc = float(list_line[2]) KT_init = float(list_line[4]) NH4_Ec = float(list_line[5]) NH4_KT = float(list_line[6]) #",
"P.putida KT initial biomass ratio # NH4 uptake ratio (E.coli/P.putida) # Pi uptake",
"fructose uptake rates ratio # E.coli/ P.putida KT initial biomass ratio # NH4",
"llevar análisis estadístico a archivo para posterior 'ComparativeAnalysis' entre configuraciones # Array 3D",
"'New_column' contains the categorical classification of values, depending on the established ranks #",
"de los rangos, hay que pasarle un límite superior más alto que el",
"hay que pasarle un límite superior más alto que el mejor de los",
"initbiomass_ratio = round(Ec_init/KT_init, 3) return uptake_ratio, initbiomass_ratio # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT",
"COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE FITNESS RANKS (new column 'FitRank')",
"# LIMITACIONES # ------------ # Limitación: el primero de los rangos, hay que",
"stat_descr = stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\" # 'PRINT' version for rank_limits_tuple in rank_limits_set:",
"dataframe.loc[row[0], new_column] = str(rank_tuple) break return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT",
"(E.coli/P.putida) # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_ratios_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur",
"3) return uptake_ratio, initbiomass_ratio, NH4_Ec_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT INPUT PARAMETERS",
"OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION Series of functions to define and",
"return uptake_ratio, initbiomass_ratio # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT PARAMETERS",
"21 21:20:59 2021 @author: <NAME> \"\"\" \"\"\" OUTPUT ANALYSIS AFTER FLYCOP (UTILITIES) DESCRIPTION",
"(when this effect is first registered in a given simulation) EXPECTED INPUT -",
"----------------------------------------------------------------------------- # EXTRACT RATIOS OF INPUT PARAMETERS FOR FLYCOP run (configuration) as a",
"ref_colum: reference column to extract the fraction of the dataframe. Default :'fitness' -",
"@author: <NAME> \"\"\" \"\"\" OUTPUT ANALYSIS AFTER FLYCOP (UTILITIES) DESCRIPTION ORGANIZATION OF FITNESS",
"\"DT_cycles\"].split(\"-\") DT_cycles_init = DT_cycles[0] if DT_cycles_init != \"NoDeadTracking\": dataframe.loc[row[0], \"DT_cycles_init\"] = int(DT_cycles_init) return",
"= rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], \"FitRank\"] = int(i) break",
"for 'DT_cycles_init' is 0. # If the mean for the death effect (initial",
"rank_limits[0]] # Lower limit return final_frac_dataframe # STATISTICAL DESCRIPTION for the selected fitness",
"a file \"\"\" filename = \"stats_description.txt\" # Which name? with open(filename, \"w\") as",
"\"FitRank\"] = int(i) break elif ref_variable == 0: ConfigError = dataframe.loc[row[0] , \"ZeroDivisionError\"]",
"# Lower limit return final_frac_dataframe # STATISTICAL DESCRIPTION for the selected fitness rank,",
"NH4 uptake ratio (E.coli/P.putida) # Pi uptake ratio (E.coli/P.putida) # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def",
"Feb 21 21:20:59 2021 @author: <NAME> \"\"\" \"\"\" OUTPUT ANALYSIS AFTER FLYCOP (UTILITIES)",
"is required def stats_description(frac_dataframe, descr_columns): stat_description = frac_dataframe[descr_columns].describe() return stat_description # COMBINES THE",
"pandas as pd # import os.path # ----------------------------------------------------------------------------- # ORGANIZATION OF FITNESS RANKS",
"- describe_fitness_ranks: combination of the last two functions INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run)",
"Comparative Analysis (FLYCOP run, input parameters) - organize_fitness_ranks EXTRACT INPUT PARAMETERS FOR A",
"KT initial biomass ratio # EXAMPLE: -8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config): list_line = string_line_config.split(\",\") sucr_ur",
"the numerator) # TO-DO: further implementation / reorganization of code lines # -----------------------------------------------------------------------------",
"ANALYSIS OF BIOMASS LOSS - when_death_starts (when this effect is first registered in",
"individual interval) - ref_colum: reference column to extract the fraction of the dataframe.",
"a fitness interval, retrieves all related information (rest of the parameters) def obtain_fitness_rank(rank_limits,",
"rates # Sucrose/ fructose uptake rates ratio # E.coli/ P.putida KT initial biomass",
"Pi_KT = float(list_line[7]) return sucr_ur, frc_ur, Ec_init, KT_init, NH4_Ec, NH4_KT # ----------------------------------------------------------------------------- #",
"frac_dataframe = dataframe[dataframe[ref_colum] < rank_limits[1]] # Higher limit final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]]",
"DT_cycles = dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init = DT_cycles[0] if DT_cycles_init != \"NoDeadTracking\": dataframe.loc[row[0], \"DT_cycles_init\"]",
"taken into # account (in the denominator) and those with no biomass loss",
"estadístico? Véase mean(), median() (individualmente) # AUTOMATIZAR # ------------------------------- # Set con tuplas",
"Makes the subsequent statistical description def describe_fitness_ranks(rank_limits_set, dataframe, descr_columns, ref_column): # 'SAVE STATS'",
"row in dataframe.itertuples(): # row[0] = Index Number ref_variable = dataframe.loc[row[0], ref_column] for",
"return dataframe # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) #",
"2021 @author: <NAME> \"\"\" \"\"\" OUTPUT ANALYSIS AFTER FLYCOP (UTILITIES) DESCRIPTION ORGANIZATION OF",
"= float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) NH4_Ec = float(list_line[4]) NH4_KT",
"to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config): list_line =",
"un único parámetro estadístico? Véase mean(), median() (individualmente) # AUTOMATIZAR # ------------------------------- #",
"= float(list_line[6]) # Pi_KT = float(list_line[7]) return sucr_ur, frc_ur, Ec_init, KT_init, NH4_Ec, NH4_KT",
"Individual Comparative Analysis within each FLYCOP run # The ranks are defined based",
"# ----------------------------------------------------------------------------- # RETURNS FRACTION OF INTEREST (fitness rank, all columns) OF THE",
"dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print() # LIMITACIONES",
"the statistical description is required def stats_description(frac_dataframe, descr_columns): stat_description = frac_dataframe[descr_columns].describe() return stat_description",
"mejor de los fitness # Limitación: ¿cómo haríamos cálculos individuales de un único",
"DESCRIPTION ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION Series of functions to",
"individuales de un único parámetro estadístico? Véase mean(), median() (individualmente) # AUTOMATIZAR #",
"STATS DESCRIPTION Series of functions to define and process fitness ranks (utility for",
"fitness rank in FLYCOP output tables def organize_fitness_ranks(dataframe, rank_limits_set, ref_column): for row in",
"----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # ----------------------------------------------------------------------------- # DEFINE RANKS (new",
"mean for the death effect (initial cycle) was computed, all configurations would be",
"name? with open(filename, \"w\") as stats_file: for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple,",
"NH4_Ec_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT INPUT PARAMETERS FOR FLYCOP run (configuration)",
"THE TWO LAST FUNCTIONS # 1. Obtains every single fitness rank # 2.",
"= float(list_line[4]) NH4_KT = float(list_line[5]) NH4_Ec_KT = round(NH4_Ec/NH4_KT, 3) # Pi_Ec = float(list_line[6])",
"simulation) EXPECTED INPUT - Dataframe: dataframe to be processed - rank_limits_set: tuple with",
"- obtain_fitness_rank - stats_description - describe_fitness_ranks: combination of the last two functions INDIVIDUAL",
"elif ref_variable == 0: ConfigError = dataframe.loc[row[0] , \"ZeroDivisionError\"] if ConfigError == 0:",
"given dataframe # 'New_column' contains the categorical classification of values, depending on the",
"is 0. # If the mean for the death effect (initial cycle) was",
"all related information (rest of the parameters) def obtain_fitness_rank(rank_limits, dataframe, ref_colum): frac_dataframe =",
"-8.0,0.3,-12.0,0.05 OUTPUT See each particular function NOTE THAT: Script in development (...) \"\"\"",
"rank_limits[1]] # Higher limit final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]] # Lower limit return",
"fitness rank # 2. Makes the subsequent statistical description def describe_fitness_ranks(rank_limits_set, dataframe, descr_columns,",
"ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION # ----------------------------------------------------------------------------- # RETURNS FRACTION",
"# Limitación: ¿cómo haríamos cálculos individuales de un único parámetro estadístico? Véase mean(),",
"mean(), median() (individualmente) # AUTOMATIZAR # ------------------------------- # Set con tuplas para los",
"ref_column) stat_descr = stats_description(fitness_rank, descr_columns) print(f\"{ref_column} rank: {rank_limits_tuple[0]}-{rank_limits_tuple[1]}\") print(stat_descr) print() # LIMITACIONES #",
"See each particular function NOTE THAT: Script in development (...) \"\"\" # import",
"FLYCOP run # Utility required for further comparison of parameter ratios of each",
"print() # LIMITACIONES # ------------ # Limitación: el primero de los rangos, hay",
"EXAMPLE: -4.0,0.15,-18.0,0.05,-6.0,-10.0,-0.2,-0.25 def extract_baseConfig_NP(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0]) frc_ur = float(list_line[3])",
"dataframe) # OUTPUT: same dataframe with new column: # 'DT_cycles_init': cycle when dead",
"DATAFRAME # For a fitness interval, retrieves all related information (rest of the",
"for i in range(1, len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if rank_tuple[0] < ref_variable <",
"0 else: dataframe.loc[row[0] , \"FitRank\"] = -1 return dataframe # ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------",
"= float(list_line[2]) uptake_ratio = round(sucr_ur/frc_ur, 3) Ec_init = float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio",
"when_death_starts (when this effect is first registered in a given simulation) EXPECTED INPUT",
"new column: # 'DT_cycles_init': cycle when dead effect starts # NOTE THAT: \"NoDeadTracking\"",
"be taken into # account (in the denominator) and those with no biomass",
"dataframe # 'New_column' contains the categorical classification of values, depending on the established",
"# import os.path # ----------------------------------------------------------------------------- # ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS",
"= round(Ec_init/KT_init, 3) return uptake_ratio, initbiomass_ratio # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT RATIOS",
"functions to define and process fitness ranks (utility for scripts related to Statistical",
"# ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT INPUT PARAMETERS FOR FLYCOP run (configuration) as",
"columns) OF THE DATAFRAME # For a fitness interval, retrieves all related information",
"= Index Number ref_variable = dataframe.loc[row[0], ref_column] for i in range(1, len(rank_limits_set)+1): rank_tuple",
"float(list_line[1]) # Ec_init_glyc = float(list_line[2]) KT_init = float(list_line[4]) NH4_Ec = float(list_line[5]) NH4_KT =",
"initbiomass_ratio = round(Ec_init/KT_init, 3) NH4_Ec = float(list_line[4]) NH4_KT = float(list_line[5]) NH4_Ec_KT = round(NH4_Ec/NH4_KT,",
"alto que el mejor de los fitness # Limitación: ¿cómo haríamos cálculos individuales",
"dataframe.itertuples(): DT_cycles = dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init = DT_cycles[0] if DT_cycles_init != \"NoDeadTracking\": dataframe.loc[row[0],",
"# ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # EXAMPLE:",
"the dataframe. Default :'fitness' - frac_dataframe: fraction of a particular dataframe - descr_columns:",
"= round(Ec_init/KT_init, 3) NH4_Ec = float(list_line[4]) NH4_KT = float(list_line[5]) NH4_Ec_KT = round(NH4_Ec/NH4_KT, 3)",
"lines # ----------------------------------------------------------------------------- def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] = 0 for row in dataframe.itertuples(): DT_cycles",
"run (configuration) as a single str line # ----------------------------------------------------------------------------- # Currently: specific to",
"# ----------------------------------------------------------------------------- # ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS DESCRIPTION # -----------------------------------------------------------------------------",
"the fitness interval itself def organize_ranks(dataframe, rank_limits_set, ref_column, new_column): for row in dataframe.itertuples():",
"tables def organize_fitness_ranks(dataframe, rank_limits_set, ref_column): for row in dataframe.itertuples(): # row[0] = Index",
"dataframe.loc[row[0], \"FitRank\"] = int(i) break elif ref_variable == 0: ConfigError = dataframe.loc[row[0] ,",
"# Set con tuplas para los rangos # NUEVA IDEA: llevar análisis estadístico",
"----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # Sucrose/ fructose",
"NH4_KT = float(list_line[6]) # Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) return sucr_ur,",
"the last two functions INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) Define fitness ranks for",
"itself def organize_ranks(dataframe, rank_limits_set, ref_column, new_column): for row in dataframe.itertuples(): # row[0] =",
"& ASSOCIATED STATS DESCRIPTION # ----------------------------------------------------------------------------- # RETURNS FRACTION OF INTEREST (fitness rank,",
"particular function NOTE THAT: Script in development (...) \"\"\" # import re #",
"----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # INDIVIDUAL COMPARATIVE ANALYSIS (FLYCOP run) # -----------------------------------------------------------------------------",
"Analysis within each FLYCOP run # Utility required for further comparison of parameter",
"ref_column, new_column): for row in dataframe.itertuples(): # row[0] = Index Number ref_variable =",
"len(rank_limits_set)+1): rank_tuple = rank_limits_set[i-1] if rank_tuple[0] < ref_variable < rank_tuple[1]: dataframe.loc[row[0], new_column] =",
"return sucr_ur, frc_ur, Ec_init, KT_init, NH4_Ec, NH4_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # FUNCTION",
"float(list_line[1]) KT_init = float(list_line[3]) initbiomass_ratio = round(Ec_init/KT_init, 3) NH4_Ec = float(list_line[4]) NH4_KT =",
"first registered in a given simulation) EXPECTED INPUT - Dataframe: dataframe to be",
"describe_fitness_ranks(rank_limits_set, dataframe, descr_columns, ref_column): # 'SAVE STATS' version, if wanted to be stored",
"for which the statistical description is required def stats_description(frac_dataframe, descr_columns): stat_description = frac_dataframe[descr_columns].describe()",
"biomass ratio # EXAMPLE: -8.0,0.3,-12.0,0.05 def extract_ratios(string_line_config): list_line = string_line_config.split(\",\") sucr_ur = float(list_line[0])",
"float(list_line[7]) # Pi_Ec_KT = round(Pi_Ec/Pi_KT, 3) return uptake_ratio, initbiomass_ratio, NH4_Ec_KT # ----------------------------------------------------------------------------- #",
"import pandas as pd # import os.path # ----------------------------------------------------------------------------- # ORGANIZATION OF FITNESS",
"# DEFINE RANKS (new column) for the Individual Comparative Analysis within each FLYCOP",
"configuraciones # Array 3D # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- #",
"# 'DT_cycles_init': cycle when dead effect starts # NOTE THAT: \"NoDeadTracking\" means there",
"Pi_Ec = float(list_line[6]) # Pi_KT = float(list_line[7]) return sucr_ur, frc_ur, Ec_init, KT_init, NH4_Ec,",
"re # import pandas as pd # import os.path # ----------------------------------------------------------------------------- # ORGANIZATION",
"COMBINES THE TWO LAST FUNCTIONS # 1. Obtains every single fitness rank #",
"reference column to extract the fraction of the dataframe. Default :'fitness' - frac_dataframe:",
"wanted to be stored in a file \"\"\" filename = \"stats_description.txt\" # Which",
"run # The ranks are defined based on the desired 'ref_column' in the",
"el primero de los rangos, hay que pasarle un límite superior más alto",
"row in dataframe.itertuples(): DT_cycles = dataframe.loc[row[0], \"DT_cycles\"].split(\"-\") DT_cycles_init = DT_cycles[0] if DT_cycles_init !=",
"run, input parameters) - organize_fitness_ranks EXTRACT INPUT PARAMETERS FOR A FLYCOP run (configuration)",
"-*- \"\"\" Created on Sun Feb 21 21:20:59 2021 @author: <NAME> \"\"\" \"\"\"",
"'FitRank') for the Individual Comparative Analysis within each FLYCOP run # Utility required",
"stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\" # 'PRINT' version for rank_limits_tuple in rank_limits_set: fitness_rank =",
"into # account (in the denominator) and those with no biomass loss would",
"# ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # Sucrose/",
"# Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration: # Sucrose/ fructose uptake rates ratio #",
", \"FitRank\"] = 0 else: dataframe.loc[row[0] , \"FitRank\"] = -1 return dataframe #",
"Index Number ref_variable = dataframe.loc[row[0], ref_column] for i in range(1, len(rank_limits_set)+1): rank_tuple =",
"def organize_ranks(dataframe, rank_limits_set, ref_column, new_column): for row in dataframe.itertuples(): # row[0] = Index",
"----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration: # Sucrose/ fructose uptake rates ratio",
"sucr_ur = float(list_line[0]) frc_ur = float(list_line[3]) Ec_init = float(list_line[1]) # Ec_init_glyc = float(list_line[2])",
"descr_columns, ref_column): # 'SAVE STATS' version, if wanted to be stored in a",
"return stat_description # COMBINES THE TWO LAST FUNCTIONS # 1. Obtains every single",
"as a single str line # ----------------------------------------------------------------------------- # Currently: specific to E.coli_iEC1364-P.putida_KT2440 configuration,",
"the mean for the death effect (initial cycle) was computed, all configurations would",
"# ----------------------------------------------------------------------------- def when_death_starts(dataframe): dataframe[\"DT_cycles_init\"] = 0 for row in dataframe.itertuples(): DT_cycles =",
"The ranks are defined based on the desired 'ref_column' in the given dataframe",
"EXTRACT INPUT PARAMETERS FOR FLYCOP run (configuration) as a single str line #",
"EXTRACT INPUT PARAMETERS FOR A FLYCOP run (configuration) as a single str line",
"the desired 'ref_column' in the given dataframe # 'New_column' contains the categorical classification",
"round(Pi_Ec/Pi_KT, 3) return uptake_ratio, initbiomass_ratio, NH4_Ec_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # EXTRACT INPUT",
"dataframe[dataframe[ref_colum] < rank_limits[1]] # Higher limit final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]] # Lower",
"be described with 'Pandas' statistical description (method .describe()) - string_line_config. Example: -8.0,0.3,-12.0,0.05 OUTPUT",
"configurations would be taken into # account (in the denominator) and those with",
"statistical description (method .describe()) - string_line_config. Example: -8.0,0.3,-12.0,0.05 OUTPUT See each particular function",
"specific to E.coli_iEC1364-P.putida_KT2440 configuration, with NP_uptake rates # Sucrose/ fructose uptake rates ratio",
"interval, retrieves all related information (rest of the parameters) def obtain_fitness_rank(rank_limits, dataframe, ref_colum):",
"Higher limit final_frac_dataframe = frac_dataframe[frac_dataframe[ref_colum] > rank_limits[0]] # Lower limit return final_frac_dataframe #",
"= obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr = stats_description(fitness_rank, descr_columns) stats_file.write(stat_descr+\"\\n\") \"\"\" # 'PRINT' version",
"OUTPUT ANALYSIS AFTER FLYCOP (UTILITIES) DESCRIPTION ORGANIZATION OF FITNESS RANKS & ASSOCIATED STATS",
"frc_ur, Ec_init, KT_init, NH4_Ec, NH4_KT # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # FUNCTION TO: obtain",
"to be stored in a file \"\"\" filename = \"stats_description.txt\" # Which name?",
"columns (parameters) for which the statistical description is required def stats_description(frac_dataframe, descr_columns): stat_description",
"# 'PRINT' version for rank_limits_tuple in rank_limits_set: fitness_rank = obtain_fitness_rank(rank_limits_tuple, dataframe, ref_column) stat_descr"
] |
[
"(b'', '<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def test_digest(self): for b,",
"self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x = hashlib.sha3_512() for i in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c'))",
"x.update(b) self.assertEqual(x.digest(), unhexlify(d)) x = hashlib.sha3_512() for i in range(1000000): x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87'))",
"] vectors_keccak = [ (b'', '<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ]",
"hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(), unhexlify(d)) x = hashlib.sha3_512() for i in range(1000000): x.update(b'a') self.assertEqual(x.digest(),",
"(b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak = [ (b'', '<KEY>'), (b'abc',",
"unhexlify(d)) def test_update(self): for b, d in self.vectors: x = hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(),",
"hashlib.sha3_512() for i in range(1000000): x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x = hashlib.sha3_512() for",
"self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def test_digest_keccak(self): for b, d in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d))",
"(b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak = [ (b'', '<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>',",
"range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def test_update_keccak(self): for b, d in self.vectors_keccak: x",
"x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) if __name__ == '__main__': unittest.main()",
"import hashlib class TestCryptoSha3_512(unittest.TestCase): # vectors from http://www.di-mgt.com.au/sha_testvectors.html vectors = [ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'),",
"= hashlib.sha3_512(keccak=True) d0 = x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1)",
"self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def test_update_keccak(self): for b, d in self.vectors_keccak: x = hashlib.sha3_512(keccak=True)",
"unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def test_update_keccak(self): for b, d in self.vectors_keccak: x = hashlib.sha3_512(keccak=True) x.update(b)",
"'18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def test_digest(self): for b, d in self.vectors:",
"b, d in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d)) def test_update(self): for b, d in",
"x = hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(), unhexlify(d)) def test_digest_multi(self): x = hashlib.sha3_512() d0 =",
"<gh_stars>0 from common import * from trezor.crypto import hashlib class TestCryptoSha3_512(unittest.TestCase): # vectors",
"d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) def test_digest_multi_keccak(self): x = hashlib.sha3_512(keccak=True) d0",
"(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak = [ (b'', '<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu',",
"in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d)) def test_update(self): for b, d in self.vectors: x",
"= hashlib.sha3_512() d0 = x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1)",
"'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def test_digest(self): for b, d in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def test_digest_keccak(self):",
"in range(1000000): x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x = hashlib.sha3_512() for i in range(16777216):",
"i in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def test_update_keccak(self): for b, d in",
"'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak = [ (b'', '<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'),",
"self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def test_digest_keccak(self): for b, d in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d)) def",
"x = hashlib.sha3_512() d0 = x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0,",
"unhexlify(d)) x = hashlib.sha3_512() for i in range(1000000): x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x",
"= x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) def test_digest_multi_keccak(self): x =",
"x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) def test_digest_multi_keccak(self): x = hashlib.sha3_512(keccak=True)",
"vectors_keccak = [ (b'', '<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def",
"x.update(b) self.assertEqual(x.digest(), unhexlify(d)) def test_digest_multi(self): x = hashlib.sha3_512() d0 = x.digest() d1 =",
"d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) if __name__ ==",
"for b, d in self.vectors_keccak: x = hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(), unhexlify(d)) def test_digest_multi(self):",
"d in self.vectors_keccak: x = hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(), unhexlify(d)) def test_digest_multi(self): x =",
"x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) if __name__",
"= hashlib.sha3_512() for i in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def test_update_keccak(self): for",
"x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) def test_digest_multi_keccak(self): x = hashlib.sha3_512(keccak=True) d0 = x.digest()",
"x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x = hashlib.sha3_512() for i in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(),",
"for i in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def test_update_keccak(self): for b, d",
"hashlib.sha3_512(keccak=True) d0 = x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0,",
"[ (b'', '<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def test_digest(self): for",
"'<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def test_digest(self): for b, d",
"for b, d in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def test_digest_keccak(self): for b, d in",
"def test_digest_keccak(self): for b, d in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d)) def test_update(self): for",
"self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d)) def test_update(self): for b, d in self.vectors: x = hashlib.sha3_512()",
"test_update(self): for b, d in self.vectors: x = hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(), unhexlify(d)) x",
"self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d)) def test_update(self): for b, d in self.vectors: x =",
"unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x = hashlib.sha3_512() for i in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) '''",
"= x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) def",
"d in self.vectors: x = hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(), unhexlify(d)) x = hashlib.sha3_512() for",
"(b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak = [ (b'',",
"''' x = hashlib.sha3_512() for i in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def",
"self.assertEqual(x.digest(), unhexlify(d)) x = hashlib.sha3_512() for i in range(1000000): x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) '''",
"i in range(1000000): x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x = hashlib.sha3_512() for i in",
"test_digest(self): for b, d in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def test_digest_keccak(self): for b, d",
"self.assertEqual(x.digest(), unhexlify(d)) def test_digest_multi(self): x = hashlib.sha3_512() d0 = x.digest() d1 = x.digest()",
"in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def test_update_keccak(self): for b, d in self.vectors_keccak:",
"in self.vectors_keccak: x = hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(), unhexlify(d)) def test_digest_multi(self): x = hashlib.sha3_512()",
"# vectors from http://www.di-mgt.com.au/sha_testvectors.html vectors = [ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'),",
"= hashlib.sha3_512() for i in range(1000000): x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x = hashlib.sha3_512()",
"x = hashlib.sha3_512() for i in range(1000000): x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x =",
"= x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) if",
"self.assertEqual(d0, d1) self.assertEqual(d0, d2) def test_digest_multi_keccak(self): x = hashlib.sha3_512(keccak=True) d0 = x.digest() d1",
"unhexlify(d)) def test_digest_multi(self): x = hashlib.sha3_512() d0 = x.digest() d1 = x.digest() d2",
"test_digest_multi_keccak(self): x = hashlib.sha3_512(keccak=True) d0 = x.digest() d1 = x.digest() d2 = x.digest()",
"x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def test_update_keccak(self): for b, d in self.vectors_keccak: x =",
"'04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak = [ (b'', '<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'),",
"keccak=True).digest(), unhexlify(d)) def test_update(self): for b, d in self.vectors: x = hashlib.sha3_512() x.update(b)",
"self.vectors: x = hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(), unhexlify(d)) x = hashlib.sha3_512() for i in",
"[ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak = [",
"(b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def test_digest(self): for b, d in",
"hashlib.sha3_512() for i in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def test_update_keccak(self): for b,",
"in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def test_digest_keccak(self): for b, d in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(),",
"x = hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(), unhexlify(d)) x = hashlib.sha3_512() for i in range(1000000):",
"= x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) def test_digest_multi_keccak(self): x = hashlib.sha3_512(keccak=True) d0 =",
"import * from trezor.crypto import hashlib class TestCryptoSha3_512(unittest.TestCase): # vectors from http://www.di-mgt.com.au/sha_testvectors.html vectors",
"test_update_keccak(self): for b, d in self.vectors_keccak: x = hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(), unhexlify(d)) def",
"test_digest_multi(self): x = hashlib.sha3_512() d0 = x.digest() d1 = x.digest() d2 = x.digest()",
"d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) def test_digest_multi_keccak(self): x",
"hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(), unhexlify(d)) def test_digest_multi(self): x = hashlib.sha3_512() d0 = x.digest() d1",
"(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def test_digest(self): for b, d in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def",
"for b, d in self.vectors: x = hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(), unhexlify(d)) x =",
"= x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) if __name__ == '__main__':",
"TestCryptoSha3_512(unittest.TestCase): # vectors from http://www.di-mgt.com.au/sha_testvectors.html vectors = [ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',",
"d in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d)) def test_update(self): for b, d in self.vectors:",
"class TestCryptoSha3_512(unittest.TestCase): # vectors from http://www.di-mgt.com.au/sha_testvectors.html vectors = [ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'),",
"vectors = [ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak",
"hashlib.sha3_512() d0 = x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0,",
"d1) self.assertEqual(d0, d2) def test_digest_multi_keccak(self): x = hashlib.sha3_512(keccak=True) d0 = x.digest() d1 =",
"d2) def test_digest_multi_keccak(self): x = hashlib.sha3_512(keccak=True) d0 = x.digest() d1 = x.digest() d2",
"def test_digest_multi_keccak(self): x = hashlib.sha3_512(keccak=True) d0 = x.digest() d1 = x.digest() d2 =",
"common import * from trezor.crypto import hashlib class TestCryptoSha3_512(unittest.TestCase): # vectors from http://www.di-mgt.com.au/sha_testvectors.html",
"'<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def test_digest(self): for b, d in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d))",
"'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak = [ (b'', '<KEY>'),",
"trezor.crypto import hashlib class TestCryptoSha3_512(unittest.TestCase): # vectors from http://www.di-mgt.com.au/sha_testvectors.html vectors = [ (b'',",
"self.vectors_keccak: x = hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(), unhexlify(d)) def test_digest_multi(self): x = hashlib.sha3_512() d0",
"for i in range(1000000): x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x = hashlib.sha3_512() for i",
"range(1000000): x.update(b'a') self.assertEqual(x.digest(), unhexlify('3c3a876da14034ab60627c077bb98f7e120a2a5370212dffb3385a18d4f38859ed311d0a9d5141ce9cc5c66ee689b266a8aa18ace8282a0e0db596c90b0a7b87')) ''' x = hashlib.sha3_512() for i in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno')",
"= [ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak =",
"'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ] vectors_keccak = [ (b'', '<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'),",
"b, d in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def test_digest_keccak(self): for b, d in self.vectors_keccak:",
"''' def test_update_keccak(self): for b, d in self.vectors_keccak: x = hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(),",
"def test_digest_multi(self): x = hashlib.sha3_512() d0 = x.digest() d1 = x.digest() d2 =",
"x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2) def test_digest_multi_keccak(self):",
"from http://www.di-mgt.com.au/sha_testvectors.html vectors = [ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'),",
"from trezor.crypto import hashlib class TestCryptoSha3_512(unittest.TestCase): # vectors from http://www.di-mgt.com.au/sha_testvectors.html vectors = [",
"def test_update_keccak(self): for b, d in self.vectors_keccak: x = hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(), unhexlify(d))",
"def test_digest(self): for b, d in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def test_digest_keccak(self): for b,",
"test_digest_keccak(self): for b, d in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d)) def test_update(self): for b,",
"vectors from http://www.di-mgt.com.au/sha_testvectors.html vectors = [ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu',",
"b, d in self.vectors_keccak: x = hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(), unhexlify(d)) def test_digest_multi(self): x",
"from common import * from trezor.crypto import hashlib class TestCryptoSha3_512(unittest.TestCase): # vectors from",
"d in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def test_digest_keccak(self): for b, d in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b,",
"* from trezor.crypto import hashlib class TestCryptoSha3_512(unittest.TestCase): # vectors from http://www.di-mgt.com.au/sha_testvectors.html vectors =",
"hashlib class TestCryptoSha3_512(unittest.TestCase): # vectors from http://www.di-mgt.com.au/sha_testvectors.html vectors = [ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc',",
"(b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def test_digest(self): for b, d in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(),",
"] def test_digest(self): for b, d in self.vectors: self.assertEqual(hashlib.sha3_512(b).digest(), unhexlify(d)) def test_digest_keccak(self): for",
"http://www.di-mgt.com.au/sha_testvectors.html vectors = [ (b'', 'a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26'), (b'abc', 'b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0'), (b'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '04a371e84ecfb5b8b77cb48610fca8182dd457ce6f326a0fd3d7ec2f1e91636dee691fbe0c985302ba1b0d8dc78c086346b533b49c030d99a27daf1139d6e75e'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185'), ]",
"= hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(), unhexlify(d)) x = hashlib.sha3_512() for i in range(1000000): x.update(b'a')",
"d0 = x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0, d1) self.assertEqual(d0, d2)",
"for b, d in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d)) def test_update(self): for b, d",
"unhexlify(d)) def test_digest_keccak(self): for b, d in self.vectors_keccak: self.assertEqual(hashlib.sha3_512(b, keccak=True).digest(), unhexlify(d)) def test_update(self):",
"self.assertEqual(d0, d2) def test_digest_multi_keccak(self): x = hashlib.sha3_512(keccak=True) d0 = x.digest() d1 = x.digest()",
"x = hashlib.sha3_512() for i in range(16777216): x.update(b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno') self.assertEqual(x.digest(), unhexlify('235ffd53504ef836a1342b488f483b396eabbfe642cf78ee0d31feec788b23d0d18d5c339550dd5958a500d4b95363da1b5fa18affc1bab2292dc63b7d85097c')) ''' def test_update_keccak(self):",
"= [ (b'', '<KEY>'), (b'abc', '18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96'), (b'<KEY>', '<KEY>'), (b'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682'), ] def test_digest(self):",
"x = hashlib.sha3_512(keccak=True) d0 = x.digest() d1 = x.digest() d2 = x.digest() self.assertEqual(d0,",
"b, d in self.vectors: x = hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(), unhexlify(d)) x = hashlib.sha3_512()",
"in self.vectors: x = hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(), unhexlify(d)) x = hashlib.sha3_512() for i",
"= hashlib.sha3_512(keccak=True) x.update(b) self.assertEqual(x.digest(), unhexlify(d)) def test_digest_multi(self): x = hashlib.sha3_512() d0 = x.digest()",
"def test_update(self): for b, d in self.vectors: x = hashlib.sha3_512() x.update(b) self.assertEqual(x.digest(), unhexlify(d))"
] |
[
"commands from bot_constant import bot_constant from command_handler import command_handler from bot_listener import bot_listener",
"import commands from bot_constant import bot_constant from command_handler import command_handler from bot_listener import",
"self.bot.add_cog(self.command_handler) self.bot_listener = bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot() def start_bot(self) -> None: self.bot.run(bot_constant.bot_token) def get_command_handler(self)",
"import bot_constant from command_handler import command_handler from bot_listener import bot_listener class bot_manager: def",
"= bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot() def start_bot(self) -> None: self.bot.run(bot_constant.bot_token) def get_command_handler(self) -> command_handler:",
"def get_command_handler(self) -> command_handler: return self.command_handler def get_bot_listener(self) -> bot_listener: return self.bot_listener def",
"self.command_handler def get_bot_listener(self) -> bot_listener: return self.bot_listener def get_bot(self) -> commands.Bot: return self.bot",
"from bot_constant import bot_constant from command_handler import command_handler from bot_listener import bot_listener class",
"def start_bot(self) -> None: self.bot.run(bot_constant.bot_token) def get_command_handler(self) -> command_handler: return self.command_handler def get_bot_listener(self)",
"command_handler import command_handler from bot_listener import bot_listener class bot_manager: def __init__(self): self.bot =",
"class bot_manager: def __init__(self): self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler = command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener",
"__init__(self): self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler = command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener = bot_listener() self.bot.add_cog(self.bot_listener)",
"start_bot(self) -> None: self.bot.run(bot_constant.bot_token) def get_command_handler(self) -> command_handler: return self.command_handler def get_bot_listener(self) ->",
"bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot() def start_bot(self) -> None: self.bot.run(bot_constant.bot_token) def get_command_handler(self) -> command_handler: return",
"command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener = bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot() def start_bot(self) -> None: self.bot.run(bot_constant.bot_token) def",
"self.bot_listener = bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot() def start_bot(self) -> None: self.bot.run(bot_constant.bot_token) def get_command_handler(self) ->",
"import bot_listener class bot_manager: def __init__(self): self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler = command_handler(self.bot)",
"-> command_handler: return self.command_handler def get_bot_listener(self) -> bot_listener: return self.bot_listener def get_bot(self) ->",
"from command_handler import command_handler from bot_listener import bot_listener class bot_manager: def __init__(self): self.bot",
"def __init__(self): self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler = command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener = bot_listener()",
"description=bot_constant.bot_description) self.command_handler = command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener = bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot() def start_bot(self) ->",
"import command_handler from bot_listener import bot_listener class bot_manager: def __init__(self): self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix,",
"bot_manager: def __init__(self): self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler = command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener =",
"bot_constant import bot_constant from command_handler import command_handler from bot_listener import bot_listener class bot_manager:",
"bot_listener class bot_manager: def __init__(self): self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler = command_handler(self.bot) self.bot.add_cog(self.command_handler)",
"command_handler: return self.command_handler def get_bot_listener(self) -> bot_listener: return self.bot_listener def get_bot(self) -> commands.Bot:",
"self.bot.add_cog(self.bot_listener) self.start_bot() def start_bot(self) -> None: self.bot.run(bot_constant.bot_token) def get_command_handler(self) -> command_handler: return self.command_handler",
"<reponame>NgLamVN/HiBot<gh_stars>0 from discord.ext import commands from bot_constant import bot_constant from command_handler import command_handler",
"bot_constant from command_handler import command_handler from bot_listener import bot_listener class bot_manager: def __init__(self):",
"None: self.bot.run(bot_constant.bot_token) def get_command_handler(self) -> command_handler: return self.command_handler def get_bot_listener(self) -> bot_listener: return",
"= commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler = command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener = bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot() def",
"= command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener = bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot() def start_bot(self) -> None: self.bot.run(bot_constant.bot_token)",
"return self.command_handler def get_bot_listener(self) -> bot_listener: return self.bot_listener def get_bot(self) -> commands.Bot: return",
"discord.ext import commands from bot_constant import bot_constant from command_handler import command_handler from bot_listener",
"self.start_bot() def start_bot(self) -> None: self.bot.run(bot_constant.bot_token) def get_command_handler(self) -> command_handler: return self.command_handler def",
"self.command_handler = command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener = bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot() def start_bot(self) -> None:",
"self.bot.run(bot_constant.bot_token) def get_command_handler(self) -> command_handler: return self.command_handler def get_bot_listener(self) -> bot_listener: return self.bot_listener",
"get_command_handler(self) -> command_handler: return self.command_handler def get_bot_listener(self) -> bot_listener: return self.bot_listener def get_bot(self)",
"self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler = command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener = bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot()",
"commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler = command_handler(self.bot) self.bot.add_cog(self.command_handler) self.bot_listener = bot_listener() self.bot.add_cog(self.bot_listener) self.start_bot() def start_bot(self)",
"from bot_listener import bot_listener class bot_manager: def __init__(self): self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler",
"-> None: self.bot.run(bot_constant.bot_token) def get_command_handler(self) -> command_handler: return self.command_handler def get_bot_listener(self) -> bot_listener:",
"command_handler from bot_listener import bot_listener class bot_manager: def __init__(self): self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description)",
"bot_listener import bot_listener class bot_manager: def __init__(self): self.bot = commands.Bot(command_prefix=bot_constant.bot_prefix, description=bot_constant.bot_description) self.command_handler =",
"from discord.ext import commands from bot_constant import bot_constant from command_handler import command_handler from"
] |
[
"\"ATHENS\" #upload data try: city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") except Exception:",
"and predicted_price/real_price > 1 - precision: aces += 1 del train_set[\"distance\"] average_deviation =",
"= test_set.loc[[index], :][\"price\"] real_price = real_price.item() differences_squared.append((predicted_price - real_price)**2) if predicted_price/real_price < 1",
"+ city + \"_listings.csv\") city = \"HONG KONG\" if city == \"LOS ANGELES\":",
"\"SAN FRANCISCO\" #select relevant columns from the data city_listings = city_listings[columns] #drop room",
"normalise for items in columns[1:]: mean = city_listings[items].mean() std = np.std(city_listings[items]) N_items =",
"city + \"_listings.csv\") except Exception: if city == \"HONG KONG\": city = \"HK\"",
"city_listings.sample(frac=1,random_state=0) #remove unwanted sharacters city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private room type to 0",
"= sum(differences_squared) / float(len(differences_squared)) print \"Aces: \", aces rmse = (average_deviation)**0.5 print \"Rmse:",
"= city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private room type to 0 and entire home/apt to 1",
"no reviews city_listings = city_listings.dropna() #shuffle city_listings = city_listings.sample(frac=1,random_state=0) #remove unwanted sharacters city_listings['price']",
"\"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f = train_set[feature_cols] test_set_f = test_set[feature_cols]",
"\"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f = train_set[feature_cols] test_set_f = test_set[feature_cols] standard_deviation = 0 k =",
"= city_listings[items].mean() std = np.std(city_listings[items]) N_items = \"N_\"+items city_listings[N_items] = (city_listings[items] - mean)",
"train, 25% as test train_set = city_listings.iloc[:split_value] test_set = city_listings.iloc[split_value:] print test_set.head(5) #we",
"== \"SAN FRANCISCO\": city = \"SF\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\")",
"knn = train_set.iloc[:k] predicted_price = knn[\"price\"].mean() predicted_price = predicted_price.item() real_price = test_set.loc[[index], :][\"price\"]",
"= 0 k = 5 aces = 0 differences_squared = [] precision =",
"precision = 0.30 for index, rows in test_set_f.iterrows(): distance_series = train_set_f.apply(lambda row: distance.euclidean(rows,",
"json.load(json_data) del cities_dict['EXAMPLE'] #choose the city city = \"ATHENS\" #upload data try: city_listings",
"mean_price = city_listings[\"price\"].mean() split_value = int(round(float(city_listings.shape[0])*75/100)) #we use 75% of the dataset as",
"std = np.std(city_listings[items]) N_items = \"N_\"+items city_listings[N_items] = (city_listings[items] - mean) / std",
"== \"HONG KONG\": city = \"HK\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\")",
"\"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f = train_set[feature_cols] test_set_f = test_set[feature_cols] standard_deviation = 0 k",
"\"number_of_reviews\", \"latitude\", \"longitude\", \"review_scores_value\"] #load cities' information with open('cities_dictionary.json') as json_data: cities_dict =",
"except Exception: if city == \"HONG KONG\": city = \"HK\" city_listings = pd.read_csv(\"DATA/raw/\"",
"\"N_bathrooms\", \"N_beds\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f = train_set[feature_cols] test_set_f = test_set[feature_cols] standard_deviation",
"\"_listings.csv\") except Exception: if city == \"HONG KONG\": city = \"HK\" city_listings =",
"= test_set[feature_cols] standard_deviation = 0 k = 5 aces = 0 differences_squared =",
"city_listings[N_items] = (city_listings[items] - mean) / std N_columns = [\"price\", \"N_room_type\", \"N_accommodates\", \"N_bedrooms\",",
"columns = [\"price\", \"room_type\", \"accommodates\", \"bedrooms\", \"bathrooms\", \"beds\", \"number_of_reviews\", \"latitude\", \"longitude\", \"review_scores_value\"] #load",
"with open('cities_dictionary.json') as json_data: cities_dict = json.load(json_data) del cities_dict['EXAMPLE'] #choose the city city",
"the city city = \"ATHENS\" #upload data try: city_listings = pd.read_csv(\"DATA/raw/\" + city",
"normal_city_listings = city_listings[N_columns] train_set = normal_city_listings.iloc[:2888] test_set = normal_city_listings.iloc[2888:] #choose columns you want",
"> 1 - precision: aces += 1 del train_set[\"distance\"] average_deviation = sum(differences_squared) /",
"into account for the purpose of calculating the price feature_cols = [\"N_room_type\", \"N_accommodates\",",
"columns[1:]: mean = city_listings[items].mean() std = np.std(city_listings[items]) N_items = \"N_\"+items city_listings[N_items] = (city_listings[items]",
"train_set.sort_values(\"distance\", inplace=True) knn = train_set.iloc[:k] predicted_price = knn[\"price\"].mean() predicted_price = predicted_price.item() real_price =",
"private room type to 0 and entire home/apt to 1 city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True)",
"math columns = [\"price\", \"room_type\", \"accommodates\", \"bedrooms\", \"bathrooms\", \"beds\", \"number_of_reviews\", \"latitude\", \"longitude\", \"review_scores_value\"]",
"\", rmse, \"for a price mean: \", mean_price acespercent = float(aces)/float(test_set.shape[0]) print \"Accuracy",
"drop items which have no reviews city_listings = city_listings.dropna() #shuffle city_listings = city_listings.sample(frac=1,random_state=0)",
"NaN rows, which means we mostly drop items which have no reviews city_listings",
"city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True) mean_price = city_listings[\"price\"].mean() split_value = int(round(float(city_listings.shape[0])*75/100)) #we",
"\"Aces: \", aces rmse = (average_deviation)**0.5 print \"Rmse: \", rmse, \"for a price",
"the data city_listings = city_listings[columns] #drop room types that are not well formatted",
"mean) / std N_columns = [\"price\", \"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\", \"N_latitude\",",
"(city_listings[items] - mean) / std N_columns = [\"price\", \"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\",",
"(city_listings[\"room_type\"] == \"Entire home/apt\") | (city_listings[\"room_type\"] == \"Private room\") city_listings = city_listings[TF] #drop",
"predicted_price/real_price > 1 - precision: aces += 1 del train_set[\"distance\"] average_deviation = sum(differences_squared)",
"train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True) knn = train_set.iloc[:k] predicted_price = knn[\"price\"].mean() predicted_price = predicted_price.item() real_price",
"a price mean: \", mean_price acespercent = float(aces)/float(test_set.shape[0]) print \"Accuracy %:\", acespercent, \"with",
"\"review_scores_value\"] #load cities' information with open('cities_dictionary.json') as json_data: cities_dict = json.load(json_data) del cities_dict['EXAMPLE']",
"city == \"SAN FRANCISCO\": city = \"SF\" city_listings = pd.read_csv(\"DATA/raw/\" + city +",
"\"LOS ANGELES\": city = \"LA\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city",
"city = \"LOS ANGELES\" if city == \"SAN FRANCISCO\": city = \"SF\" city_listings",
"\"N_number_of_reviews\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\"] #drop old columns normal_city_listings = city_listings[N_columns] train_set = normal_city_listings.iloc[:2888]",
"+= 1 del train_set[\"distance\"] average_deviation = sum(differences_squared) / float(len(differences_squared)) print \"Aces: \", aces",
"sharacters city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private room type to 0 and entire home/apt",
"= pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") except Exception: if city == \"HONG KONG\":",
"index, rows in test_set_f.iterrows(): distance_series = train_set_f.apply(lambda row: distance.euclidean(rows, row), axis=1) train_set =",
"scipy.spatial import distance import sys import json import math columns = [\"price\", \"room_type\",",
"1 - precision: aces += 1 del train_set[\"distance\"] average_deviation = sum(differences_squared) / float(len(differences_squared))",
"rmse, \"for a price mean: \", mean_price acespercent = float(aces)/float(test_set.shape[0]) print \"Accuracy %:\",",
"and entire home/apt to 1 city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True) mean_price =",
"N_columns = [\"price\", \"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\"] #drop",
"cities_dict['EXAMPLE'] #choose the city city = \"ATHENS\" #upload data try: city_listings = pd.read_csv(\"DATA/raw/\"",
"print \"Aces: \", aces rmse = (average_deviation)**0.5 print \"Rmse: \", rmse, \"for a",
"city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private room type to 0 and entire home/apt to 1 city_listings['room_type'].replace(\"Private",
"if city == \"LOS ANGELES\": city = \"LA\" city_listings = pd.read_csv(\"DATA/raw/\" + city",
"= normal_city_listings.iloc[2888:] #choose columns you want to take into account for the purpose",
"\"_listings.csv\") city = \"SAN FRANCISCO\" #select relevant columns from the data city_listings =",
"relevant columns from the data city_listings = city_listings[columns] #drop room types that are",
"feature_cols = [\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f =",
"[] precision = 0.30 for index, rows in test_set_f.iterrows(): distance_series = train_set_f.apply(lambda row:",
"+ precision and predicted_price/real_price > 1 - precision: aces += 1 del train_set[\"distance\"]",
"city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"LOS ANGELES\" if city",
"= city_listings[TF] #drop NaN rows, which means we mostly drop items which have",
"\"N_latitude\", \"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f = train_set[feature_cols] test_set_f = test_set[feature_cols] standard_deviation = 0",
"= 5 aces = 0 differences_squared = [] precision = 0.30 for index,",
"city + \"_listings.csv\") city = \"HONG KONG\" if city == \"LOS ANGELES\": city",
"\"beds\", \"number_of_reviews\", \"latitude\", \"longitude\", \"review_scores_value\"] #load cities' information with open('cities_dictionary.json') as json_data: cities_dict",
"\"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\"] #drop old columns normal_city_listings =",
"np.std(city_listings[items]) N_items = \"N_\"+items city_listings[N_items] = (city_listings[items] - mean) / std N_columns =",
"= city_listings[N_columns] train_set = normal_city_listings.iloc[:2888] test_set = normal_city_listings.iloc[2888:] #choose columns you want to",
"\"Entire home/apt\") | (city_listings[\"room_type\"] == \"Private room\") city_listings = city_listings[TF] #drop NaN rows,",
"#set private room type to 0 and entire home/apt to 1 city_listings['room_type'].replace(\"Private room\",",
"formatted TF = (city_listings[\"room_type\"] == \"Entire home/apt\") | (city_listings[\"room_type\"] == \"Private room\") city_listings",
"= \"HONG KONG\" if city == \"LOS ANGELES\": city = \"LA\" city_listings =",
"\", mean_price acespercent = float(aces)/float(test_set.shape[0]) print \"Accuracy %:\", acespercent, \"with a precision: \",",
"= city_listings.sample(frac=1,random_state=0) #remove unwanted sharacters city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private room type to",
"train_set_f = train_set[feature_cols] test_set_f = test_set[feature_cols] standard_deviation = 0 k = 5 aces",
"which means we mostly drop items which have no reviews city_listings = city_listings.dropna()",
"to 1 city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True) mean_price = city_listings[\"price\"].mean() split_value =",
"as json_data: cities_dict = json.load(json_data) del cities_dict['EXAMPLE'] #choose the city city = \"ATHENS\"",
"rows, which means we mostly drop items which have no reviews city_listings =",
"city city = \"ATHENS\" #upload data try: city_listings = pd.read_csv(\"DATA/raw/\" + city +",
"= \"SF\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"SAN FRANCISCO\"",
"= city_listings.iloc[:split_value] test_set = city_listings.iloc[split_value:] print test_set.head(5) #we normalise for items in columns[1:]:",
"KONG\": city = \"HK\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city =",
"0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True) mean_price = city_listings[\"price\"].mean() split_value = int(round(float(city_listings.shape[0])*75/100)) #we use 75%",
"= train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True) knn = train_set.iloc[:k] predicted_price = knn[\"price\"].mean() predicted_price = predicted_price.item()",
"train_set_f.apply(lambda row: distance.euclidean(rows, row), axis=1) train_set = train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True) knn = train_set.iloc[:k]",
"predicted_price = predicted_price.item() real_price = test_set.loc[[index], :][\"price\"] real_price = real_price.item() differences_squared.append((predicted_price - real_price)**2)",
"the dataset as train, 25% as test train_set = city_listings.iloc[:split_value] test_set = city_listings.iloc[split_value:]",
"entire home/apt to 1 city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True) mean_price = city_listings[\"price\"].mean()",
"\"accommodates\", \"bedrooms\", \"bathrooms\", \"beds\", \"number_of_reviews\", \"latitude\", \"longitude\", \"review_scores_value\"] #load cities' information with open('cities_dictionary.json')",
"try: city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") except Exception: if city ==",
"+ city + \"_listings.csv\") city = \"SAN FRANCISCO\" #select relevant columns from the",
"cities_dict = json.load(json_data) del cities_dict['EXAMPLE'] #choose the city city = \"ATHENS\" #upload data",
"#remove unwanted sharacters city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private room type to 0 and",
"sys import json import math columns = [\"price\", \"room_type\", \"accommodates\", \"bedrooms\", \"bathrooms\", \"beds\",",
"\"bedrooms\", \"bathrooms\", \"beds\", \"number_of_reviews\", \"latitude\", \"longitude\", \"review_scores_value\"] #load cities' information with open('cities_dictionary.json') as",
"import pandas as pd import numpy as np from scipy.spatial import distance import",
"columns normal_city_listings = city_listings[N_columns] train_set = normal_city_listings.iloc[:2888] test_set = normal_city_listings.iloc[2888:] #choose columns you",
"#choose columns you want to take into account for the purpose of calculating",
"#drop old columns normal_city_listings = city_listings[N_columns] train_set = normal_city_listings.iloc[:2888] test_set = normal_city_listings.iloc[2888:] #choose",
"the price feature_cols = [\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"]",
"items in columns[1:]: mean = city_listings[items].mean() std = np.std(city_listings[items]) N_items = \"N_\"+items city_listings[N_items]",
"float(len(differences_squared)) print \"Aces: \", aces rmse = (average_deviation)**0.5 print \"Rmse: \", rmse, \"for",
"import json import math columns = [\"price\", \"room_type\", \"accommodates\", \"bedrooms\", \"bathrooms\", \"beds\", \"number_of_reviews\",",
"normal_city_listings.iloc[:2888] test_set = normal_city_listings.iloc[2888:] #choose columns you want to take into account for",
"real_price = real_price.item() differences_squared.append((predicted_price - real_price)**2) if predicted_price/real_price < 1 + precision and",
"data try: city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") except Exception: if city",
"(city_listings[\"room_type\"] == \"Private room\") city_listings = city_listings[TF] #drop NaN rows, which means we",
"city == \"HONG KONG\": city = \"HK\" city_listings = pd.read_csv(\"DATA/raw/\" + city +",
"pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"LOS ANGELES\" if city == \"SAN",
"1 + precision and predicted_price/real_price > 1 - precision: aces += 1 del",
"open('cities_dictionary.json') as json_data: cities_dict = json.load(json_data) del cities_dict['EXAMPLE'] #choose the city city =",
"mean = city_listings[items].mean() std = np.std(city_listings[items]) N_items = \"N_\"+items city_listings[N_items] = (city_listings[items] -",
"import distance import sys import json import math columns = [\"price\", \"room_type\", \"accommodates\",",
"json_data: cities_dict = json.load(json_data) del cities_dict['EXAMPLE'] #choose the city city = \"ATHENS\" #upload",
"as pd import numpy as np from scipy.spatial import distance import sys import",
"\"N_review_scores_value\"] #drop old columns normal_city_listings = city_listings[N_columns] train_set = normal_city_listings.iloc[:2888] test_set = normal_city_listings.iloc[2888:]",
"test train_set = city_listings.iloc[:split_value] test_set = city_listings.iloc[split_value:] print test_set.head(5) #we normalise for items",
"\"HK\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"HONG KONG\" if",
"ANGELES\": city = \"LA\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city =",
"for items in columns[1:]: mean = city_listings[items].mean() std = np.std(city_listings[items]) N_items = \"N_\"+items",
"columns from the data city_listings = city_listings[columns] #drop room types that are not",
"home/apt to 1 city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True) mean_price = city_listings[\"price\"].mean() split_value",
"of the dataset as train, 25% as test train_set = city_listings.iloc[:split_value] test_set =",
"city_listings[columns] #drop room types that are not well formatted TF = (city_listings[\"room_type\"] ==",
"= int(round(float(city_listings.shape[0])*75/100)) #we use 75% of the dataset as train, 25% as test",
"predicted_price.item() real_price = test_set.loc[[index], :][\"price\"] real_price = real_price.item() differences_squared.append((predicted_price - real_price)**2) if predicted_price/real_price",
"which have no reviews city_listings = city_listings.dropna() #shuffle city_listings = city_listings.sample(frac=1,random_state=0) #remove unwanted",
"data city_listings = city_listings[columns] #drop room types that are not well formatted TF",
"city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") except Exception: if city == \"HONG",
"pd import numpy as np from scipy.spatial import distance import sys import json",
"= knn[\"price\"].mean() predicted_price = predicted_price.item() real_price = test_set.loc[[index], :][\"price\"] real_price = real_price.item() differences_squared.append((predicted_price",
"in columns[1:]: mean = city_listings[items].mean() std = np.std(city_listings[items]) N_items = \"N_\"+items city_listings[N_items] =",
"as np from scipy.spatial import distance import sys import json import math columns",
"the purpose of calculating the price feature_cols = [\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\",",
"0 differences_squared = [] precision = 0.30 for index, rows in test_set_f.iterrows(): distance_series",
"for index, rows in test_set_f.iterrows(): distance_series = train_set_f.apply(lambda row: distance.euclidean(rows, row), axis=1) train_set",
"aces += 1 del train_set[\"distance\"] average_deviation = sum(differences_squared) / float(len(differences_squared)) print \"Aces: \",",
"\"LA\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"LOS ANGELES\" if",
"FRANCISCO\" #select relevant columns from the data city_listings = city_listings[columns] #drop room types",
"test_set = normal_city_listings.iloc[2888:] #choose columns you want to take into account for the",
"means we mostly drop items which have no reviews city_listings = city_listings.dropna() #shuffle",
"dataset as train, 25% as test train_set = city_listings.iloc[:split_value] test_set = city_listings.iloc[split_value:] print",
"= city_listings.iloc[split_value:] print test_set.head(5) #we normalise for items in columns[1:]: mean = city_listings[items].mean()",
"5 aces = 0 differences_squared = [] precision = 0.30 for index, rows",
"#shuffle city_listings = city_listings.sample(frac=1,random_state=0) #remove unwanted sharacters city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private room",
"we mostly drop items which have no reviews city_listings = city_listings.dropna() #shuffle city_listings",
"purpose of calculating the price feature_cols = [\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_latitude\",",
"city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"SAN FRANCISCO\" #select relevant",
"+ \"_listings.csv\") city = \"HONG KONG\" if city == \"LOS ANGELES\": city =",
"price mean: \", mean_price acespercent = float(aces)/float(test_set.shape[0]) print \"Accuracy %:\", acespercent, \"with a",
"city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private room type to 0 and entire home/apt to",
"= city_listings.dropna() #shuffle city_listings = city_listings.sample(frac=1,random_state=0) #remove unwanted sharacters city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set",
"distance.euclidean(rows, row), axis=1) train_set = train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True) knn = train_set.iloc[:k] predicted_price =",
"room\") city_listings = city_listings[TF] #drop NaN rows, which means we mostly drop items",
"== \"Entire home/apt\") | (city_listings[\"room_type\"] == \"Private room\") city_listings = city_listings[TF] #drop NaN",
"+ \"_listings.csv\") city = \"SAN FRANCISCO\" #select relevant columns from the data city_listings",
"city_listings = city_listings.sample(frac=1,random_state=0) #remove unwanted sharacters city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private room type",
"room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True) mean_price = city_listings[\"price\"].mean() split_value = int(round(float(city_listings.shape[0])*75/100)) #we use",
"+ \"_listings.csv\") except Exception: if city == \"HONG KONG\": city = \"HK\" city_listings",
"account for the purpose of calculating the price feature_cols = [\"N_room_type\", \"N_accommodates\", \"N_bedrooms\",",
"city = \"HONG KONG\" if city == \"LOS ANGELES\": city = \"LA\" city_listings",
"pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"SAN FRANCISCO\" #select relevant columns from",
"price feature_cols = [\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f",
"train_set[feature_cols] test_set_f = test_set[feature_cols] standard_deviation = 0 k = 5 aces = 0",
"real_price)**2) if predicted_price/real_price < 1 + precision and predicted_price/real_price > 1 - precision:",
"city = \"LA\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"LOS",
"city_listings[\"price\"].mean() split_value = int(round(float(city_listings.shape[0])*75/100)) #we use 75% of the dataset as train, 25%",
"TF = (city_listings[\"room_type\"] == \"Entire home/apt\") | (city_listings[\"room_type\"] == \"Private room\") city_listings =",
"\"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\"] #drop old columns normal_city_listings = city_listings[N_columns] train_set",
"test_set = city_listings.iloc[split_value:] print test_set.head(5) #we normalise for items in columns[1:]: mean =",
"want to take into account for the purpose of calculating the price feature_cols",
"differences_squared.append((predicted_price - real_price)**2) if predicted_price/real_price < 1 + precision and predicted_price/real_price > 1",
"aces = 0 differences_squared = [] precision = 0.30 for index, rows in",
"\"N_number_of_reviews\"] train_set_f = train_set[feature_cols] test_set_f = test_set[feature_cols] standard_deviation = 0 k = 5",
"\"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f = train_set[feature_cols] test_set_f =",
"pandas as pd import numpy as np from scipy.spatial import distance import sys",
"home/apt\") | (city_listings[\"room_type\"] == \"Private room\") city_listings = city_listings[TF] #drop NaN rows, which",
"< 1 + precision and predicted_price/real_price > 1 - precision: aces += 1",
"city_listings.iloc[split_value:] print test_set.head(5) #we normalise for items in columns[1:]: mean = city_listings[items].mean() std",
"0 and entire home/apt to 1 city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True) mean_price",
"city_listings = city_listings[TF] #drop NaN rows, which means we mostly drop items which",
"\"HONG KONG\": city = \"HK\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city",
"train_set.iloc[:k] predicted_price = knn[\"price\"].mean() predicted_price = predicted_price.item() real_price = test_set.loc[[index], :][\"price\"] real_price =",
"rmse = (average_deviation)**0.5 print \"Rmse: \", rmse, \"for a price mean: \", mean_price",
"= (city_listings[items] - mean) / std N_columns = [\"price\", \"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\",",
"#upload data try: city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") except Exception: if",
"\"SF\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"SAN FRANCISCO\" #select",
"\"for a price mean: \", mean_price acespercent = float(aces)/float(test_set.shape[0]) print \"Accuracy %:\", acespercent,",
"to take into account for the purpose of calculating the price feature_cols =",
"import math columns = [\"price\", \"room_type\", \"accommodates\", \"bedrooms\", \"bathrooms\", \"beds\", \"number_of_reviews\", \"latitude\", \"longitude\",",
"\"N_longitude\", \"N_review_scores_value\"] #drop old columns normal_city_listings = city_listings[N_columns] train_set = normal_city_listings.iloc[:2888] test_set =",
"= np.std(city_listings[items]) N_items = \"N_\"+items city_listings[N_items] = (city_listings[items] - mean) / std N_columns",
"- mean) / std N_columns = [\"price\", \"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\",",
"train_set = city_listings.iloc[:split_value] test_set = city_listings.iloc[split_value:] print test_set.head(5) #we normalise for items in",
"sum(differences_squared) / float(len(differences_squared)) print \"Aces: \", aces rmse = (average_deviation)**0.5 print \"Rmse: \",",
"information with open('cities_dictionary.json') as json_data: cities_dict = json.load(json_data) del cities_dict['EXAMPLE'] #choose the city",
"ANGELES\" if city == \"SAN FRANCISCO\": city = \"SF\" city_listings = pd.read_csv(\"DATA/raw/\" +",
"real_price.item() differences_squared.append((predicted_price - real_price)**2) if predicted_price/real_price < 1 + precision and predicted_price/real_price >",
"= [\"price\", \"room_type\", \"accommodates\", \"bedrooms\", \"bathrooms\", \"beds\", \"number_of_reviews\", \"latitude\", \"longitude\", \"review_scores_value\"] #load cities'",
"split_value = int(round(float(city_listings.shape[0])*75/100)) #we use 75% of the dataset as train, 25% as",
"= city_listings[columns] #drop room types that are not well formatted TF = (city_listings[\"room_type\"]",
"pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"HONG KONG\" if city == \"LOS",
"FRANCISCO\": city = \"SF\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city =",
"= pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"LOS ANGELES\" if city ==",
"1 del train_set[\"distance\"] average_deviation = sum(differences_squared) / float(len(differences_squared)) print \"Aces: \", aces rmse",
"city_listings = city_listings.dropna() #shuffle city_listings = city_listings.sample(frac=1,random_state=0) #remove unwanted sharacters city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float)",
"as train, 25% as test train_set = city_listings.iloc[:split_value] test_set = city_listings.iloc[split_value:] print test_set.head(5)",
"= (average_deviation)**0.5 print \"Rmse: \", rmse, \"for a price mean: \", mean_price acespercent",
"= [\"price\", \"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\"] #drop old",
"del cities_dict['EXAMPLE'] #choose the city city = \"ATHENS\" #upload data try: city_listings =",
"0 k = 5 aces = 0 differences_squared = [] precision = 0.30",
"/ std N_columns = [\"price\", \"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\", \"N_latitude\", \"N_longitude\",",
"json import math columns = [\"price\", \"room_type\", \"accommodates\", \"bedrooms\", \"bathrooms\", \"beds\", \"number_of_reviews\", \"latitude\",",
"= \"HK\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"HONG KONG\"",
"precision and predicted_price/real_price > 1 - precision: aces += 1 del train_set[\"distance\"] average_deviation",
"k = 5 aces = 0 differences_squared = [] precision = 0.30 for",
"items which have no reviews city_listings = city_listings.dropna() #shuffle city_listings = city_listings.sample(frac=1,random_state=0) #remove",
"std N_columns = [\"price\", \"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\"]",
"= pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"SAN FRANCISCO\" #select relevant columns",
"numpy as np from scipy.spatial import distance import sys import json import math",
"= [\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f = train_set[feature_cols]",
"\"_listings.csv\") city = \"LOS ANGELES\" if city == \"SAN FRANCISCO\": city = \"SF\"",
"\"N_beds\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f = train_set[feature_cols] test_set_f = test_set[feature_cols] standard_deviation =",
"axis=1) train_set = train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True) knn = train_set.iloc[:k] predicted_price = knn[\"price\"].mean() predicted_price",
"you want to take into account for the purpose of calculating the price",
"\"bathrooms\", \"beds\", \"number_of_reviews\", \"latitude\", \"longitude\", \"review_scores_value\"] #load cities' information with open('cities_dictionary.json') as json_data:",
"[\"price\", \"room_type\", \"accommodates\", \"bedrooms\", \"bathrooms\", \"beds\", \"number_of_reviews\", \"latitude\", \"longitude\", \"review_scores_value\"] #load cities' information",
"for the purpose of calculating the price feature_cols = [\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\",",
"cities' information with open('cities_dictionary.json') as json_data: cities_dict = json.load(json_data) del cities_dict['EXAMPLE'] #choose the",
"75% of the dataset as train, 25% as test train_set = city_listings.iloc[:split_value] test_set",
"#load cities' information with open('cities_dictionary.json') as json_data: cities_dict = json.load(json_data) del cities_dict['EXAMPLE'] #choose",
"unwanted sharacters city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private room type to 0 and entire",
"predicted_price/real_price < 1 + precision and predicted_price/real_price > 1 - precision: aces +=",
"\"longitude\", \"review_scores_value\"] #load cities' information with open('cities_dictionary.json') as json_data: cities_dict = json.load(json_data) del",
"row), axis=1) train_set = train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True) knn = train_set.iloc[:k] predicted_price = knn[\"price\"].mean()",
"= train_set[feature_cols] test_set_f = test_set[feature_cols] standard_deviation = 0 k = 5 aces =",
"are not well formatted TF = (city_listings[\"room_type\"] == \"Entire home/apt\") | (city_listings[\"room_type\"] ==",
"import sys import json import math columns = [\"price\", \"room_type\", \"accommodates\", \"bedrooms\", \"bathrooms\",",
"import numpy as np from scipy.spatial import distance import sys import json import",
"0.30 for index, rows in test_set_f.iterrows(): distance_series = train_set_f.apply(lambda row: distance.euclidean(rows, row), axis=1)",
"old columns normal_city_listings = city_listings[N_columns] train_set = normal_city_listings.iloc[:2888] test_set = normal_city_listings.iloc[2888:] #choose columns",
"from scipy.spatial import distance import sys import json import math columns = [\"price\",",
"that are not well formatted TF = (city_listings[\"room_type\"] == \"Entire home/apt\") | (city_listings[\"room_type\"]",
"city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"HONG KONG\" if city",
"city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True) mean_price = city_listings[\"price\"].mean() split_value = int(round(float(city_listings.shape[0])*75/100)) #we use 75% of",
"city = \"ATHENS\" #upload data try: city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\")",
"city_listings.iloc[:split_value] test_set = city_listings.iloc[split_value:] print test_set.head(5) #we normalise for items in columns[1:]: mean",
"to 0 and entire home/apt to 1 city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True)",
"| (city_listings[\"room_type\"] == \"Private room\") city_listings = city_listings[TF] #drop NaN rows, which means",
"\"HONG KONG\" if city == \"LOS ANGELES\": city = \"LA\" city_listings = pd.read_csv(\"DATA/raw/\"",
"room type to 0 and entire home/apt to 1 city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire",
"as test train_set = city_listings.iloc[:split_value] test_set = city_listings.iloc[split_value:] print test_set.head(5) #we normalise for",
"home/apt\", 1.0,inplace=True) mean_price = city_listings[\"price\"].mean() split_value = int(round(float(city_listings.shape[0])*75/100)) #we use 75% of the",
"+ city + \"_listings.csv\") city = \"LOS ANGELES\" if city == \"SAN FRANCISCO\":",
"= real_price.item() differences_squared.append((predicted_price - real_price)**2) if predicted_price/real_price < 1 + precision and predicted_price/real_price",
"= train_set.iloc[:k] predicted_price = knn[\"price\"].mean() predicted_price = predicted_price.item() real_price = test_set.loc[[index], :][\"price\"] real_price",
"city_listings = city_listings[columns] #drop room types that are not well formatted TF =",
"/ float(len(differences_squared)) print \"Aces: \", aces rmse = (average_deviation)**0.5 print \"Rmse: \", rmse,",
"+ \"_listings.csv\") city = \"LOS ANGELES\" if city == \"SAN FRANCISCO\": city =",
"reviews city_listings = city_listings.dropna() #shuffle city_listings = city_listings.sample(frac=1,random_state=0) #remove unwanted sharacters city_listings['price'] =",
"inplace=True) knn = train_set.iloc[:k] predicted_price = knn[\"price\"].mean() predicted_price = predicted_price.item() real_price = test_set.loc[[index],",
"test_set.loc[[index], :][\"price\"] real_price = real_price.item() differences_squared.append((predicted_price - real_price)**2) if predicted_price/real_price < 1 +",
"distance_series = train_set_f.apply(lambda row: distance.euclidean(rows, row), axis=1) train_set = train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True) knn",
"columns you want to take into account for the purpose of calculating the",
"[\"price\", \"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\"] #drop old columns",
"= \"ATHENS\" #upload data try: city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") except",
"#select relevant columns from the data city_listings = city_listings[columns] #drop room types that",
"knn[\"price\"].mean() predicted_price = predicted_price.item() real_price = test_set.loc[[index], :][\"price\"] real_price = real_price.item() differences_squared.append((predicted_price -",
"if city == \"SAN FRANCISCO\": city = \"SF\" city_listings = pd.read_csv(\"DATA/raw/\" + city",
"= normal_city_listings.iloc[:2888] test_set = normal_city_listings.iloc[2888:] #choose columns you want to take into account",
"int(round(float(city_listings.shape[0])*75/100)) #we use 75% of the dataset as train, 25% as test train_set",
"#drop room types that are not well formatted TF = (city_listings[\"room_type\"] == \"Entire",
"\", aces rmse = (average_deviation)**0.5 print \"Rmse: \", rmse, \"for a price mean:",
"city = \"SAN FRANCISCO\" #select relevant columns from the data city_listings = city_listings[columns]",
"[\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\", \"N_number_of_reviews\"] train_set_f = train_set[feature_cols] test_set_f",
"if predicted_price/real_price < 1 + precision and predicted_price/real_price > 1 - precision: aces",
"KONG\" if city == \"LOS ANGELES\": city = \"LA\" city_listings = pd.read_csv(\"DATA/raw/\" +",
"average_deviation = sum(differences_squared) / float(len(differences_squared)) print \"Aces: \", aces rmse = (average_deviation)**0.5 print",
"row: distance.euclidean(rows, row), axis=1) train_set = train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True) knn = train_set.iloc[:k] predicted_price",
":][\"price\"] real_price = real_price.item() differences_squared.append((predicted_price - real_price)**2) if predicted_price/real_price < 1 + precision",
"city_listings[TF] #drop NaN rows, which means we mostly drop items which have no",
"test_set_f.iterrows(): distance_series = train_set_f.apply(lambda row: distance.euclidean(rows, row), axis=1) train_set = train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True)",
"print \"Rmse: \", rmse, \"for a price mean: \", mean_price acespercent = float(aces)/float(test_set.shape[0])",
"city + \"_listings.csv\") city = \"LOS ANGELES\" if city == \"SAN FRANCISCO\": city",
"\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\"] #drop old columns normal_city_listings",
"precision: aces += 1 del train_set[\"distance\"] average_deviation = sum(differences_squared) / float(len(differences_squared)) print \"Aces:",
"= city_listings[\"price\"].mean() split_value = int(round(float(city_listings.shape[0])*75/100)) #we use 75% of the dataset as train,",
"\"Private room\") city_listings = city_listings[TF] #drop NaN rows, which means we mostly drop",
"= train_set_f.apply(lambda row: distance.euclidean(rows, row), axis=1) train_set = train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True) knn =",
"== \"LOS ANGELES\": city = \"LA\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\")",
"train_set = train_set.assign(distance=distance_series) train_set.sort_values(\"distance\", inplace=True) knn = train_set.iloc[:k] predicted_price = knn[\"price\"].mean() predicted_price =",
"#drop NaN rows, which means we mostly drop items which have no reviews",
"train_set = normal_city_listings.iloc[:2888] test_set = normal_city_listings.iloc[2888:] #choose columns you want to take into",
"#choose the city city = \"ATHENS\" #upload data try: city_listings = pd.read_csv(\"DATA/raw/\" +",
"not well formatted TF = (city_listings[\"room_type\"] == \"Entire home/apt\") | (city_listings[\"room_type\"] == \"Private",
"test_set[feature_cols] standard_deviation = 0 k = 5 aces = 0 differences_squared = []",
"\"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_number_of_reviews\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\"] #drop old columns normal_city_listings = city_listings[N_columns]",
"\"latitude\", \"longitude\", \"review_scores_value\"] #load cities' information with open('cities_dictionary.json') as json_data: cities_dict = json.load(json_data)",
"1.0,inplace=True) mean_price = city_listings[\"price\"].mean() split_value = int(round(float(city_listings.shape[0])*75/100)) #we use 75% of the dataset",
"\"LOS ANGELES\" if city == \"SAN FRANCISCO\": city = \"SF\" city_listings = pd.read_csv(\"DATA/raw/\"",
"= pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"HONG KONG\" if city ==",
"Exception: if city == \"HONG KONG\": city = \"HK\" city_listings = pd.read_csv(\"DATA/raw/\" +",
"- real_price)**2) if predicted_price/real_price < 1 + precision and predicted_price/real_price > 1 -",
"well formatted TF = (city_listings[\"room_type\"] == \"Entire home/apt\") | (city_listings[\"room_type\"] == \"Private room\")",
"= 0 differences_squared = [] precision = 0.30 for index, rows in test_set_f.iterrows():",
"del train_set[\"distance\"] average_deviation = sum(differences_squared) / float(len(differences_squared)) print \"Aces: \", aces rmse =",
"25% as test train_set = city_listings.iloc[:split_value] test_set = city_listings.iloc[split_value:] print test_set.head(5) #we normalise",
"city_listings.dropna() #shuffle city_listings = city_listings.sample(frac=1,random_state=0) #remove unwanted sharacters city_listings['price'] = city_listings.price.str.replace(\"\\$|,\",'').astype(float) #set private",
"+ city + \"_listings.csv\") except Exception: if city == \"HONG KONG\": city =",
"aces rmse = (average_deviation)**0.5 print \"Rmse: \", rmse, \"for a price mean: \",",
"mean_price acespercent = float(aces)/float(test_set.shape[0]) print \"Accuracy %:\", acespercent, \"with a precision: \", precision",
"city = \"SF\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"SAN",
"city == \"LOS ANGELES\": city = \"LA\" city_listings = pd.read_csv(\"DATA/raw/\" + city +",
"\"SAN FRANCISCO\": city = \"SF\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city",
"use 75% of the dataset as train, 25% as test train_set = city_listings.iloc[:split_value]",
"(average_deviation)**0.5 print \"Rmse: \", rmse, \"for a price mean: \", mean_price acespercent =",
"= 0.30 for index, rows in test_set_f.iterrows(): distance_series = train_set_f.apply(lambda row: distance.euclidean(rows, row),",
"from the data city_listings = city_listings[columns] #drop room types that are not well",
"predicted_price = knn[\"price\"].mean() predicted_price = predicted_price.item() real_price = test_set.loc[[index], :][\"price\"] real_price = real_price.item()",
"N_items = \"N_\"+items city_listings[N_items] = (city_listings[items] - mean) / std N_columns = [\"price\",",
"= \"LOS ANGELES\" if city == \"SAN FRANCISCO\": city = \"SF\" city_listings =",
"test_set.head(5) #we normalise for items in columns[1:]: mean = city_listings[items].mean() std = np.std(city_listings[items])",
"city_listings[items].mean() std = np.std(city_listings[items]) N_items = \"N_\"+items city_listings[N_items] = (city_listings[items] - mean) /",
"types that are not well formatted TF = (city_listings[\"room_type\"] == \"Entire home/apt\") |",
"= predicted_price.item() real_price = test_set.loc[[index], :][\"price\"] real_price = real_price.item() differences_squared.append((predicted_price - real_price)**2) if",
"standard_deviation = 0 k = 5 aces = 0 differences_squared = [] precision",
"normal_city_listings.iloc[2888:] #choose columns you want to take into account for the purpose of",
"#we normalise for items in columns[1:]: mean = city_listings[items].mean() std = np.std(city_listings[items]) N_items",
"\"N_\"+items city_listings[N_items] = (city_listings[items] - mean) / std N_columns = [\"price\", \"N_room_type\", \"N_accommodates\",",
"train_set[\"distance\"] average_deviation = sum(differences_squared) / float(len(differences_squared)) print \"Aces: \", aces rmse = (average_deviation)**0.5",
"\"room_type\", \"accommodates\", \"bedrooms\", \"bathrooms\", \"beds\", \"number_of_reviews\", \"latitude\", \"longitude\", \"review_scores_value\"] #load cities' information with",
"== \"Private room\") city_listings = city_listings[TF] #drop NaN rows, which means we mostly",
"np from scipy.spatial import distance import sys import json import math columns =",
"= \"N_\"+items city_listings[N_items] = (city_listings[items] - mean) / std N_columns = [\"price\", \"N_room_type\",",
"= json.load(json_data) del cities_dict['EXAMPLE'] #choose the city city = \"ATHENS\" #upload data try:",
"1 city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\", 1.0,inplace=True) mean_price = city_listings[\"price\"].mean() split_value = int(round(float(city_listings.shape[0])*75/100))",
"distance import sys import json import math columns = [\"price\", \"room_type\", \"accommodates\", \"bedrooms\",",
"city + \"_listings.csv\") city = \"SAN FRANCISCO\" #select relevant columns from the data",
"\"N_latitude\", \"N_longitude\", \"N_review_scores_value\"] #drop old columns normal_city_listings = city_listings[N_columns] train_set = normal_city_listings.iloc[:2888] test_set",
"of calculating the price feature_cols = [\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_latitude\", \"N_longitude\",",
"= \"LA\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"LOS ANGELES\"",
"room types that are not well formatted TF = (city_listings[\"room_type\"] == \"Entire home/apt\")",
"= \"SAN FRANCISCO\" #select relevant columns from the data city_listings = city_listings[columns] #drop",
"city = \"HK\" city_listings = pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") city = \"HONG",
"- precision: aces += 1 del train_set[\"distance\"] average_deviation = sum(differences_squared) / float(len(differences_squared)) print",
"calculating the price feature_cols = [\"N_room_type\", \"N_accommodates\", \"N_bedrooms\", \"N_bathrooms\", \"N_beds\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\",",
"print test_set.head(5) #we normalise for items in columns[1:]: mean = city_listings[items].mean() std =",
"#we use 75% of the dataset as train, 25% as test train_set =",
"\"Rmse: \", rmse, \"for a price mean: \", mean_price acespercent = float(aces)/float(test_set.shape[0]) print",
"in test_set_f.iterrows(): distance_series = train_set_f.apply(lambda row: distance.euclidean(rows, row), axis=1) train_set = train_set.assign(distance=distance_series) train_set.sort_values(\"distance\",",
"= (city_listings[\"room_type\"] == \"Entire home/apt\") | (city_listings[\"room_type\"] == \"Private room\") city_listings = city_listings[TF]",
"= [] precision = 0.30 for index, rows in test_set_f.iterrows(): distance_series = train_set_f.apply(lambda",
"have no reviews city_listings = city_listings.dropna() #shuffle city_listings = city_listings.sample(frac=1,random_state=0) #remove unwanted sharacters",
"pd.read_csv(\"DATA/raw/\" + city + \"_listings.csv\") except Exception: if city == \"HONG KONG\": city",
"city_listings[N_columns] train_set = normal_city_listings.iloc[:2888] test_set = normal_city_listings.iloc[2888:] #choose columns you want to take",
"mean: \", mean_price acespercent = float(aces)/float(test_set.shape[0]) print \"Accuracy %:\", acespercent, \"with a precision:",
"test_set_f = test_set[feature_cols] standard_deviation = 0 k = 5 aces = 0 differences_squared",
"take into account for the purpose of calculating the price feature_cols = [\"N_room_type\",",
"<filename>statistics_check.py<gh_stars>1-10 import pandas as pd import numpy as np from scipy.spatial import distance",
"mostly drop items which have no reviews city_listings = city_listings.dropna() #shuffle city_listings =",
"\"_listings.csv\") city = \"HONG KONG\" if city == \"LOS ANGELES\": city = \"LA\"",
"if city == \"HONG KONG\": city = \"HK\" city_listings = pd.read_csv(\"DATA/raw/\" + city",
"differences_squared = [] precision = 0.30 for index, rows in test_set_f.iterrows(): distance_series =",
"rows in test_set_f.iterrows(): distance_series = train_set_f.apply(lambda row: distance.euclidean(rows, row), axis=1) train_set = train_set.assign(distance=distance_series)",
"\"N_beds\", \"N_number_of_reviews\", \"N_latitude\", \"N_longitude\", \"N_review_scores_value\"] #drop old columns normal_city_listings = city_listings[N_columns] train_set =",
"real_price = test_set.loc[[index], :][\"price\"] real_price = real_price.item() differences_squared.append((predicted_price - real_price)**2) if predicted_price/real_price <",
"type to 0 and entire home/apt to 1 city_listings['room_type'].replace(\"Private room\", 0.0,inplace=True) city_listings['room_type'].replace(\"Entire home/apt\","
] |
[
"= list(map(int, input().split())) # process ''' 각 장이 섞여도 됨. >> 힙에서 제일",
"# input t = int(input()) for _ in range(t): chapter = int(input()) pages",
"= 0 hq.heapify(pages) for _ in range(chapter - 1): cost = hq.heappop(pages) +",
"sol = 0 hq.heapify(pages) for _ in range(chapter - 1): cost = hq.heappop(pages)",
"range(chapter - 1): cost = hq.heappop(pages) + hq.heappop(pages) sol += cost hq.heappush(pages, cost)",
"sys.stdin.readline import heapq as hq # input t = int(input()) for _ in",
"제일 작은 거 두 개 합치고 다시 넣음. ''' sol = 0 hq.heapify(pages)",
"import sys input = sys.stdin.readline import heapq as hq # input t =",
"int(input()) for _ in range(t): chapter = int(input()) pages = list(map(int, input().split())) #",
"import heapq as hq # input t = int(input()) for _ in range(t):",
"''' 각 장이 섞여도 됨. >> 힙에서 제일 작은 거 두 개 합치고",
"input = sys.stdin.readline import heapq as hq # input t = int(input()) for",
"_ in range(t): chapter = int(input()) pages = list(map(int, input().split())) # process '''",
"두 개 합치고 다시 넣음. ''' sol = 0 hq.heapify(pages) for _ in",
"됨. >> 힙에서 제일 작은 거 두 개 합치고 다시 넣음. ''' sol",
"heapq as hq # input t = int(input()) for _ in range(t): chapter",
"개 합치고 다시 넣음. ''' sol = 0 hq.heapify(pages) for _ in range(chapter",
"_ in range(chapter - 1): cost = hq.heappop(pages) + hq.heappop(pages) sol += cost",
"sys input = sys.stdin.readline import heapq as hq # input t = int(input())",
"t = int(input()) for _ in range(t): chapter = int(input()) pages = list(map(int,",
"힙에서 제일 작은 거 두 개 합치고 다시 넣음. ''' sol = 0",
"''' sol = 0 hq.heapify(pages) for _ in range(chapter - 1): cost =",
"합치고 다시 넣음. ''' sol = 0 hq.heapify(pages) for _ in range(chapter -",
"cost = hq.heappop(pages) + hq.heappop(pages) sol += cost hq.heappush(pages, cost) # output print(sol)",
"0 hq.heapify(pages) for _ in range(chapter - 1): cost = hq.heappop(pages) + hq.heappop(pages)",
"input().split())) # process ''' 각 장이 섞여도 됨. >> 힙에서 제일 작은 거",
"in range(t): chapter = int(input()) pages = list(map(int, input().split())) # process ''' 각",
"섞여도 됨. >> 힙에서 제일 작은 거 두 개 합치고 다시 넣음. '''",
"int(input()) pages = list(map(int, input().split())) # process ''' 각 장이 섞여도 됨. >>",
"다시 넣음. ''' sol = 0 hq.heapify(pages) for _ in range(chapter - 1):",
"= int(input()) for _ in range(t): chapter = int(input()) pages = list(map(int, input().split()))",
"in range(chapter - 1): cost = hq.heappop(pages) + hq.heappop(pages) sol += cost hq.heappush(pages,",
"range(t): chapter = int(input()) pages = list(map(int, input().split())) # process ''' 각 장이",
">> 힙에서 제일 작은 거 두 개 합치고 다시 넣음. ''' sol =",
"hq.heapify(pages) for _ in range(chapter - 1): cost = hq.heappop(pages) + hq.heappop(pages) sol",
"for _ in range(t): chapter = int(input()) pages = list(map(int, input().split())) # process",
"list(map(int, input().split())) # process ''' 각 장이 섞여도 됨. >> 힙에서 제일 작은",
"= int(input()) pages = list(map(int, input().split())) # process ''' 각 장이 섞여도 됨.",
"= sys.stdin.readline import heapq as hq # input t = int(input()) for _",
"# process ''' 각 장이 섞여도 됨. >> 힙에서 제일 작은 거 두",
"거 두 개 합치고 다시 넣음. ''' sol = 0 hq.heapify(pages) for _",
"넣음. ''' sol = 0 hq.heapify(pages) for _ in range(chapter - 1): cost",
"input t = int(input()) for _ in range(t): chapter = int(input()) pages =",
"pages = list(map(int, input().split())) # process ''' 각 장이 섞여도 됨. >> 힙에서",
"process ''' 각 장이 섞여도 됨. >> 힙에서 제일 작은 거 두 개",
"작은 거 두 개 합치고 다시 넣음. ''' sol = 0 hq.heapify(pages) for",
"as hq # input t = int(input()) for _ in range(t): chapter =",
"for _ in range(chapter - 1): cost = hq.heappop(pages) + hq.heappop(pages) sol +=",
"각 장이 섞여도 됨. >> 힙에서 제일 작은 거 두 개 합치고 다시",
"- 1): cost = hq.heappop(pages) + hq.heappop(pages) sol += cost hq.heappush(pages, cost) #",
"1): cost = hq.heappop(pages) + hq.heappop(pages) sol += cost hq.heappush(pages, cost) # output",
"chapter = int(input()) pages = list(map(int, input().split())) # process ''' 각 장이 섞여도",
"hq # input t = int(input()) for _ in range(t): chapter = int(input())",
"장이 섞여도 됨. >> 힙에서 제일 작은 거 두 개 합치고 다시 넣음."
] |
[
"counter_message = '\\n'.join( [\"\\tCount\\tMessage\"] + [ f\"\\t{count}\\t{message}\" for message, count in Counter(self.message).most_common() ]",
"None, x0: np.ndarray = None, fval0: float = None, history: History = None,",
"else None self.sres: np.ndarray = np.array(sres) if sres is not None else None",
"\\n\" f\"* time taken to optimize: {self.time} \\n\" f\"* startpoint: {self.x0} \\n\" f\"*",
"new_ids: raise ValueError( \"Some id's you want to merge coincide with \" \"the",
"f\"* number of evaluations: {self.n_fval} \\n\" f\"* time taken to optimize: {self.time} \\n\"",
"+= f\"* final residual sensitivity: {self.sres} \\n\" return message def update_to_full(self, problem: Problem)",
"new_ids = [ prefix + identifier for identifier in optimize_result.id if identifier is",
"Boolean used so we only sort once when appending an optimize_result. prefix: The",
"history self.exitflag: int = exitflag self.time: float = time self.message: str = message",
"OptimizeResult): new_ids = [ prefix + identifier for identifier in optimize_result.id if identifier",
"or matrices \"\"\" self.x = problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad = problem.get_full_vector(self.grad) self.hess = problem.get_full_matrix(self.hess)",
"str = None, optimizer: str = None, ): super().__init__() self.id = id self.x:",
"int = exitflag self.time: float = time self.message: str = message self.optimizer =",
"best found parameters. fval: The best found function value, `fun(x)`. grad: The gradient",
"= self.list if keys is not None: lst = [{key: res[key] for key",
"Result \\n\\n\" f\"* number of starts: {len(self)} \\n\" f\"* execution time summary: {times_message}\\n\"",
"pandas DataFrame. If keys is a list, return only the specified values, otherwise",
"if optimize_result.id is None: self.list.append(optimize_result) else: new_id = prefix + optimize_result.id if new_id",
"None self.n_fval: int = n_fval self.n_grad: int = n_grad self.n_hess: int = n_hess",
"if available if self.fval is not None: message += f\"* final objective value:",
"about how to convert to full vectors or matrices \"\"\" self.x = problem.get_full_vector(self.x,",
"a dict. Attributes ---------- id: Id of the optimizer run. Usually the start",
"..util import assign_clusters, delete_nan_inf OptimizationResult = Union['OptimizerResult', 'OptimizeResult'] class OptimizerResult(dict): \"\"\" The result",
"Usually the start index. x: The best found parameters. fval: The best found",
"is deprecated in favour of \" \"optimize_result['key'] and will be removed in future",
"raise AttributeError(key) def __getitem__(self, index): \"\"\"Define `optimize_result[i]` to access the i-th result.\"\"\" try:",
"if identifier is not None ] if current_ids.isdisjoint(new_ids) and new_ids: raise ValueError( \"Some",
"found: \" f\"{1 + max(clust) - sum(clustsize == 1)} \\n\" f\"* best value:",
"message: str Textual comment on the optimization result. optimizer: str The optimizer used",
"to the format understood by pypesto. Can be used like a dict. Attributes",
"dict. Attributes ---------- id: Id of the optimizer run. Usually the start index.",
"None: message += f\"* final residual value: {self.res} \\n\" if self.sres is not",
"optimizer. time: Execution time. message: str Textual comment on the optimization result. optimizer:",
"problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad = problem.get_full_vector(self.grad) self.hess = problem.get_full_matrix(self.hess) self.x0 = problem.get_full_vector(self.x0, problem.x_fixed_vals) class",
"result of one or more (local) optimizer run. sort: Boolean used so we",
"self.hess is not None: message += f\"* final hessian value: {self.hess} \\n\" if",
"optimizer used for optimization. Notes ----- Any field not supported by the optimizer",
"id is None, append without checking for duplicate ids if optimize_result.id is None:",
"index. x: The best found parameters. fval: The best found function value, `fun(x)`.",
"better information clust, clustsize = assign_clusters(delete_nan_inf(self.fval)[1]) counter_message = '\\n'.join( [\"\\tCount\\tMessage\"] + [ f\"\\t{count}\\t{message}\"",
"merge coincides with \" \"the existing id's. Please use an \" \"appropriate prefix",
"to full vectors or matrices \"\"\" self.x = problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad = problem.get_full_vector(self.grad)",
"\\n\" f\"* endpoint: {self.x} \\n\" ) # add fval, gradient, hessian, res, sres",
"on the optimization result. optimizer: str The optimizer used for optimization. Notes -----",
"you want to merge coincides with \" \"the existing id's. Please use an",
"list of values for the specified key as a list.\"\"\" warnings.warn( \"get_for_key() is",
"optimizer: str = None, ): super().__init__() self.id = id self.x: np.ndarray = np.array(x)",
"`fun(x)`. grad: The gradient at `x`. hess: The Hessian at `x`. res: The",
"which contains info about how to convert to full vectors or matrices \"\"\"",
"f\"* summary of optimizer messages:\\n{counter_message}\\n\" f\"* best value found (approximately) {clustsize[0]} time(s) \\n\"",
"except KeyError: raise AttributeError(key) def __getitem__(self, index): \"\"\"Define `optimize_result[i]` to access the i-th",
"f'id={self[np.argmin(self.time)].id}' ) summary = ( \"## Optimization Result \\n\\n\" f\"* number of starts:",
"ids if optimize_result.id is None: self.list.append(optimize_result) else: new_id = prefix + optimize_result.id if",
"value: {self.fval} \\n\" if self.grad is not None: message += f\"* final gradient",
"= n_grad self.n_hess: int = n_hess self.n_res: int = n_res self.n_sres: int =",
"np.ndarray = np.array(sres) if sres is not None else None self.n_fval: int =",
"best value found (approximately) {clustsize[0]} time(s) \\n\" f\"* number of plateaus found: \"",
"f\"A summary of the best run:\\n\\n{self[0].summary()}\" ) return summary def append( self, optimize_result:",
"message self.optimizer = optimizer def __getattr__(self, key): try: return self[key] except KeyError: raise",
"will be prefixed with this. \"\"\" current_ids = set(self.id) if isinstance(optimize_result, OptimizeResult): new_ids",
"optimizer results by function value fval (ascending).\"\"\" def get_fval(res): return res.fval if not",
"= None, n_hess: int = None, n_res: int = None, n_sres: int =",
"value: {self[0]['fval']}, \" f\"worst value: {self[-1]['fval']} \\n\\n\" f\"A summary of the best run:\\n\\n{self[0].summary()}\"",
"def __len__(self): return len(self.list) def summary(self): \"\"\"Get summary of the object.\"\"\" # perform",
"optimizer run. sort: Boolean used so we only sort once when appending an",
"= problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad = problem.get_full_vector(self.grad) self.hess = problem.get_full_matrix(self.hess) self.x0 = problem.get_full_vector(self.x0, problem.x_fixed_vals)",
"= ( \"### Optimizer Result \\n\\n\" f\"* optimizer used: {self.optimizer} \\n\" f\"* message:",
"with this. \"\"\" current_ids = set(self.id) if isinstance(optimize_result, OptimizeResult): new_ids = [ prefix",
"is None, append without checking for duplicate ids if optimize_result.id is None: self.list.append(optimize_result)",
"Result \\n\\n\" f\"* optimizer used: {self.optimizer} \\n\" f\"* message: {self.message} \\n\" f\"* number",
"values, otherwise all. \"\"\" lst = self.as_list(keys) df = pd.DataFrame(lst) return df def",
"import pandas as pd from ..objective import History from ..problem import Problem from",
"return summary def append( self, optimize_result: OptimizationResult, sort: bool = True, prefix: str",
"{clustsize[0]} time(s) \\n\" f\"* number of plateaus found: \" f\"{1 + max(clust) -",
"else np.inf self.list = sorted(self.list, key=get_fval) def as_dataframe(self, keys=None) -> pd.DataFrame: \"\"\" Get",
"sensitivities at `x`. n_fval Number of function evaluations. n_grad: Number of gradient evaluations.",
"a list, return only the specified values. Parameters ---------- keys: list(str), optional Labels",
"np.ndarray = np.array(hess) if hess is not None else None self.res: np.ndarray =",
"not None: message += f\"* final hessian value: {self.hess} \\n\" if self.res is",
"value found (approximately) {clustsize[0]} time(s) \\n\" f\"* number of plateaus found: \" f\"{1",
"self.list = sorted(self.list, key=get_fval) def as_dataframe(self, keys=None) -> pd.DataFrame: \"\"\" Get as pandas",
"f\"* optimizer used: {self.optimizer} \\n\" f\"* message: {self.message} \\n\" f\"* number of evaluations:",
"copy import deepcopy from typing import Sequence, Union import numpy as np import",
"self.fval is not None: message += f\"* final objective value: {self.fval} \\n\" if",
"{self[-1]['fval']} \\n\\n\" f\"A summary of the best run:\\n\\n{self[0].summary()}\" ) return summary def append(",
"fval0 self.history: History = history self.exitflag: int = exitflag self.time: float = time",
"update_to_full(self, problem: Problem) -> None: \"\"\" Update values to full vectors/matrices. Parameters ----------",
"\" f\"length {len(self.list)}.\" ) def __len__(self): return len(self.list) def summary(self): \"\"\"Get summary of",
"n_sres: Number of residual sensitivity evaluations. x0: The starting parameters. fval0: The starting",
"you want to merge coincide with \" \"the existing id's. Please use an",
"\" \"the existing id's. Please use an \" \"appropriate prefix such as 'run_2_'.\"",
"= None, res: np.ndarray = None, sres: np.ndarray = None, n_fval: int =",
"self.message: str = message self.optimizer = optimizer def __getattr__(self, key): try: return self[key]",
"n_fval: int = None, n_grad: int = None, n_hess: int = None, n_res:",
"IndexError: raise IndexError( f\"{index} out of range for optimize result of \" f\"length",
"Union import numpy as np import pandas as pd from ..objective import History",
"\"\"\" current_ids = set(self.id) if isinstance(optimize_result, OptimizeResult): new_ids = [ prefix + identifier",
"\"appropriate prefix such as 'run_2_'.\" ) for optimizer_result in optimize_result.list: self.append(optimizer_result, sort=False, prefix=prefix)",
"n_grad: int = None, n_hess: int = None, n_res: int = None, n_sres:",
"\\n\" return message def update_to_full(self, problem: Problem) -> None: \"\"\" Update values to",
"is not None ] if current_ids.isdisjoint(new_ids) and new_ids: raise ValueError( \"Some id's you",
"of optimizer messages:\\n{counter_message}\\n\" f\"* best value found (approximately) {clustsize[0]} time(s) \\n\" f\"* number",
"summary def append( self, optimize_result: OptimizationResult, sort: bool = True, prefix: str =",
"sres: np.ndarray = None, n_fval: int = None, n_grad: int = None, n_hess:",
"get_for_key(self, key) -> list: \"\"\"Extract the list of values for the specified key",
"if sort: self.sort() def sort(self): \"\"\"Sort the optimizer results by function value fval",
"= problem.get_full_matrix(self.hess) self.x0 = problem.get_full_vector(self.x0, problem.x_fixed_vals) class OptimizeResult: \"\"\"Result of the :py:func:`pypesto.optimize.minimize` function.\"\"\"",
"assign_clusters(delete_nan_inf(self.fval)[1]) counter_message = '\\n'.join( [\"\\tCount\\tMessage\"] + [ f\"\\t{count}\\t{message}\" for message, count in Counter(self.message).most_common()",
"residual sensitivity evaluations. x0: The starting parameters. fval0: The starting function value, `fun(x0)`.",
"object.\"\"\" # perform clustering for better information clust, clustsize = assign_clusters(delete_nan_inf(self.fval)[1]) counter_message =",
"key) -> list: \"\"\"Extract the list of values for the specified key as",
"Get as pandas DataFrame. If keys is a list, return only the specified",
"res.fval if not np.isnan(res.fval) else np.inf self.list = sorted(self.list, key=get_fval) def as_dataframe(self, keys=None)",
"found (approximately) {clustsize[0]} time(s) \\n\" f\"* number of plateaus found: \" f\"{1 +",
"self[key] except KeyError: raise AttributeError(key) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def summary(self):",
"not None ] if current_ids.isdisjoint(new_ids) and new_ids: raise ValueError( \"Some id's you want",
"return len(self.list) def summary(self): \"\"\"Get summary of the object.\"\"\" # perform clustering for",
"'\\n'.join( [\"\\tCount\\tMessage\"] + [ f\"\\t{count}\\t{message}\" for message, count in Counter(self.message).most_common() ] ) times_message",
"history. exitflag: The exitflag of the optimizer. time: Execution time. message: str Textual",
"message: str = None, optimizer: str = None, ): super().__init__() self.id = id",
"f\"* best value: {self[0]['fval']}, \" f\"worst value: {self[-1]['fval']} \\n\\n\" f\"A summary of the",
"the result object. Parameters ---------- optimize_result: The result of one or more (local)",
"not None else None self.res: np.ndarray = np.array(res) if res is not None",
"optimizer def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(key) __setattr__ =",
"summary of the object.\"\"\" message = ( \"### Optimizer Result \\n\\n\" f\"* optimizer",
"'run_2_'.\" ) optimize_result.id = new_id self.list.append(optimize_result) if sort: self.sort() def sort(self): \"\"\"Sort the",
"sensitivity: {self.sres} \\n\" return message def update_to_full(self, problem: Problem) -> None: \"\"\" Update",
"Problem from ..util import assign_clusters, delete_nan_inf OptimizationResult = Union['OptimizerResult', 'OptimizeResult'] class OptimizerResult(dict): \"\"\"",
"sres is not None else None self.n_fval: int = n_fval self.n_grad: int =",
"= None, optimizer: str = None, ): super().__init__() self.id = id self.x: np.ndarray",
"summary of the best run:\\n\\n{self[0].summary()}\" ) return summary def append( self, optimize_result: OptimizationResult,",
"= None, n_fval: int = None, n_grad: int = None, n_hess: int =",
"None, res: np.ndarray = None, sres: np.ndarray = None, n_fval: int = None,",
"x0 is not None else None self.fval0: float = fval0 self.history: History =",
"= OptimizeResult() other.list = deepcopy(self.list) return other def __getattr__(self, key): \"\"\"Define `optimize_result.key`.\"\"\" try:",
"prefix: str = '', ): \"\"\" Append an OptimizerResult or an OptimizeResult to",
"full vectors/matrices. Parameters ---------- problem: problem which contains info about how to convert",
"self.as_list(keys) df = pd.DataFrame(lst) return df def as_list(self, keys=None) -> Sequence: \"\"\" Get",
"res is not None else None self.sres: np.ndarray = np.array(sres) if sres is",
"to merge coincides with \" \"the existing id's. Please use an \" \"appropriate",
"new_id = prefix + optimize_result.id if new_id in current_ids: raise ValueError( \"The id",
"is not None: message += f\"* final gradient value: {self.grad} \\n\" if self.hess",
"grad is not None else None self.hess: np.ndarray = np.array(hess) if hess is",
"def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(key) __setattr__ = dict.__setitem__",
"`optimize_result.key`.\"\"\" try: return [res[key] for res in self.list] except KeyError: raise AttributeError(key) def",
"time(s) \\n\" f\"* number of plateaus found: \" f\"{1 + max(clust) - sum(clustsize",
"Objective history. exitflag: The exitflag of the optimizer. time: Execution time. message: str",
"not None else None self.fval: float = fval self.grad: np.ndarray = np.array(grad) if",
"like a dict. Attributes ---------- id: Id of the optimizer run. Usually the",
"set(self.id) if isinstance(optimize_result, OptimizeResult): new_ids = [ prefix + identifier for identifier in",
"only the specified values. Parameters ---------- keys: list(str), optional Labels of the field",
"self.optimizer = optimizer def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(key)",
"value: {self.hess} \\n\" if self.res is not None: message += f\"* final residual",
"assign_clusters, delete_nan_inf OptimizationResult = Union['OptimizerResult', 'OptimizeResult'] class OptimizerResult(dict): \"\"\" The result of an",
"by the optimizer is filled with None. \"\"\" def __init__( self, id: str",
"str The optimizer used for optimization. Notes ----- Any field not supported by",
"= None, x0: np.ndarray = None, fval0: float = None, history: History =",
"sres if available if self.fval is not None: message += f\"* final objective",
"problem: problem which contains info about how to convert to full vectors or",
"(local) optimizer run. sort: Boolean used so we only sort once when appending",
"fval (ascending).\"\"\" def get_fval(res): return res.fval if not np.isnan(res.fval) else np.inf self.list =",
"Can be used like a dict. Attributes ---------- id: Id of the optimizer",
"self.append(optimizer_result, sort=False, prefix=prefix) elif isinstance(optimize_result, OptimizerResult): # if id is None, append without",
"time: Execution time. message: str Textual comment on the optimization result. optimizer: str",
"numpy as np import pandas as pd from ..objective import History from ..problem",
"res: The residuals at `x`. sres: The residual sensitivities at `x`. n_fval Number",
"of the object.\"\"\" message = ( \"### Optimizer Result \\n\\n\" f\"* optimizer used:",
"the individual result objects returned by the employed optimizers to the format understood",
"if new_id in current_ids: raise ValueError( \"The id you want to merge coincides",
"field not supported by the optimizer is filled with None. \"\"\" def __init__(",
"return df def as_list(self, keys=None) -> Sequence: \"\"\" Get as list. If keys",
"( \"## Optimization Result \\n\\n\" f\"* number of starts: {len(self)} \\n\" f\"* execution",
"problem.x_fixed_vals) self.grad = problem.get_full_vector(self.grad) self.hess = problem.get_full_matrix(self.hess) self.x0 = problem.get_full_vector(self.x0, problem.x_fixed_vals) class OptimizeResult:",
"for duplicate ids if optimize_result.id is None: self.list.append(optimize_result) else: new_id = prefix +",
"__deepcopy__(self, memo): other = OptimizeResult() other.list = deepcopy(self.list) return other def __getattr__(self, key):",
"execution time summary: {times_message}\\n\" f\"* summary of optimizer messages:\\n{counter_message}\\n\" f\"* best value found",
"function value fval (ascending).\"\"\" def get_fval(res): return res.fval if not np.isnan(res.fval) else np.inf",
"found function value, `fun(x)`. grad: The gradient at `x`. hess: The Hessian at",
"prefix + optimize_result.id if new_id in current_ids: raise ValueError( \"The id you want",
"for the specified key as a list.\"\"\" warnings.warn( \"get_for_key() is deprecated in favour",
"results will be prefixed with this. \"\"\" current_ids = set(self.id) if isinstance(optimize_result, OptimizeResult):",
"None: \"\"\" Update values to full vectors/matrices. Parameters ---------- problem: problem which contains",
"None: self.list.append(optimize_result) else: new_id = prefix + optimize_result.id if new_id in current_ids: raise",
"id's. Please use an \" \"appropriate prefix such as 'run_2_'.\" ) optimize_result.id =",
"run:\\n\\n{self[0].summary()}\" ) return summary def append( self, optimize_result: OptimizationResult, sort: bool = True,",
"= None, ): super().__init__() self.id = id self.x: np.ndarray = np.array(x) if x",
"evaluations: {self.n_fval} \\n\" f\"* time taken to optimize: {self.time} \\n\" f\"* startpoint: {self.x0}",
"identifier for identifier in optimize_result.id if identifier is not None ] if current_ids.isdisjoint(new_ids)",
"evaluations. n_sres: Number of residual sensitivity evaluations. x0: The starting parameters. fval0: The",
"individual result objects returned by the employed optimizers to the format understood by",
"gradient, hessian, res, sres if available if self.fval is not None: message +=",
"final objective value: {self.fval} \\n\" if self.grad is not None: message += f\"*",
"[{key: res[key] for key in keys} for res in lst] return lst def",
"for optimization. Notes ----- Any field not supported by the optimizer is filled",
"self.n_fval: int = n_fval self.n_grad: int = n_grad self.n_hess: int = n_hess self.n_res:",
"value to map from the individual result objects returned by the employed optimizers",
"fval self.grad: np.ndarray = np.array(grad) if grad is not None else None self.hess:",
"Textual comment on the optimization result. optimizer: str The optimizer used for optimization.",
"existing id's. Please use an \" \"appropriate prefix such as 'run_2_'.\" ) for",
"used like a dict. Attributes ---------- id: Id of the optimizer run. Usually",
"\"\"\"Sort the optimizer results by function value fval (ascending).\"\"\" def get_fval(res): return res.fval",
"of \" \"optimize_result['key'] and will be removed in future \" \"releases.\" ) return",
"ValueError( \"The id you want to merge coincides with \" \"the existing id's.",
"---------- id: Id of the optimizer run. Usually the start index. x: The",
"one or more (local) optimizer run. sort: Boolean used so we only sort",
"[ f\"\\t{count}\\t{message}\" for message, count in Counter(self.message).most_common() ] ) times_message = ( f'\\n\\tMean",
"deepcopy(self.list) return other def __getattr__(self, key): \"\"\"Define `optimize_result.key`.\"\"\" try: return [res[key] for res",
"objects returned by the employed optimizers to the format understood by pypesto. Can",
"not None: message += f\"* final residual value: {self.res} \\n\" if self.sres is",
"result objects returned by the employed optimizers to the format understood by pypesto.",
"] if current_ids.isdisjoint(new_ids) and new_ids: raise ValueError( \"Some id's you want to merge",
"Number of Hessian evaluations. n_res: Number of residuals evaluations. n_sres: Number of residual",
"= np.array(grad) if grad is not None else None self.hess: np.ndarray = np.array(hess)",
"if hess is not None else None self.res: np.ndarray = np.array(res) if res",
"or an OptimizeResult to the result object. Parameters ---------- optimize_result: The result of",
"def __getitem__(self, index): \"\"\"Define `optimize_result[i]` to access the i-th result.\"\"\" try: return self.list[index]",
"IndexError( f\"{index} out of range for optimize result of \" f\"length {len(self.list)}.\" )",
"def sort(self): \"\"\"Sort the optimizer results by function value fval (ascending).\"\"\" def get_fval(res):",
"use an \" \"appropriate prefix such as 'run_2_'.\" ) for optimizer_result in optimize_result.list:",
"returned by the employed optimizers to the format understood by pypesto. Can be",
"sort(self): \"\"\"Sort the optimizer results by function value fval (ascending).\"\"\" def get_fval(res): return",
"other def __getattr__(self, key): \"\"\"Define `optimize_result.key`.\"\"\" try: return [res[key] for res in self.list]",
"f\"* best value found (approximately) {clustsize[0]} time(s) \\n\" f\"* number of plateaus found:",
"message += f\"* final objective value: {self.fval} \\n\" if self.grad is not None:",
"self.fval0: float = fval0 self.history: History = history self.exitflag: int = exitflag self.time:",
"with \" \"the existing id's. Please use an \" \"appropriate prefix such as",
"message += f\"* final hessian value: {self.hess} \\n\" if self.res is not None:",
"for res in self.list] except KeyError: raise AttributeError(key) def __getitem__(self, index): \"\"\"Define `optimize_result[i]`",
"{self.sres} \\n\" return message def update_to_full(self, problem: Problem) -> None: \"\"\" Update values",
"best run:\\n\\n{self[0].summary()}\" ) return summary def append( self, optimize_result: OptimizationResult, sort: bool =",
"self.sort() def sort(self): \"\"\"Sort the optimizer results by function value fval (ascending).\"\"\" def",
"return message def update_to_full(self, problem: Problem) -> None: \"\"\" Update values to full",
"value: {self[-1]['fval']} \\n\\n\" f\"A summary of the best run:\\n\\n{self[0].summary()}\" ) return summary def",
"self.list if keys is not None: lst = [{key: res[key] for key in",
"as a list.\"\"\" warnings.warn( \"get_for_key() is deprecated in favour of \" \"optimize_result['key'] and",
"is not None else None self.res: np.ndarray = np.array(res) if res is not",
"taken to optimize: {self.time} \\n\" f\"* startpoint: {self.x0} \\n\" f\"* endpoint: {self.x} \\n\"",
"add fval, gradient, hessian, res, sres if available if self.fval is not None:",
"+= f\"* final residual value: {self.res} \\n\" if self.sres is not None: message",
"= [ prefix + identifier for identifier in optimize_result.id if identifier is not",
"{len(self)} \\n\" f\"* execution time summary: {times_message}\\n\" f\"* summary of optimizer messages:\\n{counter_message}\\n\" f\"*",
"self.res is not None: message += f\"* final residual value: {self.res} \\n\" if",
"used: {self.optimizer} \\n\" f\"* message: {self.message} \\n\" f\"* number of evaluations: {self.n_fval} \\n\"",
"The best found parameters. fval: The best found function value, `fun(x)`. grad: The",
"results by function value fval (ascending).\"\"\" def get_fval(res): return res.fval if not np.isnan(res.fval)",
"if id is None, append without checking for duplicate ids if optimize_result.id is",
"if self.fval is not None: message += f\"* final objective value: {self.fval} \\n\"",
"pypesto. Can be used like a dict. Attributes ---------- id: Id of the",
"else None self.fval: float = fval self.grad: np.ndarray = np.array(grad) if grad is",
"n_res: Number of residuals evaluations. n_sres: Number of residual sensitivity evaluations. x0: The",
"f\"* startpoint: {self.x0} \\n\" f\"* endpoint: {self.x} \\n\" ) # add fval, gradient,",
"of plateaus found: \" f\"{1 + max(clust) - sum(clustsize == 1)} \\n\" f\"*",
"hessian, res, sres if available if self.fval is not None: message += f\"*",
"n_fval Number of function evaluations. n_grad: Number of gradient evaluations. n_hess: Number of",
"\"\"\" self.x = problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad = problem.get_full_vector(self.grad) self.hess = problem.get_full_matrix(self.hess) self.x0 =",
"else None self.fval0: float = fval0 self.history: History = history self.exitflag: int =",
"AttributeError(key) def __getitem__(self, index): \"\"\"Define `optimize_result[i]` to access the i-th result.\"\"\" try: return",
"f'\\tMaximum execution time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' ) summary =",
"[\"\\tCount\\tMessage\"] + [ f\"\\t{count}\\t{message}\" for message, count in Counter(self.message).most_common() ] ) times_message =",
"Hessian at `x`. res: The residuals at `x`. sres: The residual sensitivities at",
"Update values to full vectors/matrices. Parameters ---------- problem: problem which contains info about",
"raise ValueError( \"Some id's you want to merge coincide with \" \"the existing",
"of values for the specified key as a list.\"\"\" warnings.warn( \"get_for_key() is deprecated",
"specified values, otherwise all. \"\"\" lst = self.as_list(keys) df = pd.DataFrame(lst) return df",
"..objective import History from ..problem import Problem from ..util import assign_clusters, delete_nan_inf OptimizationResult",
"n_grad self.n_hess: int = n_hess self.n_res: int = n_res self.n_sres: int = n_sres",
"time summary: {times_message}\\n\" f\"* summary of optimizer messages:\\n{counter_message}\\n\" f\"* best value found (approximately)",
"clust, clustsize = assign_clusters(delete_nan_inf(self.fval)[1]) counter_message = '\\n'.join( [\"\\tCount\\tMessage\"] + [ f\"\\t{count}\\t{message}\" for message,",
"res[key] for key in keys} for res in lst] return lst def get_for_key(self,",
"vectors/matrices. Parameters ---------- problem: problem which contains info about how to convert to",
"other.list = deepcopy(self.list) return other def __getattr__(self, key): \"\"\"Define `optimize_result.key`.\"\"\" try: return [res[key]",
"the i-th result.\"\"\" try: return self.list[index] except IndexError: raise IndexError( f\"{index} out of",
"checking for duplicate ids if optimize_result.id is None: self.list.append(optimize_result) else: new_id = prefix",
"deprecated in favour of \" \"optimize_result['key'] and will be removed in future \"",
"float = fval0 self.history: History = history self.exitflag: int = exitflag self.time: float",
"1)} \\n\" f\"* best value: {self[0]['fval']}, \" f\"worst value: {self[-1]['fval']} \\n\\n\" f\"A summary",
"list, return only the specified values. Parameters ---------- keys: list(str), optional Labels of",
"keys is a list, return only the specified values. Parameters ---------- keys: list(str),",
"prefix + identifier for identifier in optimize_result.id if identifier is not None ]",
"def update_to_full(self, problem: Problem) -> None: \"\"\" Update values to full vectors/matrices. Parameters",
"class OptimizeResult: \"\"\"Result of the :py:func:`pypesto.optimize.minimize` function.\"\"\" def __init__(self): self.list = [] def",
"id you want to merge coincides with \" \"the existing id's. Please use",
"problem which contains info about how to convert to full vectors or matrices",
"id's you want to merge coincide with \" \"the existing id's. Please use",
"id self.x: np.ndarray = np.array(x) if x is not None else None self.fval:",
"dict.__setitem__ __delattr__ = dict.__delitem__ def summary(self): \"\"\"Get summary of the object.\"\"\" message =",
"get_fval(res): return res.fval if not np.isnan(res.fval) else np.inf self.list = sorted(self.list, key=get_fval) def",
"f\"* message: {self.message} \\n\" f\"* number of evaluations: {self.n_fval} \\n\" f\"* time taken",
"history: History = None, exitflag: int = None, time: float = None, message:",
"= history self.exitflag: int = exitflag self.time: float = time self.message: str =",
"if keys is not None: lst = [{key: res[key] for key in keys}",
"from copy import deepcopy from typing import Sequence, Union import numpy as np",
"= problem.get_full_vector(self.grad) self.hess = problem.get_full_matrix(self.hess) self.x0 = problem.get_full_vector(self.x0, problem.x_fixed_vals) class OptimizeResult: \"\"\"Result of",
"x0: np.ndarray = None, fval0: float = None, history: History = None, exitflag:",
"None, exitflag: int = None, time: float = None, message: str = None,",
"result.\"\"\" try: return self.list[index] except IndexError: raise IndexError( f\"{index} out of range for",
"all appended results will be prefixed with this. \"\"\" current_ids = set(self.id) if",
"time. message: str Textual comment on the optimization result. optimizer: str The optimizer",
"if x is not None else None self.fval: float = fval self.grad: np.ndarray",
"f\"\\t{count}\\t{message}\" for message, count in Counter(self.message).most_common() ] ) times_message = ( f'\\n\\tMean execution",
"self.history: History = history self.exitflag: int = exitflag self.time: float = time self.message:",
"{np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' ) summary = ( \"## Optimization",
"= dict.__setitem__ __delattr__ = dict.__delitem__ def summary(self): \"\"\"Get summary of the object.\"\"\" message",
"self.res: np.ndarray = np.array(res) if res is not None else None self.sres: np.ndarray",
"of the best run:\\n\\n{self[0].summary()}\" ) return summary def append( self, optimize_result: OptimizationResult, sort:",
"Counter from copy import deepcopy from typing import Sequence, Union import numpy as",
"duplicate ids if optimize_result.id is None: self.list.append(optimize_result) else: new_id = prefix + optimize_result.id",
"deepcopy from typing import Sequence, Union import numpy as np import pandas as",
"\\n\" f\"* number of evaluations: {self.n_fval} \\n\" f\"* time taken to optimize: {self.time}",
"res in self.list] except KeyError: raise AttributeError(key) def __getitem__(self, index): \"\"\"Define `optimize_result[i]` to",
"clustsize = assign_clusters(delete_nan_inf(self.fval)[1]) counter_message = '\\n'.join( [\"\\tCount\\tMessage\"] + [ f\"\\t{count}\\t{message}\" for message, count",
"append( self, optimize_result: OptimizationResult, sort: bool = True, prefix: str = '', ):",
"to the result object. Parameters ---------- optimize_result: The result of one or more",
"= set(self.id) if isinstance(optimize_result, OptimizeResult): new_ids = [ prefix + identifier for identifier",
"problem.get_full_vector(self.grad) self.hess = problem.get_full_matrix(self.hess) self.x0 = problem.get_full_vector(self.x0, problem.x_fixed_vals) class OptimizeResult: \"\"\"Result of the",
"the field to extract. \"\"\" lst = self.list if keys is not None:",
"float = time self.message: str = message self.optimizer = optimizer def __getattr__(self, key):",
"except IndexError: raise IndexError( f\"{index} out of range for optimize result of \"",
"as a standardized return value to map from the individual result objects returned",
"from typing import Sequence, Union import numpy as np import pandas as pd",
"parameters. fval: The best found function value, `fun(x)`. grad: The gradient at `x`.",
"None, n_fval: int = None, n_grad: int = None, n_hess: int = None,",
"dict.__delitem__ def summary(self): \"\"\"Get summary of the object.\"\"\" message = ( \"### Optimizer",
"self.x: np.ndarray = np.array(x) if x is not None else None self.fval: float",
"\"The id you want to merge coincides with \" \"the existing id's. Please",
"is a list, return only the specified values, otherwise all. \"\"\" lst =",
"for key in keys} for res in lst] return lst def get_for_key(self, key)",
"for identifier in optimize_result.id if identifier is not None ] if current_ids.isdisjoint(new_ids) and",
"function evaluations. n_grad: Number of gradient evaluations. n_hess: Number of Hessian evaluations. n_res:",
"import warnings from collections import Counter from copy import deepcopy from typing import",
"self.fval: float = fval self.grad: np.ndarray = np.array(grad) if grad is not None",
"= prefix + optimize_result.id if new_id in current_ids: raise ValueError( \"The id you",
"return value to map from the individual result objects returned by the employed",
"'OptimizeResult'] class OptimizerResult(dict): \"\"\" The result of an optimizer run. Used as a",
"if res is not None else None self.sres: np.ndarray = np.array(sres) if sres",
"= fval self.grad: np.ndarray = np.array(grad) if grad is not None else None",
"DataFrame. If keys is a list, return only the specified values, otherwise all.",
"OptimizeResult: \"\"\"Result of the :py:func:`pypesto.optimize.minimize` function.\"\"\" def __init__(self): self.list = [] def __deepcopy__(self,",
"= np.array(sres) if sres is not None else None self.n_fval: int = n_fval",
"object. Parameters ---------- optimize_result: The result of one or more (local) optimizer run.",
"i-th result.\"\"\" try: return self.list[index] except IndexError: raise IndexError( f\"{index} out of range",
"df = pd.DataFrame(lst) return df def as_list(self, keys=None) -> Sequence: \"\"\" Get as",
"f\"* time taken to optimize: {self.time} \\n\" f\"* startpoint: {self.x0} \\n\" f\"* endpoint:",
"hessian value: {self.hess} \\n\" if self.res is not None: message += f\"* final",
"\"Some id's you want to merge coincide with \" \"the existing id's. Please",
"range for optimize result of \" f\"length {len(self.list)}.\" ) def __len__(self): return len(self.list)",
"keys} for res in lst] return lst def get_for_key(self, key) -> list: \"\"\"Extract",
"Please use an \" \"appropriate prefix such as 'run_2_'.\" ) for optimizer_result in",
"= self.as_list(keys) df = pd.DataFrame(lst) return df def as_list(self, keys=None) -> Sequence: \"\"\"",
"optimizer_result in optimize_result.list: self.append(optimizer_result, sort=False, prefix=prefix) elif isinstance(optimize_result, OptimizerResult): # if id is",
"hess: The Hessian at `x`. res: The residuals at `x`. sres: The residual",
"None. \"\"\" def __init__( self, id: str = None, x: np.ndarray = None,",
"sort: self.sort() def sort(self): \"\"\"Sort the optimizer results by function value fval (ascending).\"\"\"",
"None else None self.hess: np.ndarray = np.array(hess) if hess is not None else",
"convert to full vectors or matrices \"\"\" self.x = problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad =",
"def __init__( self, id: str = None, x: np.ndarray = None, fval: float",
"optimize_result.id = new_id self.list.append(optimize_result) if sort: self.sort() def sort(self): \"\"\"Sort the optimizer results",
"self.hess: np.ndarray = np.array(hess) if hess is not None else None self.res: np.ndarray",
"\" f\"{1 + max(clust) - sum(clustsize == 1)} \\n\" f\"* best value: {self[0]['fval']},",
"None else None self.n_fval: int = n_fval self.n_grad: int = n_grad self.n_hess: int",
"lst def get_for_key(self, key) -> list: \"\"\"Extract the list of values for the",
"Notes ----- Any field not supported by the optimizer is filled with None.",
"problem: Problem) -> None: \"\"\" Update values to full vectors/matrices. Parameters ---------- problem:",
"int = None, n_hess: int = None, n_res: int = None, n_sres: int",
"'run_2_'.\" ) for optimizer_result in optimize_result.list: self.append(optimizer_result, sort=False, prefix=prefix) elif isinstance(optimize_result, OptimizerResult): #",
"None, hess: np.ndarray = None, res: np.ndarray = None, sres: np.ndarray = None,",
"np.ndarray = None, n_fval: int = None, n_grad: int = None, n_hess: int",
"optimizer run. Used as a standardized return value to map from the individual",
"{len(self.list)}.\" ) def __len__(self): return len(self.list) def summary(self): \"\"\"Get summary of the object.\"\"\"",
"\"\"\" Update values to full vectors/matrices. Parameters ---------- problem: problem which contains info",
"without checking for duplicate ids if optimize_result.id is None: self.list.append(optimize_result) else: new_id =",
"comment on the optimization result. optimizer: str The optimizer used for optimization. Notes",
"ValueError( \"Some id's you want to merge coincide with \" \"the existing id's.",
"OptimizationResult = Union['OptimizerResult', 'OptimizeResult'] class OptimizerResult(dict): \"\"\" The result of an optimizer run.",
"= np.array(x) if x is not None else None self.fval: float = fval",
"def __getattr__(self, key): \"\"\"Define `optimize_result.key`.\"\"\" try: return [res[key] for res in self.list] except",
"the optimizer. time: Execution time. message: str Textual comment on the optimization result.",
"self, optimize_result: OptimizationResult, sort: bool = True, prefix: str = '', ): \"\"\"",
"lst = self.as_list(keys) df = pd.DataFrame(lst) return df def as_list(self, keys=None) -> Sequence:",
"grad: The gradient at `x`. hess: The Hessian at `x`. res: The residuals",
"# add fval, gradient, hessian, res, sres if available if self.fval is not",
"+= f\"* final hessian value: {self.hess} \\n\" if self.res is not None: message",
"optimize_result.id if identifier is not None ] if current_ids.isdisjoint(new_ids) and new_ids: raise ValueError(",
"int = None, n_res: int = None, n_sres: int = None, x0: np.ndarray",
"will be removed in future \" \"releases.\" ) return [res[key] for res in",
"# perform clustering for better information clust, clustsize = assign_clusters(delete_nan_inf(self.fval)[1]) counter_message = '\\n'.join(",
"endpoint: {self.x} \\n\" ) # add fval, gradient, hessian, res, sres if available",
"None, n_sres: int = None, x0: np.ndarray = None, fval0: float = None,",
"f\"* final objective value: {self.fval} \\n\" if self.grad is not None: message +=",
"History = history self.exitflag: int = exitflag self.time: float = time self.message: str",
"`fun(x0)`. history: Objective history. exitflag: The exitflag of the optimizer. time: Execution time.",
"__getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(key) __setattr__ = dict.__setitem__ __delattr__",
"time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' ) summary = ( \"##",
"int = n_res self.n_sres: int = n_sres self.x0: np.ndarray = np.array(x0) if x0",
"in Counter(self.message).most_common() ] ) times_message = ( f'\\n\\tMean execution time: {np.mean(self.time)}s\\n' f'\\tMaximum execution",
"Parameters ---------- problem: problem which contains info about how to convert to full",
"for all appended results will be prefixed with this. \"\"\" current_ids = set(self.id)",
"starting function value, `fun(x0)`. history: Objective history. exitflag: The exitflag of the optimizer.",
"The residuals at `x`. sres: The residual sensitivities at `x`. n_fval Number of",
"is not None: message += f\"* final residual value: {self.res} \\n\" if self.sres",
"of function evaluations. n_grad: Number of gradient evaluations. n_hess: Number of Hessian evaluations.",
"function value, `fun(x0)`. history: Objective history. exitflag: The exitflag of the optimizer. time:",
"not None else None self.n_fval: int = n_fval self.n_grad: int = n_grad self.n_hess:",
"to convert to full vectors or matrices \"\"\" self.x = problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad",
"np.ndarray = np.array(res) if res is not None else None self.sres: np.ndarray =",
"\"\"\" Get as list. If keys is a list, return only the specified",
"None, x: np.ndarray = None, fval: float = None, grad: np.ndarray = None,",
"np.ndarray = np.array(x0) if x0 is not None else None self.fval0: float =",
"isinstance(optimize_result, OptimizerResult): # if id is None, append without checking for duplicate ids",
"The optimizer used for optimization. Notes ----- Any field not supported by the",
"sorted(self.list, key=get_fval) def as_dataframe(self, keys=None) -> pd.DataFrame: \"\"\" Get as pandas DataFrame. If",
"{self.fval} \\n\" if self.grad is not None: message += f\"* final gradient value:",
"as_list(self, keys=None) -> Sequence: \"\"\" Get as list. If keys is a list,",
"of the field to extract. \"\"\" lst = self.list if keys is not",
"lst = self.list if keys is not None: lst = [{key: res[key] for",
"to optimize: {self.time} \\n\" f\"* startpoint: {self.x0} \\n\" f\"* endpoint: {self.x} \\n\" )",
"\" f\"worst value: {self[-1]['fval']} \\n\\n\" f\"A summary of the best run:\\n\\n{self[0].summary()}\" ) return",
"Please use an \" \"appropriate prefix such as 'run_2_'.\" ) optimize_result.id = new_id",
"sort once when appending an optimize_result. prefix: The IDs for all appended results",
"message += f\"* final residual value: {self.res} \\n\" if self.sres is not None:",
"True, prefix: str = '', ): \"\"\" Append an OptimizerResult or an OptimizeResult",
"def as_dataframe(self, keys=None) -> pd.DataFrame: \"\"\" Get as pandas DataFrame. If keys is",
"time self.message: str = message self.optimizer = optimizer def __getattr__(self, key): try: return",
"`x`. hess: The Hessian at `x`. res: The residuals at `x`. sres: The",
"to extract. \"\"\" lst = self.list if keys is not None: lst =",
"isinstance(optimize_result, OptimizeResult): new_ids = [ prefix + identifier for identifier in optimize_result.id if",
"message += f\"* final gradient value: {self.grad} \\n\" if self.hess is not None:",
"\"## Optimization Result \\n\\n\" f\"* number of starts: {len(self)} \\n\" f\"* execution time",
"[ prefix + identifier for identifier in optimize_result.id if identifier is not None",
"None, sres: np.ndarray = None, n_fval: int = None, n_grad: int = None,",
"gradient evaluations. n_hess: Number of Hessian evaluations. n_res: Number of residuals evaluations. n_sres:",
"if self.hess is not None: message += f\"* final hessian value: {self.hess} \\n\"",
"with None. \"\"\" def __init__( self, id: str = None, x: np.ndarray =",
"): super().__init__() self.id = id self.x: np.ndarray = np.array(x) if x is not",
"None, fval: float = None, grad: np.ndarray = None, hess: np.ndarray = None,",
"float = None, message: str = None, optimizer: str = None, ): super().__init__()",
"fval, gradient, hessian, res, sres if available if self.fval is not None: message",
"merge coincide with \" \"the existing id's. Please use an \" \"appropriate prefix",
"import Sequence, Union import numpy as np import pandas as pd from ..objective",
"\"\"\" The result of an optimizer run. Used as a standardized return value",
"(ascending).\"\"\" def get_fval(res): return res.fval if not np.isnan(res.fval) else np.inf self.list = sorted(self.list,",
"optimizer used: {self.optimizer} \\n\" f\"* message: {self.message} \\n\" f\"* number of evaluations: {self.n_fval}",
"at `x`. hess: The Hessian at `x`. res: The residuals at `x`. sres:",
"startpoint: {self.x0} \\n\" f\"* endpoint: {self.x} \\n\" ) # add fval, gradient, hessian,",
"{self.x0} \\n\" f\"* endpoint: {self.x} \\n\" ) # add fval, gradient, hessian, res,",
"\\n\" if self.grad is not None: message += f\"* final gradient value: {self.grad}",
"specified key as a list.\"\"\" warnings.warn( \"get_for_key() is deprecated in favour of \"",
"= np.array(hess) if hess is not None else None self.res: np.ndarray = np.array(res)",
"None self.sres: np.ndarray = np.array(sres) if sres is not None else None self.n_fval:",
"= n_hess self.n_res: int = n_res self.n_sres: int = n_sres self.x0: np.ndarray =",
"res, sres if available if self.fval is not None: message += f\"* final",
"] ) times_message = ( f'\\n\\tMean execution time: {np.mean(self.time)}s\\n' f'\\tMaximum execution time: {np.max(self.time)}s,'",
"self.list] except KeyError: raise AttributeError(key) def __getitem__(self, index): \"\"\"Define `optimize_result[i]` to access the",
"at `x`. res: The residuals at `x`. sres: The residual sensitivities at `x`.",
"employed optimizers to the format understood by pypesto. Can be used like a",
"info about how to convert to full vectors or matrices \"\"\" self.x =",
"int = None, x0: np.ndarray = None, fval0: float = None, history: History",
"np.ndarray = None, fval0: float = None, history: History = None, exitflag: int",
"{np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' ) summary = ( \"## Optimization Result \\n\\n\" f\"* number of",
"prefix such as 'run_2_'.\" ) for optimizer_result in optimize_result.list: self.append(optimizer_result, sort=False, prefix=prefix) elif",
"f\"* final hessian value: {self.hess} \\n\" if self.res is not None: message +=",
"run. sort: Boolean used so we only sort once when appending an optimize_result.",
"keys is not None: lst = [{key: res[key] for key in keys} for",
"starts: {len(self)} \\n\" f\"* execution time summary: {times_message}\\n\" f\"* summary of optimizer messages:\\n{counter_message}\\n\"",
"of gradient evaluations. n_hess: Number of Hessian evaluations. n_res: Number of residuals evaluations.",
"raise AttributeError(key) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def summary(self): \"\"\"Get summary of",
"def get_fval(res): return res.fval if not np.isnan(res.fval) else np.inf self.list = sorted(self.list, key=get_fval)",
"message def update_to_full(self, problem: Problem) -> None: \"\"\" Update values to full vectors/matrices.",
"-> pd.DataFrame: \"\"\" Get as pandas DataFrame. If keys is a list, return",
"None else None self.fval: float = fval self.grad: np.ndarray = np.array(grad) if grad",
"execution time: {np.mean(self.time)}s\\n' f'\\tMaximum execution time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}'",
"\" \"optimize_result['key'] and will be removed in future \" \"releases.\" ) return [res[key]",
"optimize_result. prefix: The IDs for all appended results will be prefixed with this.",
"if current_ids.isdisjoint(new_ids) and new_ids: raise ValueError( \"Some id's you want to merge coincide",
"f\"* final gradient value: {self.grad} \\n\" if self.hess is not None: message +=",
"how to convert to full vectors or matrices \"\"\" self.x = problem.get_full_vector(self.x, problem.x_fixed_vals)",
"of residual sensitivity evaluations. x0: The starting parameters. fval0: The starting function value,",
"result of \" f\"length {len(self.list)}.\" ) def __len__(self): return len(self.list) def summary(self): \"\"\"Get",
"of Hessian evaluations. n_res: Number of residuals evaluations. n_sres: Number of residual sensitivity",
"max(clust) - sum(clustsize == 1)} \\n\" f\"* best value: {self[0]['fval']}, \" f\"worst value:",
"lst = [{key: res[key] for key in keys} for res in lst] return",
"The result of one or more (local) optimizer run. sort: Boolean used so",
"pd from ..objective import History from ..problem import Problem from ..util import assign_clusters,",
"\\n\" f\"* number of plateaus found: \" f\"{1 + max(clust) - sum(clustsize ==",
"pandas as pd from ..objective import History from ..problem import Problem from ..util",
"optimizer messages:\\n{counter_message}\\n\" f\"* best value found (approximately) {clustsize[0]} time(s) \\n\" f\"* number of",
"used for optimization. Notes ----- Any field not supported by the optimizer is",
"= id self.x: np.ndarray = np.array(x) if x is not None else None",
"The gradient at `x`. hess: The Hessian at `x`. res: The residuals at",
"of the :py:func:`pypesto.optimize.minimize` function.\"\"\" def __init__(self): self.list = [] def __deepcopy__(self, memo): other",
"used so we only sort once when appending an optimize_result. prefix: The IDs",
"+ identifier for identifier in optimize_result.id if identifier is not None ] if",
"df def as_list(self, keys=None) -> Sequence: \"\"\" Get as list. If keys is",
"`optimize_result[i]` to access the i-th result.\"\"\" try: return self.list[index] except IndexError: raise IndexError(",
"key=get_fval) def as_dataframe(self, keys=None) -> pd.DataFrame: \"\"\" Get as pandas DataFrame. If keys",
"not None: message += f\"* final residual sensitivity: {self.sres} \\n\" return message def",
"if self.grad is not None: message += f\"* final gradient value: {self.grad} \\n\"",
"import deepcopy from typing import Sequence, Union import numpy as np import pandas",
"an \" \"appropriate prefix such as 'run_2_'.\" ) for optimizer_result in optimize_result.list: self.append(optimizer_result,",
"__len__(self): return len(self.list) def summary(self): \"\"\"Get summary of the object.\"\"\" # perform clustering",
"a standardized return value to map from the individual result objects returned by",
"optional Labels of the field to extract. \"\"\" lst = self.list if keys",
"None: message += f\"* final objective value: {self.fval} \\n\" if self.grad is not",
"clustering for better information clust, clustsize = assign_clusters(delete_nan_inf(self.fval)[1]) counter_message = '\\n'.join( [\"\\tCount\\tMessage\"] +",
"\"the existing id's. Please use an \" \"appropriate prefix such as 'run_2_'.\" )",
"once when appending an optimize_result. prefix: The IDs for all appended results will",
"filled with None. \"\"\" def __init__( self, id: str = None, x: np.ndarray",
"id: Id of the optimizer run. Usually the start index. x: The best",
"function.\"\"\" def __init__(self): self.list = [] def __deepcopy__(self, memo): other = OptimizeResult() other.list",
"Labels of the field to extract. \"\"\" lst = self.list if keys is",
"summary: {times_message}\\n\" f\"* summary of optimizer messages:\\n{counter_message}\\n\" f\"* best value found (approximately) {clustsize[0]}",
"supported by the optimizer is filled with None. \"\"\" def __init__( self, id:",
"int = n_grad self.n_hess: int = n_hess self.n_res: int = n_res self.n_sres: int",
"Parameters ---------- keys: list(str), optional Labels of the field to extract. \"\"\" lst",
"`x`. res: The residuals at `x`. sres: The residual sensitivities at `x`. n_fval",
"perform clustering for better information clust, clustsize = assign_clusters(delete_nan_inf(self.fval)[1]) counter_message = '\\n'.join( [\"\\tCount\\tMessage\"]",
"def __deepcopy__(self, memo): other = OptimizeResult() other.list = deepcopy(self.list) return other def __getattr__(self,",
"int = n_hess self.n_res: int = n_res self.n_sres: int = n_sres self.x0: np.ndarray",
"np.ndarray = np.array(grad) if grad is not None else None self.hess: np.ndarray =",
"__init__( self, id: str = None, x: np.ndarray = None, fval: float =",
"= None, history: History = None, exitflag: int = None, time: float =",
"from the individual result objects returned by the employed optimizers to the format",
"keys is a list, return only the specified values, otherwise all. \"\"\" lst",
"the list of values for the specified key as a list.\"\"\" warnings.warn( \"get_for_key()",
"The best found function value, `fun(x)`. grad: The gradient at `x`. hess: The",
"self.sres: np.ndarray = np.array(sres) if sres is not None else None self.n_fval: int",
"optimize_result.id if new_id in current_ids: raise ValueError( \"The id you want to merge",
"otherwise all. \"\"\" lst = self.as_list(keys) df = pd.DataFrame(lst) return df def as_list(self,",
"self.grad = problem.get_full_vector(self.grad) self.hess = problem.get_full_matrix(self.hess) self.x0 = problem.get_full_vector(self.x0, problem.x_fixed_vals) class OptimizeResult: \"\"\"Result",
"OptimizeResult to the result object. Parameters ---------- optimize_result: The result of one or",
"The exitflag of the optimizer. time: Execution time. message: str Textual comment on",
"as pandas DataFrame. If keys is a list, return only the specified values,",
"in self.list] except KeyError: raise AttributeError(key) def __getitem__(self, index): \"\"\"Define `optimize_result[i]` to access",
"as 'run_2_'.\" ) for optimizer_result in optimize_result.list: self.append(optimizer_result, sort=False, prefix=prefix) elif isinstance(optimize_result, OptimizerResult):",
"\"\"\"Optimization result.\"\"\" import warnings from collections import Counter from copy import deepcopy from",
"elif isinstance(optimize_result, OptimizerResult): # if id is None, append without checking for duplicate",
"np.ndarray = np.array(x) if x is not None else None self.fval: float =",
"not None: message += f\"* final gradient value: {self.grad} \\n\" if self.hess is",
"OptimizationResult, sort: bool = True, prefix: str = '', ): \"\"\" Append an",
"-> Sequence: \"\"\" Get as list. If keys is a list, return only",
"parameters. fval0: The starting function value, `fun(x0)`. history: Objective history. exitflag: The exitflag",
"str = message self.optimizer = optimizer def __getattr__(self, key): try: return self[key] except",
") # add fval, gradient, hessian, res, sres if available if self.fval is",
"the format understood by pypesto. Can be used like a dict. Attributes ----------",
"of the optimizer run. Usually the start index. x: The best found parameters.",
"by pypesto. Can be used like a dict. Attributes ---------- id: Id of",
"\"\"\"Define `optimize_result[i]` to access the i-th result.\"\"\" try: return self.list[index] except IndexError: raise",
"= ( \"## Optimization Result \\n\\n\" f\"* number of starts: {len(self)} \\n\" f\"*",
"other = OptimizeResult() other.list = deepcopy(self.list) return other def __getattr__(self, key): \"\"\"Define `optimize_result.key`.\"\"\"",
"out of range for optimize result of \" f\"length {len(self.list)}.\" ) def __len__(self):",
"\"\"\"Result of the :py:func:`pypesto.optimize.minimize` function.\"\"\" def __init__(self): self.list = [] def __deepcopy__(self, memo):",
"time: float = None, message: str = None, optimizer: str = None, ):",
"None, n_hess: int = None, n_res: int = None, n_sres: int = None,",
"the start index. x: The best found parameters. fval: The best found function",
"{self.grad} \\n\" if self.hess is not None: message += f\"* final hessian value:",
"return other def __getattr__(self, key): \"\"\"Define `optimize_result.key`.\"\"\" try: return [res[key] for res in",
"\\n\\n\" f\"* optimizer used: {self.optimizer} \\n\" f\"* message: {self.message} \\n\" f\"* number of",
"def get_for_key(self, key) -> list: \"\"\"Extract the list of values for the specified",
"start index. x: The best found parameters. fval: The best found function value,",
"(approximately) {clustsize[0]} time(s) \\n\" f\"* number of plateaus found: \" f\"{1 + max(clust)",
"{self.message} \\n\" f\"* number of evaluations: {self.n_fval} \\n\" f\"* time taken to optimize:",
"int = n_fval self.n_grad: int = n_grad self.n_hess: int = n_hess self.n_res: int",
"is a list, return only the specified values. Parameters ---------- keys: list(str), optional",
"sort: Boolean used so we only sort once when appending an optimize_result. prefix:",
"\"\"\" lst = self.as_list(keys) df = pd.DataFrame(lst) return df def as_list(self, keys=None) ->",
"\"\"\"Extract the list of values for the specified key as a list.\"\"\" warnings.warn(",
"as list. If keys is a list, return only the specified values. Parameters",
"def as_list(self, keys=None) -> Sequence: \"\"\" Get as list. If keys is a",
"value, `fun(x)`. grad: The gradient at `x`. hess: The Hessian at `x`. res:",
"self.hess = problem.get_full_matrix(self.hess) self.x0 = problem.get_full_vector(self.x0, problem.x_fixed_vals) class OptimizeResult: \"\"\"Result of the :py:func:`pypesto.optimize.minimize`",
"= fval0 self.history: History = history self.exitflag: int = exitflag self.time: float =",
"fval: float = None, grad: np.ndarray = None, hess: np.ndarray = None, res:",
"= '\\n'.join( [\"\\tCount\\tMessage\"] + [ f\"\\t{count}\\t{message}\" for message, count in Counter(self.message).most_common() ] )",
"and new_ids: raise ValueError( \"Some id's you want to merge coincide with \"",
"len(self.list) def summary(self): \"\"\"Get summary of the object.\"\"\" # perform clustering for better",
"None, ): super().__init__() self.id = id self.x: np.ndarray = np.array(x) if x is",
"= n_sres self.x0: np.ndarray = np.array(x0) if x0 is not None else None",
"If keys is a list, return only the specified values, otherwise all. \"\"\"",
"times_message = ( f'\\n\\tMean execution time: {np.mean(self.time)}s\\n' f'\\tMaximum execution time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum",
"identifier in optimize_result.id if identifier is not None ] if current_ids.isdisjoint(new_ids) and new_ids:",
"prefix=prefix) elif isinstance(optimize_result, OptimizerResult): # if id is None, append without checking for",
"np import pandas as pd from ..objective import History from ..problem import Problem",
"\"appropriate prefix such as 'run_2_'.\" ) optimize_result.id = new_id self.list.append(optimize_result) if sort: self.sort()",
"None ] if current_ids.isdisjoint(new_ids) and new_ids: raise ValueError( \"Some id's you want to",
"only sort once when appending an optimize_result. prefix: The IDs for all appended",
"\\n\" ) # add fval, gradient, hessian, res, sres if available if self.fval",
"keys: list(str), optional Labels of the field to extract. \"\"\" lst = self.list",
"starting parameters. fval0: The starting function value, `fun(x0)`. history: Objective history. exitflag: The",
"`x`. sres: The residual sensitivities at `x`. n_fval Number of function evaluations. n_grad:",
"__setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def summary(self): \"\"\"Get summary of the object.\"\"\"",
"= '', ): \"\"\" Append an OptimizerResult or an OptimizeResult to the result",
"values. Parameters ---------- keys: list(str), optional Labels of the field to extract. \"\"\"",
"optimizer: str The optimizer used for optimization. Notes ----- Any field not supported",
"except KeyError: raise AttributeError(key) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def summary(self): \"\"\"Get",
"prefixed with this. \"\"\" current_ids = set(self.id) if isinstance(optimize_result, OptimizeResult): new_ids = [",
"result. optimizer: str The optimizer used for optimization. Notes ----- Any field not",
"an optimizer run. Used as a standardized return value to map from the",
"None, message: str = None, optimizer: str = None, ): super().__init__() self.id =",
"if sres is not None else None self.n_fval: int = n_fval self.n_grad: int",
"f\"{1 + max(clust) - sum(clustsize == 1)} \\n\" f\"* best value: {self[0]['fval']}, \"",
"such as 'run_2_'.\" ) for optimizer_result in optimize_result.list: self.append(optimizer_result, sort=False, prefix=prefix) elif isinstance(optimize_result,",
"\\n\" f\"* message: {self.message} \\n\" f\"* number of evaluations: {self.n_fval} \\n\" f\"* time",
"= n_fval self.n_grad: int = n_grad self.n_hess: int = n_hess self.n_res: int =",
"current_ids = set(self.id) if isinstance(optimize_result, OptimizeResult): new_ids = [ prefix + identifier for",
"collections import Counter from copy import deepcopy from typing import Sequence, Union import",
"= ( f'\\n\\tMean execution time: {np.mean(self.time)}s\\n' f'\\tMaximum execution time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution",
"str = None, ): super().__init__() self.id = id self.x: np.ndarray = np.array(x) if",
"from collections import Counter from copy import deepcopy from typing import Sequence, Union",
"self.grad is not None: message += f\"* final gradient value: {self.grad} \\n\" if",
"self.n_hess: int = n_hess self.n_res: int = n_res self.n_sres: int = n_sres self.x0:",
"time: {np.mean(self.time)}s\\n' f'\\tMaximum execution time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' )",
"is not None: lst = [{key: res[key] for key in keys} for res",
"res in lst] return lst def get_for_key(self, key) -> list: \"\"\"Extract the list",
"fval: The best found function value, `fun(x)`. grad: The gradient at `x`. hess:",
"Execution time. message: str Textual comment on the optimization result. optimizer: str The",
"number of evaluations: {self.n_fval} \\n\" f\"* time taken to optimize: {self.time} \\n\" f\"*",
"problem.get_full_vector(self.x0, problem.x_fixed_vals) class OptimizeResult: \"\"\"Result of the :py:func:`pypesto.optimize.minimize` function.\"\"\" def __init__(self): self.list =",
"+ max(clust) - sum(clustsize == 1)} \\n\" f\"* best value: {self[0]['fval']}, \" f\"worst",
"def __init__(self): self.list = [] def __deepcopy__(self, memo): other = OptimizeResult() other.list =",
") times_message = ( f'\\n\\tMean execution time: {np.mean(self.time)}s\\n' f'\\tMaximum execution time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n'",
"res: np.ndarray = None, sres: np.ndarray = None, n_fval: int = None, n_grad:",
"so we only sort once when appending an optimize_result. prefix: The IDs for",
"\" \"appropriate prefix such as 'run_2_'.\" ) optimize_result.id = new_id self.list.append(optimize_result) if sort:",
"Get as list. If keys is a list, return only the specified values.",
"None, fval0: float = None, history: History = None, exitflag: int = None,",
"int = n_sres self.x0: np.ndarray = np.array(x0) if x0 is not None else",
"messages:\\n{counter_message}\\n\" f\"* best value found (approximately) {clustsize[0]} time(s) \\n\" f\"* number of plateaus",
"= None, fval: float = None, grad: np.ndarray = None, hess: np.ndarray =",
"not None: message += f\"* final objective value: {self.fval} \\n\" if self.grad is",
"number of plateaus found: \" f\"{1 + max(clust) - sum(clustsize == 1)} \\n\"",
"self.n_res: int = n_res self.n_sres: int = n_sres self.x0: np.ndarray = np.array(x0) if",
"key in keys} for res in lst] return lst def get_for_key(self, key) ->",
"None self.hess: np.ndarray = np.array(hess) if hess is not None else None self.res:",
"from ..problem import Problem from ..util import assign_clusters, delete_nan_inf OptimizationResult = Union['OptimizerResult', 'OptimizeResult']",
"import assign_clusters, delete_nan_inf OptimizationResult = Union['OptimizerResult', 'OptimizeResult'] class OptimizerResult(dict): \"\"\" The result of",
"execution time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' ) summary = ( \"## Optimization Result \\n\\n\" f\"*",
"__getitem__(self, index): \"\"\"Define `optimize_result[i]` to access the i-th result.\"\"\" try: return self.list[index] except",
"None, optimizer: str = None, ): super().__init__() self.id = id self.x: np.ndarray =",
"as np import pandas as pd from ..objective import History from ..problem import",
"message = ( \"### Optimizer Result \\n\\n\" f\"* optimizer used: {self.optimizer} \\n\" f\"*",
"x0: The starting parameters. fval0: The starting function value, `fun(x0)`. history: Objective history.",
"optimize_result: OptimizationResult, sort: bool = True, prefix: str = '', ): \"\"\" Append",
"Any field not supported by the optimizer is filled with None. \"\"\" def",
"optimization result. optimizer: str The optimizer used for optimization. Notes ----- Any field",
"format understood by pypesto. Can be used like a dict. Attributes ---------- id:",
"run. Used as a standardized return value to map from the individual result",
"exitflag: The exitflag of the optimizer. time: Execution time. message: str Textual comment",
"f\"{index} out of range for optimize result of \" f\"length {len(self.list)}.\" ) def",
"optimize result of \" f\"length {len(self.list)}.\" ) def __len__(self): return len(self.list) def summary(self):",
"{times_message}\\n\" f\"* summary of optimizer messages:\\n{counter_message}\\n\" f\"* best value found (approximately) {clustsize[0]} time(s)",
"n_grad: Number of gradient evaluations. n_hess: Number of Hessian evaluations. n_res: Number of",
"this. \"\"\" current_ids = set(self.id) if isinstance(optimize_result, OptimizeResult): new_ids = [ prefix +",
"not np.isnan(res.fval) else np.inf self.list = sorted(self.list, key=get_fval) def as_dataframe(self, keys=None) -> pd.DataFrame:",
"keys=None) -> Sequence: \"\"\" Get as list. If keys is a list, return",
"`x`. n_fval Number of function evaluations. n_grad: Number of gradient evaluations. n_hess: Number",
"prefix such as 'run_2_'.\" ) optimize_result.id = new_id self.list.append(optimize_result) if sort: self.sort() def",
"self.id = id self.x: np.ndarray = np.array(x) if x is not None else",
"specified values. Parameters ---------- keys: list(str), optional Labels of the field to extract.",
"Union['OptimizerResult', 'OptimizeResult'] class OptimizerResult(dict): \"\"\" The result of an optimizer run. Used as",
"count in Counter(self.message).most_common() ] ) times_message = ( f'\\n\\tMean execution time: {np.mean(self.time)}s\\n' f'\\tMaximum",
"more (local) optimizer run. sort: Boolean used so we only sort once when",
"is None: self.list.append(optimize_result) else: new_id = prefix + optimize_result.id if new_id in current_ids:",
"np.array(res) if res is not None else None self.sres: np.ndarray = np.array(sres) if",
"n_hess self.n_res: int = n_res self.n_sres: int = n_sres self.x0: np.ndarray = np.array(x0)",
"fval0: The starting function value, `fun(x0)`. history: Objective history. exitflag: The exitflag of",
"\"\"\"Get summary of the object.\"\"\" # perform clustering for better information clust, clustsize",
"in keys} for res in lst] return lst def get_for_key(self, key) -> list:",
"time taken to optimize: {self.time} \\n\" f\"* startpoint: {self.x0} \\n\" f\"* endpoint: {self.x}",
"Id of the optimizer run. Usually the start index. x: The best found",
"the optimizer is filled with None. \"\"\" def __init__( self, id: str =",
") return summary def append( self, optimize_result: OptimizationResult, sort: bool = True, prefix:",
"an OptimizeResult to the result object. Parameters ---------- optimize_result: The result of one",
"extract. \"\"\" lst = self.list if keys is not None: lst = [{key:",
"identifier is not None ] if current_ids.isdisjoint(new_ids) and new_ids: raise ValueError( \"Some id's",
"None else None self.res: np.ndarray = np.array(res) if res is not None else",
"gradient at `x`. hess: The Hessian at `x`. res: The residuals at `x`.",
"optimization. Notes ----- Any field not supported by the optimizer is filled with",
"history: Objective history. exitflag: The exitflag of the optimizer. time: Execution time. message:",
"self.x = problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad = problem.get_full_vector(self.grad) self.hess = problem.get_full_matrix(self.hess) self.x0 = problem.get_full_vector(self.x0,",
"at `x`. sres: The residual sensitivities at `x`. n_fval Number of function evaluations.",
"\\n\\n\" f\"A summary of the best run:\\n\\n{self[0].summary()}\" ) return summary def append( self,",
"a list.\"\"\" warnings.warn( \"get_for_key() is deprecated in favour of \" \"optimize_result['key'] and will",
"= np.array(x0) if x0 is not None else None self.fval0: float = fval0",
"optimizer is filled with None. \"\"\" def __init__( self, id: str = None,",
"__getattr__(self, key): \"\"\"Define `optimize_result.key`.\"\"\" try: return [res[key] for res in self.list] except KeyError:",
"pd.DataFrame(lst) return df def as_list(self, keys=None) -> Sequence: \"\"\" Get as list. If",
"float = None, history: History = None, exitflag: int = None, time: float",
"= None, x: np.ndarray = None, fval: float = None, grad: np.ndarray =",
"the optimizer run. Usually the start index. x: The best found parameters. fval:",
"optimize_result: The result of one or more (local) optimizer run. sort: Boolean used",
"= None, message: str = None, optimizer: str = None, ): super().__init__() self.id",
"def append( self, optimize_result: OptimizationResult, sort: bool = True, prefix: str = '',",
"of residuals evaluations. n_sres: Number of residual sensitivity evaluations. x0: The starting parameters.",
"contains info about how to convert to full vectors or matrices \"\"\" self.x",
"keys=None) -> pd.DataFrame: \"\"\" Get as pandas DataFrame. If keys is a list,",
"x: np.ndarray = None, fval: float = None, grad: np.ndarray = None, hess:",
"np.ndarray = None, hess: np.ndarray = None, res: np.ndarray = None, sres: np.ndarray",
"= Union['OptimizerResult', 'OptimizeResult'] class OptimizerResult(dict): \"\"\" The result of an optimizer run. Used",
"self.n_grad: int = n_grad self.n_hess: int = n_hess self.n_res: int = n_res self.n_sres:",
"Sequence: \"\"\" Get as list. If keys is a list, return only the",
"{self.res} \\n\" if self.sres is not None: message += f\"* final residual sensitivity:",
"in optimize_result.id if identifier is not None ] if current_ids.isdisjoint(new_ids) and new_ids: raise",
"an optimize_result. prefix: The IDs for all appended results will be prefixed with",
"__delattr__ = dict.__delitem__ def summary(self): \"\"\"Get summary of the object.\"\"\" message = (",
"OptimizeResult() other.list = deepcopy(self.list) return other def __getattr__(self, key): \"\"\"Define `optimize_result.key`.\"\"\" try: return",
"access the i-th result.\"\"\" try: return self.list[index] except IndexError: raise IndexError( f\"{index} out",
"for better information clust, clustsize = assign_clusters(delete_nan_inf(self.fval)[1]) counter_message = '\\n'.join( [\"\\tCount\\tMessage\"] + [",
"current_ids: raise ValueError( \"The id you want to merge coincides with \" \"the",
"best value: {self[0]['fval']}, \" f\"worst value: {self[-1]['fval']} \\n\\n\" f\"A summary of the best",
"optimize_result.list: self.append(optimizer_result, sort=False, prefix=prefix) elif isinstance(optimize_result, OptimizerResult): # if id is None, append",
"= sorted(self.list, key=get_fval) def as_dataframe(self, keys=None) -> pd.DataFrame: \"\"\" Get as pandas DataFrame.",
"values to full vectors/matrices. Parameters ---------- problem: problem which contains info about how",
"str = '', ): \"\"\" Append an OptimizerResult or an OptimizeResult to the",
"---------- keys: list(str), optional Labels of the field to extract. \"\"\" lst =",
"summary of the object.\"\"\" # perform clustering for better information clust, clustsize =",
"residuals evaluations. n_sres: Number of residual sensitivity evaluations. x0: The starting parameters. fval0:",
"None, history: History = None, exitflag: int = None, time: float = None,",
"available if self.fval is not None: message += f\"* final objective value: {self.fval}",
"by the employed optimizers to the format understood by pypesto. Can be used",
"{self[0]['fval']}, \" f\"worst value: {self[-1]['fval']} \\n\\n\" f\"A summary of the best run:\\n\\n{self[0].summary()}\" )",
"\"\"\" Get as pandas DataFrame. If keys is a list, return only the",
"+= f\"* final objective value: {self.fval} \\n\" if self.grad is not None: message",
"= assign_clusters(delete_nan_inf(self.fval)[1]) counter_message = '\\n'.join( [\"\\tCount\\tMessage\"] + [ f\"\\t{count}\\t{message}\" for message, count in",
"warnings.warn( \"get_for_key() is deprecated in favour of \" \"optimize_result['key'] and will be removed",
"The starting function value, `fun(x0)`. history: Objective history. exitflag: The exitflag of the",
"to merge coincide with \" \"the existing id's. Please use an \" \"appropriate",
"Number of function evaluations. n_grad: Number of gradient evaluations. n_hess: Number of Hessian",
"None, n_grad: int = None, n_hess: int = None, n_res: int = None,",
"not supported by the optimizer is filled with None. \"\"\" def __init__( self,",
"n_sres self.x0: np.ndarray = np.array(x0) if x0 is not None else None self.fval0:",
"message += f\"* final residual sensitivity: {self.sres} \\n\" return message def update_to_full(self, problem:",
"History from ..problem import Problem from ..util import assign_clusters, delete_nan_inf OptimizationResult = Union['OptimizerResult',",
"\"\"\" lst = self.list if keys is not None: lst = [{key: res[key]",
"None self.res: np.ndarray = np.array(res) if res is not None else None self.sres:",
"evaluations. n_grad: Number of gradient evaluations. n_hess: Number of Hessian evaluations. n_res: Number",
"\"\"\" def __init__( self, id: str = None, x: np.ndarray = None, fval:",
"return self[key] except KeyError: raise AttributeError(key) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def",
"def summary(self): \"\"\"Get summary of the object.\"\"\" message = ( \"### Optimizer Result",
"lst] return lst def get_for_key(self, key) -> list: \"\"\"Extract the list of values",
"object.\"\"\" message = ( \"### Optimizer Result \\n\\n\" f\"* optimizer used: {self.optimizer} \\n\"",
"understood by pypesto. Can be used like a dict. Attributes ---------- id: Id",
"None: message += f\"* final gradient value: {self.grad} \\n\" if self.hess is not",
"at `x`. n_fval Number of function evaluations. n_grad: Number of gradient evaluations. n_hess:",
"is not None: message += f\"* final hessian value: {self.hess} \\n\" if self.res",
"\\n\" if self.sres is not None: message += f\"* final residual sensitivity: {self.sres}",
"is not None else None self.hess: np.ndarray = np.array(hess) if hess is not",
"= [{key: res[key] for key in keys} for res in lst] return lst",
"as_dataframe(self, keys=None) -> pd.DataFrame: \"\"\" Get as pandas DataFrame. If keys is a",
"in optimize_result.list: self.append(optimizer_result, sort=False, prefix=prefix) elif isinstance(optimize_result, OptimizerResult): # if id is None,",
"np.ndarray = None, sres: np.ndarray = None, n_fval: int = None, n_grad: int",
"if x0 is not None else None self.fval0: float = fval0 self.history: History",
"Number of residuals evaluations. n_sres: Number of residual sensitivity evaluations. x0: The starting",
"appended results will be prefixed with this. \"\"\" current_ids = set(self.id) if isinstance(optimize_result,",
"a list, return only the specified values, otherwise all. \"\"\" lst = self.as_list(keys)",
"self.sres is not None: message += f\"* final residual sensitivity: {self.sres} \\n\" return",
"key): try: return self[key] except KeyError: raise AttributeError(key) __setattr__ = dict.__setitem__ __delattr__ =",
"of evaluations: {self.n_fval} \\n\" f\"* time taken to optimize: {self.time} \\n\" f\"* startpoint:",
"message, count in Counter(self.message).most_common() ] ) times_message = ( f'\\n\\tMean execution time: {np.mean(self.time)}s\\n'",
"append without checking for duplicate ids if optimize_result.id is None: self.list.append(optimize_result) else: new_id",
"full vectors or matrices \"\"\" self.x = problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad = problem.get_full_vector(self.grad) self.hess",
"None, grad: np.ndarray = None, hess: np.ndarray = None, res: np.ndarray = None,",
"np.ndarray = None, res: np.ndarray = None, sres: np.ndarray = None, n_fval: int",
"summary = ( \"## Optimization Result \\n\\n\" f\"* number of starts: {len(self)} \\n\"",
"an OptimizerResult or an OptimizeResult to the result object. Parameters ---------- optimize_result: The",
"bool = True, prefix: str = '', ): \"\"\" Append an OptimizerResult or",
"want to merge coincide with \" \"the existing id's. Please use an \"",
"Attributes ---------- id: Id of the optimizer run. Usually the start index. x:",
"else None self.hess: np.ndarray = np.array(hess) if hess is not None else None",
") for optimizer_result in optimize_result.list: self.append(optimizer_result, sort=False, prefix=prefix) elif isinstance(optimize_result, OptimizerResult): # if",
"n_fval self.n_grad: int = n_grad self.n_hess: int = n_hess self.n_res: int = n_res",
"the :py:func:`pypesto.optimize.minimize` function.\"\"\" def __init__(self): self.list = [] def __deepcopy__(self, memo): other =",
"for optimize result of \" f\"length {len(self.list)}.\" ) def __len__(self): return len(self.list) def",
"= [] def __deepcopy__(self, memo): other = OptimizeResult() other.list = deepcopy(self.list) return other",
"list. If keys is a list, return only the specified values. Parameters ----------",
"None else None self.sres: np.ndarray = np.array(sres) if sres is not None else",
"as pd from ..objective import History from ..problem import Problem from ..util import",
"sort=False, prefix=prefix) elif isinstance(optimize_result, OptimizerResult): # if id is None, append without checking",
"use an \" \"appropriate prefix such as 'run_2_'.\" ) optimize_result.id = new_id self.list.append(optimize_result)",
"not None else None self.fval0: float = fval0 self.history: History = history self.exitflag:",
"if grad is not None else None self.hess: np.ndarray = np.array(hess) if hess",
"memo): other = OptimizeResult() other.list = deepcopy(self.list) return other def __getattr__(self, key): \"\"\"Define",
"= None, fval0: float = None, history: History = None, exitflag: int =",
"value: {self.grad} \\n\" if self.hess is not None: message += f\"* final hessian",
"not None else None self.sres: np.ndarray = np.array(sres) if sres is not None",
"self.exitflag: int = exitflag self.time: float = time self.message: str = message self.optimizer",
"or more (local) optimizer run. sort: Boolean used so we only sort once",
"AttributeError(key) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def summary(self): \"\"\"Get summary of the",
"OptimizerResult or an OptimizeResult to the result object. Parameters ---------- optimize_result: The result",
"optimizer run. Usually the start index. x: The best found parameters. fval: The",
"the object.\"\"\" message = ( \"### Optimizer Result \\n\\n\" f\"* optimizer used: {self.optimizer}",
"if isinstance(optimize_result, OptimizeResult): new_ids = [ prefix + identifier for identifier in optimize_result.id",
"in lst] return lst def get_for_key(self, key) -> list: \"\"\"Extract the list of",
"n_hess: int = None, n_res: int = None, n_sres: int = None, x0:",
"of \" f\"length {len(self.list)}.\" ) def __len__(self): return len(self.list) def summary(self): \"\"\"Get summary",
"for res in lst] return lst def get_for_key(self, key) -> list: \"\"\"Extract the",
"the best run:\\n\\n{self[0].summary()}\" ) return summary def append( self, optimize_result: OptimizationResult, sort: bool",
"new_id in current_ids: raise ValueError( \"The id you want to merge coincides with",
"np.array(hess) if hess is not None else None self.res: np.ndarray = np.array(res) if",
"OptimizerResult(dict): \"\"\" The result of an optimizer run. Used as a standardized return",
"field to extract. \"\"\" lst = self.list if keys is not None: lst",
"the specified key as a list.\"\"\" warnings.warn( \"get_for_key() is deprecated in favour of",
"is not None else None self.n_fval: int = n_fval self.n_grad: int = n_grad",
"when appending an optimize_result. prefix: The IDs for all appended results will be",
"The starting parameters. fval0: The starting function value, `fun(x0)`. history: Objective history. exitflag:",
"f\"* endpoint: {self.x} \\n\" ) # add fval, gradient, hessian, res, sres if",
"[] def __deepcopy__(self, memo): other = OptimizeResult() other.list = deepcopy(self.list) return other def",
"prefix: The IDs for all appended results will be prefixed with this. \"\"\"",
") optimize_result.id = new_id self.list.append(optimize_result) if sort: self.sort() def sort(self): \"\"\"Sort the optimizer",
"Parameters ---------- optimize_result: The result of one or more (local) optimizer run. sort:",
"Counter(self.message).most_common() ] ) times_message = ( f'\\n\\tMean execution time: {np.mean(self.time)}s\\n' f'\\tMaximum execution time:",
"appending an optimize_result. prefix: The IDs for all appended results will be prefixed",
"The result of an optimizer run. Used as a standardized return value to",
"final gradient value: {self.grad} \\n\" if self.hess is not None: message += f\"*",
"-> None: \"\"\" Update values to full vectors/matrices. Parameters ---------- problem: problem which",
"None: lst = [{key: res[key] for key in keys} for res in lst]",
"int = None, n_sres: int = None, x0: np.ndarray = None, fval0: float",
"str = None, x: np.ndarray = None, fval: float = None, grad: np.ndarray",
"is not None else None self.sres: np.ndarray = np.array(sres) if sres is not",
"= None, exitflag: int = None, time: float = None, message: str =",
"list, return only the specified values, otherwise all. \"\"\" lst = self.as_list(keys) df",
"the optimizer results by function value fval (ascending).\"\"\" def get_fval(res): return res.fval if",
"+ optimize_result.id if new_id in current_ids: raise ValueError( \"The id you want to",
"the optimization result. optimizer: str The optimizer used for optimization. Notes ----- Any",
"from ..objective import History from ..problem import Problem from ..util import assign_clusters, delete_nan_inf",
"np.array(x) if x is not None else None self.fval: float = fval self.grad:",
"[res[key] for res in self.list] except KeyError: raise AttributeError(key) def __getitem__(self, index): \"\"\"Define",
"try: return self.list[index] except IndexError: raise IndexError( f\"{index} out of range for optimize",
"import numpy as np import pandas as pd from ..objective import History from",
"self, id: str = None, x: np.ndarray = None, fval: float = None,",
"{self.optimizer} \\n\" f\"* message: {self.message} \\n\" f\"* number of evaluations: {self.n_fval} \\n\" f\"*",
"int = None, n_grad: int = None, n_hess: int = None, n_res: int",
"best found function value, `fun(x)`. grad: The gradient at `x`. hess: The Hessian",
"to map from the individual result objects returned by the employed optimizers to",
"= None, time: float = None, message: str = None, optimizer: str =",
"sort: bool = True, prefix: str = '', ): \"\"\" Append an OptimizerResult",
"Hessian evaluations. n_res: Number of residuals evaluations. n_sres: Number of residual sensitivity evaluations.",
"problem.x_fixed_vals) class OptimizeResult: \"\"\"Result of the :py:func:`pypesto.optimize.minimize` function.\"\"\" def __init__(self): self.list = []",
"be used like a dict. Attributes ---------- id: Id of the optimizer run.",
"return res.fval if not np.isnan(res.fval) else np.inf self.list = sorted(self.list, key=get_fval) def as_dataframe(self,",
"by function value fval (ascending).\"\"\" def get_fval(res): return res.fval if not np.isnan(res.fval) else",
"Optimization Result \\n\\n\" f\"* number of starts: {len(self)} \\n\" f\"* execution time summary:",
"grad: np.ndarray = None, hess: np.ndarray = None, res: np.ndarray = None, sres:",
"matrices \"\"\" self.x = problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad = problem.get_full_vector(self.grad) self.hess = problem.get_full_matrix(self.hess) self.x0",
":py:func:`pypesto.optimize.minimize` function.\"\"\" def __init__(self): self.list = [] def __deepcopy__(self, memo): other = OptimizeResult()",
"= True, prefix: str = '', ): \"\"\" Append an OptimizerResult or an",
"values for the specified key as a list.\"\"\" warnings.warn( \"get_for_key() is deprecated in",
"try: return self[key] except KeyError: raise AttributeError(key) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__",
"id's. Please use an \" \"appropriate prefix such as 'run_2_'.\" ) for optimizer_result",
"self.x0: np.ndarray = np.array(x0) if x0 is not None else None self.fval0: float",
"\"get_for_key() is deprecated in favour of \" \"optimize_result['key'] and will be removed in",
"the specified values. Parameters ---------- keys: list(str), optional Labels of the field to",
"- sum(clustsize == 1)} \\n\" f\"* best value: {self[0]['fval']}, \" f\"worst value: {self[-1]['fval']}",
"The Hessian at `x`. res: The residuals at `x`. sres: The residual sensitivities",
"import Counter from copy import deepcopy from typing import Sequence, Union import numpy",
"to access the i-th result.\"\"\" try: return self.list[index] except IndexError: raise IndexError( f\"{index}",
"optimize: {self.time} \\n\" f\"* startpoint: {self.x0} \\n\" f\"* endpoint: {self.x} \\n\" ) #",
"KeyError: raise AttributeError(key) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def summary(self): \"\"\"Get summary",
"= message self.optimizer = optimizer def __getattr__(self, key): try: return self[key] except KeyError:",
"an \" \"appropriate prefix such as 'run_2_'.\" ) optimize_result.id = new_id self.list.append(optimize_result) if",
"and will be removed in future \" \"releases.\" ) return [res[key] for res",
"= None, sres: np.ndarray = None, n_fval: int = None, n_grad: int =",
"self.list.append(optimize_result) if sort: self.sort() def sort(self): \"\"\"Sort the optimizer results by function value",
"result object. Parameters ---------- optimize_result: The result of one or more (local) optimizer",
"of range for optimize result of \" f\"length {len(self.list)}.\" ) def __len__(self): return",
"try: return [res[key] for res in self.list] except KeyError: raise AttributeError(key) def __getitem__(self,",
"favour of \" \"optimize_result['key'] and will be removed in future \" \"releases.\" )",
"the employed optimizers to the format understood by pypesto. Can be used like",
"n_res: int = None, n_sres: int = None, x0: np.ndarray = None, fval0:",
"value: {self.res} \\n\" if self.sres is not None: message += f\"* final residual",
"f\"worst value: {self[-1]['fval']} \\n\\n\" f\"A summary of the best run:\\n\\n{self[0].summary()}\" ) return summary",
"= dict.__delitem__ def summary(self): \"\"\"Get summary of the object.\"\"\" message = ( \"###",
"self.list = [] def __deepcopy__(self, memo): other = OptimizeResult() other.list = deepcopy(self.list) return",
"f\"length {len(self.list)}.\" ) def __len__(self): return len(self.list) def summary(self): \"\"\"Get summary of the",
"\"\"\"Get summary of the object.\"\"\" message = ( \"### Optimizer Result \\n\\n\" f\"*",
"float = None, grad: np.ndarray = None, hess: np.ndarray = None, res: np.ndarray",
"coincides with \" \"the existing id's. Please use an \" \"appropriate prefix such",
"message: {self.message} \\n\" f\"* number of evaluations: {self.n_fval} \\n\" f\"* time taken to",
"raise IndexError( f\"{index} out of range for optimize result of \" f\"length {len(self.list)}.\"",
"evaluations. x0: The starting parameters. fval0: The starting function value, `fun(x0)`. history: Objective",
"else: new_id = prefix + optimize_result.id if new_id in current_ids: raise ValueError( \"The",
"= pd.DataFrame(lst) return df def as_list(self, keys=None) -> Sequence: \"\"\" Get as list.",
"pd.DataFrame: \"\"\" Get as pandas DataFrame. If keys is a list, return only",
"x: The best found parameters. fval: The best found function value, `fun(x)`. grad:",
"delete_nan_inf OptimizationResult = Union['OptimizerResult', 'OptimizeResult'] class OptimizerResult(dict): \"\"\" The result of an optimizer",
"hess: np.ndarray = None, res: np.ndarray = None, sres: np.ndarray = None, n_fval:",
"+ [ f\"\\t{count}\\t{message}\" for message, count in Counter(self.message).most_common() ] ) times_message = (",
"( f'\\n\\tMean execution time: {np.mean(self.time)}s\\n' f'\\tMaximum execution time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution time:",
"None else None self.fval0: float = fval0 self.history: History = history self.exitflag: int",
"Number of residual sensitivity evaluations. x0: The starting parameters. fval0: The starting function",
"objective value: {self.fval} \\n\" if self.grad is not None: message += f\"* final",
"Problem) -> None: \"\"\" Update values to full vectors/matrices. Parameters ---------- problem: problem",
"final hessian value: {self.hess} \\n\" if self.res is not None: message += f\"*",
"self.list.append(optimize_result) else: new_id = prefix + optimize_result.id if new_id in current_ids: raise ValueError(",
"None self.fval: float = fval self.grad: np.ndarray = np.array(grad) if grad is not",
"= new_id self.list.append(optimize_result) if sort: self.sort() def sort(self): \"\"\"Sort the optimizer results by",
"is not None else None self.fval: float = fval self.grad: np.ndarray = np.array(grad)",
"\"\"\" Append an OptimizerResult or an OptimizeResult to the result object. Parameters ----------",
"is filled with None. \"\"\" def __init__( self, id: str = None, x:",
"return self.list[index] except IndexError: raise IndexError( f\"{index} out of range for optimize result",
"import Problem from ..util import assign_clusters, delete_nan_inf OptimizationResult = Union['OptimizerResult', 'OptimizeResult'] class OptimizerResult(dict):",
"if not np.isnan(res.fval) else np.inf self.list = sorted(self.list, key=get_fval) def as_dataframe(self, keys=None) ->",
") summary = ( \"## Optimization Result \\n\\n\" f\"* number of starts: {len(self)}",
"np.isnan(res.fval) else np.inf self.list = sorted(self.list, key=get_fval) def as_dataframe(self, keys=None) -> pd.DataFrame: \"\"\"",
"= None, n_grad: int = None, n_hess: int = None, n_res: int =",
"return [res[key] for res in self.list] except KeyError: raise AttributeError(key) def __getitem__(self, index):",
"\\n\" f\"* best value: {self[0]['fval']}, \" f\"worst value: {self[-1]['fval']} \\n\\n\" f\"A summary of",
"number of starts: {len(self)} \\n\" f\"* execution time summary: {times_message}\\n\" f\"* summary of",
"np.inf self.list = sorted(self.list, key=get_fval) def as_dataframe(self, keys=None) -> pd.DataFrame: \"\"\" Get as",
"residuals at `x`. sres: The residual sensitivities at `x`. n_fval Number of function",
"= time self.message: str = message self.optimizer = optimizer def __getattr__(self, key): try:",
"None self.fval0: float = fval0 self.history: History = history self.exitflag: int = exitflag",
"from ..util import assign_clusters, delete_nan_inf OptimizationResult = Union['OptimizerResult', 'OptimizeResult'] class OptimizerResult(dict): \"\"\" The",
"list.\"\"\" warnings.warn( \"get_for_key() is deprecated in favour of \" \"optimize_result['key'] and will be",
"= problem.get_full_vector(self.x0, problem.x_fixed_vals) class OptimizeResult: \"\"\"Result of the :py:func:`pypesto.optimize.minimize` function.\"\"\" def __init__(self): self.list",
"{self.time} \\n\" f\"* startpoint: {self.x0} \\n\" f\"* endpoint: {self.x} \\n\" ) # add",
"in current_ids: raise ValueError( \"The id you want to merge coincides with \"",
"evaluations. n_res: Number of residuals evaluations. n_sres: Number of residual sensitivity evaluations. x0:",
"\\n\" if self.res is not None: message += f\"* final residual value: {self.res}",
"= None, n_res: int = None, n_sres: int = None, x0: np.ndarray =",
"problem.get_full_matrix(self.hess) self.x0 = problem.get_full_vector(self.x0, problem.x_fixed_vals) class OptimizeResult: \"\"\"Result of the :py:func:`pypesto.optimize.minimize` function.\"\"\" def",
"sensitivity evaluations. x0: The starting parameters. fval0: The starting function value, `fun(x0)`. history:",
"fval0: float = None, history: History = None, exitflag: int = None, time:",
"index): \"\"\"Define `optimize_result[i]` to access the i-th result.\"\"\" try: return self.list[index] except IndexError:",
"f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' ) summary = ( \"## Optimization Result",
"self.list[index] except IndexError: raise IndexError( f\"{index} out of range for optimize result of",
"result.\"\"\" import warnings from collections import Counter from copy import deepcopy from typing",
"value fval (ascending).\"\"\" def get_fval(res): return res.fval if not np.isnan(res.fval) else np.inf self.list",
"= None, grad: np.ndarray = None, hess: np.ndarray = None, res: np.ndarray =",
"found parameters. fval: The best found function value, `fun(x)`. grad: The gradient at",
"History = None, exitflag: int = None, time: float = None, message: str",
"is not None: message += f\"* final objective value: {self.fval} \\n\" if self.grad",
"function value, `fun(x)`. grad: The gradient at `x`. hess: The Hessian at `x`.",
"current_ids.isdisjoint(new_ids) and new_ids: raise ValueError( \"Some id's you want to merge coincide with",
"to full vectors/matrices. Parameters ---------- problem: problem which contains info about how to",
"coincide with \" \"the existing id's. Please use an \" \"appropriate prefix such",
"return only the specified values. Parameters ---------- keys: list(str), optional Labels of the",
"if self.sres is not None: message += f\"* final residual sensitivity: {self.sres} \\n\"",
"f'\\n\\tMean execution time: {np.mean(self.time)}s\\n' f'\\tMaximum execution time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution time: {np.min(self.time)}s,\\t'",
"else None self.res: np.ndarray = np.array(res) if res is not None else None",
"str Textual comment on the optimization result. optimizer: str The optimizer used for",
"The IDs for all appended results will be prefixed with this. \"\"\" current_ids",
"of an optimizer run. Used as a standardized return value to map from",
"{self.x} \\n\" ) # add fval, gradient, hessian, res, sres if available if",
"----- Any field not supported by the optimizer is filled with None. \"\"\"",
"else None self.n_fval: int = n_fval self.n_grad: int = n_grad self.n_hess: int =",
"map from the individual result objects returned by the employed optimizers to the",
"= n_res self.n_sres: int = n_sres self.x0: np.ndarray = np.array(x0) if x0 is",
"return lst def get_for_key(self, key) -> list: \"\"\"Extract the list of values for",
"run. Usually the start index. x: The best found parameters. fval: The best",
"{np.mean(self.time)}s\\n' f'\\tMaximum execution time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' ) summary",
"evaluations. n_hess: Number of Hessian evaluations. n_res: Number of residuals evaluations. n_sres: Number",
"\"optimize_result['key'] and will be removed in future \" \"releases.\" ) return [res[key] for",
"np.array(sres) if sres is not None else None self.n_fval: int = n_fval self.n_grad:",
"of the optimizer. time: Execution time. message: str Textual comment on the optimization",
"\\n\" if self.hess is not None: message += f\"* final hessian value: {self.hess}",
"optimize_result.id is None: self.list.append(optimize_result) else: new_id = prefix + optimize_result.id if new_id in",
"time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' ) summary = ( \"## Optimization Result \\n\\n\" f\"* number",
"n_sres: int = None, x0: np.ndarray = None, fval0: float = None, history:",
"super().__init__() self.id = id self.x: np.ndarray = np.array(x) if x is not None",
"optimizers to the format understood by pypesto. Can be used like a dict.",
"plateaus found: \" f\"{1 + max(clust) - sum(clustsize == 1)} \\n\" f\"* best",
"want to merge coincides with \" \"the existing id's. Please use an \"",
"== 1)} \\n\" f\"* best value: {self[0]['fval']}, \" f\"worst value: {self[-1]['fval']} \\n\\n\" f\"A",
"as 'run_2_'.\" ) optimize_result.id = new_id self.list.append(optimize_result) if sort: self.sort() def sort(self): \"\"\"Sort",
"the specified values, otherwise all. \"\"\" lst = self.as_list(keys) df = pd.DataFrame(lst) return",
"\\n\\n\" f\"* number of starts: {len(self)} \\n\" f\"* execution time summary: {times_message}\\n\" f\"*",
"f'\\tMinimum execution time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' ) summary = ( \"## Optimization Result \\n\\n\"",
"+= f\"* final gradient value: {self.grad} \\n\" if self.hess is not None: message",
"such as 'run_2_'.\" ) optimize_result.id = new_id self.list.append(optimize_result) if sort: self.sort() def sort(self):",
"all. \"\"\" lst = self.as_list(keys) df = pd.DataFrame(lst) return df def as_list(self, keys=None)",
"is not None: message += f\"* final residual sensitivity: {self.sres} \\n\" return message",
"Optimizer Result \\n\\n\" f\"* optimizer used: {self.optimizer} \\n\" f\"* message: {self.message} \\n\" f\"*",
"not None else None self.hess: np.ndarray = np.array(hess) if hess is not None",
"None, n_res: int = None, n_sres: int = None, x0: np.ndarray = None,",
"of starts: {len(self)} \\n\" f\"* execution time summary: {times_message}\\n\" f\"* summary of optimizer",
"= None, hess: np.ndarray = None, res: np.ndarray = None, sres: np.ndarray =",
"key): \"\"\"Define `optimize_result.key`.\"\"\" try: return [res[key] for res in self.list] except KeyError: raise",
"final residual sensitivity: {self.sres} \\n\" return message def update_to_full(self, problem: Problem) -> None:",
"self.grad: np.ndarray = np.array(grad) if grad is not None else None self.hess: np.ndarray",
"KeyError: raise AttributeError(key) def __getitem__(self, index): \"\"\"Define `optimize_result[i]` to access the i-th result.\"\"\"",
"new_id self.list.append(optimize_result) if sort: self.sort() def sort(self): \"\"\"Sort the optimizer results by function",
"in favour of \" \"optimize_result['key'] and will be removed in future \" \"releases.\"",
"int = None, time: float = None, message: str = None, optimizer: str",
"__init__(self): self.list = [] def __deepcopy__(self, memo): other = OptimizeResult() other.list = deepcopy(self.list)",
"-> list: \"\"\"Extract the list of values for the specified key as a",
"( \"### Optimizer Result \\n\\n\" f\"* optimizer used: {self.optimizer} \\n\" f\"* message: {self.message}",
"float = fval self.grad: np.ndarray = np.array(grad) if grad is not None else",
"If keys is a list, return only the specified values. Parameters ---------- keys:",
"f\"* number of plateaus found: \" f\"{1 + max(clust) - sum(clustsize == 1)}",
"raise ValueError( \"The id you want to merge coincides with \" \"the existing",
"information clust, clustsize = assign_clusters(delete_nan_inf(self.fval)[1]) counter_message = '\\n'.join( [\"\\tCount\\tMessage\"] + [ f\"\\t{count}\\t{message}\" for",
"class OptimizerResult(dict): \"\"\" The result of an optimizer run. Used as a standardized",
"np.ndarray = None, fval: float = None, grad: np.ndarray = None, hess: np.ndarray",
"summary(self): \"\"\"Get summary of the object.\"\"\" message = ( \"### Optimizer Result \\n\\n\"",
"of one or more (local) optimizer run. sort: Boolean used so we only",
"exitflag of the optimizer. time: Execution time. message: str Textual comment on the",
"be removed in future \" \"releases.\" ) return [res[key] for res in self.list]",
"= optimizer def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(key) __setattr__",
"be prefixed with this. \"\"\" current_ids = set(self.id) if isinstance(optimize_result, OptimizeResult): new_ids =",
"exitflag: int = None, time: float = None, message: str = None, optimizer:",
"sres: The residual sensitivities at `x`. n_fval Number of function evaluations. n_grad: Number",
"only the specified values, otherwise all. \"\"\" lst = self.as_list(keys) df = pd.DataFrame(lst)",
"of the object.\"\"\" # perform clustering for better information clust, clustsize = assign_clusters(delete_nan_inf(self.fval)[1])",
"summary(self): \"\"\"Get summary of the object.\"\"\" # perform clustering for better information clust,",
"\\n\" f\"* execution time summary: {times_message}\\n\" f\"* summary of optimizer messages:\\n{counter_message}\\n\" f\"* best",
"..problem import Problem from ..util import assign_clusters, delete_nan_inf OptimizationResult = Union['OptimizerResult', 'OptimizeResult'] class",
"np.array(grad) if grad is not None else None self.hess: np.ndarray = np.array(hess) if",
"warnings from collections import Counter from copy import deepcopy from typing import Sequence,",
"None, time: float = None, message: str = None, optimizer: str = None,",
"f\"* number of starts: {len(self)} \\n\" f\"* execution time summary: {times_message}\\n\" f\"* summary",
"None, append without checking for duplicate ids if optimize_result.id is None: self.list.append(optimize_result) else:",
"None: message += f\"* final hessian value: {self.hess} \\n\" if self.res is not",
"x is not None else None self.fval: float = fval self.grad: np.ndarray =",
"f\"* final residual sensitivity: {self.sres} \\n\" return message def update_to_full(self, problem: Problem) ->",
"list: \"\"\"Extract the list of values for the specified key as a list.\"\"\"",
"Number of gradient evaluations. n_hess: Number of Hessian evaluations. n_res: Number of residuals",
"---------- problem: problem which contains info about how to convert to full vectors",
"not None: lst = [{key: res[key] for key in keys} for res in",
"if self.res is not None: message += f\"* final residual value: {self.res} \\n\"",
"final residual value: {self.res} \\n\" if self.sres is not None: message += f\"*",
"residual value: {self.res} \\n\" if self.sres is not None: message += f\"* final",
"\"\"\"Define `optimize_result.key`.\"\"\" try: return [res[key] for res in self.list] except KeyError: raise AttributeError(key)",
"existing id's. Please use an \" \"appropriate prefix such as 'run_2_'.\" ) optimize_result.id",
"self.n_sres: int = n_sres self.x0: np.ndarray = np.array(x0) if x0 is not None",
"Append an OptimizerResult or an OptimizeResult to the result object. Parameters ---------- optimize_result:",
"\" \"appropriate prefix such as 'run_2_'.\" ) for optimizer_result in optimize_result.list: self.append(optimizer_result, sort=False,",
"for message, count in Counter(self.message).most_common() ] ) times_message = ( f'\\n\\tMean execution time:",
"= None, n_sres: int = None, x0: np.ndarray = None, fval0: float =",
"The residual sensitivities at `x`. n_fval Number of function evaluations. n_grad: Number of",
"n_hess: Number of Hessian evaluations. n_res: Number of residuals evaluations. n_sres: Number of",
") def __len__(self): return len(self.list) def summary(self): \"\"\"Get summary of the object.\"\"\" #",
"exitflag self.time: float = time self.message: str = message self.optimizer = optimizer def",
"return only the specified values, otherwise all. \"\"\" lst = self.as_list(keys) df =",
"Used as a standardized return value to map from the individual result objects",
"= deepcopy(self.list) return other def __getattr__(self, key): \"\"\"Define `optimize_result.key`.\"\"\" try: return [res[key] for",
"\\n\" f\"* startpoint: {self.x0} \\n\" f\"* endpoint: {self.x} \\n\" ) # add fval,",
"residual sensitivities at `x`. n_fval Number of function evaluations. n_grad: Number of gradient",
"hess is not None else None self.res: np.ndarray = np.array(res) if res is",
"standardized return value to map from the individual result objects returned by the",
"\"### Optimizer Result \\n\\n\" f\"* optimizer used: {self.optimizer} \\n\" f\"* message: {self.message} \\n\"",
"np.array(x0) if x0 is not None else None self.fval0: float = fval0 self.history:",
"residual sensitivity: {self.sres} \\n\" return message def update_to_full(self, problem: Problem) -> None: \"\"\"",
"key as a list.\"\"\" warnings.warn( \"get_for_key() is deprecated in favour of \" \"optimize_result['key']",
"{self.hess} \\n\" if self.res is not None: message += f\"* final residual value:",
"= exitflag self.time: float = time self.message: str = message self.optimizer = optimizer",
"id: str = None, x: np.ndarray = None, fval: float = None, grad:",
"we only sort once when appending an optimize_result. prefix: The IDs for all",
"= np.array(res) if res is not None else None self.sres: np.ndarray = np.array(sres)",
"value, `fun(x0)`. history: Objective history. exitflag: The exitflag of the optimizer. time: Execution",
"vectors or matrices \"\"\" self.x = problem.get_full_vector(self.x, problem.x_fixed_vals) self.grad = problem.get_full_vector(self.grad) self.hess =",
"execution time: {np.max(self.time)}s,' f'\\tid={self[np.argmax(self.time)].id}\\n' f'\\tMinimum execution time: {np.min(self.time)}s,\\t' f'id={self[np.argmin(self.time)].id}' ) summary = (",
"'', ): \"\"\" Append an OptimizerResult or an OptimizeResult to the result object.",
"---------- optimize_result: The result of one or more (local) optimizer run. sort: Boolean",
"f\"* final residual value: {self.res} \\n\" if self.sres is not None: message +=",
"Sequence, Union import numpy as np import pandas as pd from ..objective import",
"f\"* execution time summary: {times_message}\\n\" f\"* summary of optimizer messages:\\n{counter_message}\\n\" f\"* best value",
"# if id is None, append without checking for duplicate ids if optimize_result.id",
"{self.n_fval} \\n\" f\"* time taken to optimize: {self.time} \\n\" f\"* startpoint: {self.x0} \\n\"",
"def summary(self): \"\"\"Get summary of the object.\"\"\" # perform clustering for better information",
"self.x0 = problem.get_full_vector(self.x0, problem.x_fixed_vals) class OptimizeResult: \"\"\"Result of the :py:func:`pypesto.optimize.minimize` function.\"\"\" def __init__(self):",
"list(str), optional Labels of the field to extract. \"\"\" lst = self.list if",
"typing import Sequence, Union import numpy as np import pandas as pd from",
"): \"\"\" Append an OptimizerResult or an OptimizeResult to the result object. Parameters",
"result of an optimizer run. Used as a standardized return value to map",
"sum(clustsize == 1)} \\n\" f\"* best value: {self[0]['fval']}, \" f\"worst value: {self[-1]['fval']} \\n\\n\"",
"gradient value: {self.grad} \\n\" if self.hess is not None: message += f\"* final",
"the object.\"\"\" # perform clustering for better information clust, clustsize = assign_clusters(delete_nan_inf(self.fval)[1]) counter_message",
"for optimizer_result in optimize_result.list: self.append(optimizer_result, sort=False, prefix=prefix) elif isinstance(optimize_result, OptimizerResult): # if id",
"import History from ..problem import Problem from ..util import assign_clusters, delete_nan_inf OptimizationResult =",
"summary of optimizer messages:\\n{counter_message}\\n\" f\"* best value found (approximately) {clustsize[0]} time(s) \\n\" f\"*",
"OptimizerResult): # if id is None, append without checking for duplicate ids if",
"n_res self.n_sres: int = n_sres self.x0: np.ndarray = np.array(x0) if x0 is not",
"is not None else None self.fval0: float = fval0 self.history: History = history",
"self.time: float = time self.message: str = message self.optimizer = optimizer def __getattr__(self,",
"IDs for all appended results will be prefixed with this. \"\"\" current_ids =",
"None: message += f\"* final residual sensitivity: {self.sres} \\n\" return message def update_to_full(self,"
] |
[
"sess: filename = ['A.jpg', 'B.jpg', 'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5)",
"num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader = tf.WholeFileReader() key, value = reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run()",
"tf.Session() as sess: filename = ['A.jpg', 'B.jpg', 'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue = tf.train.string_input_producer(filename,",
"tf.WholeFileReader() key, value = reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads = tf.train.start_queue_runners(sess=sess)",
"reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads = tf.train.start_queue_runners(sess=sess) i = 0 while",
"as sess: filename = ['A.jpg', 'B.jpg', 'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue = tf.train.string_input_producer(filename, shuffle=False,",
"key, value = reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads = tf.train.start_queue_runners(sess=sess) i",
"filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader = tf.WholeFileReader() key, value =",
"import tensorflow as tf if not os.path.exists('example_pic'): os.makedirs('example_pic/') with tf.Session() as sess: filename",
"reader = tf.WholeFileReader() key, value = reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads",
"import os import tensorflow as tf if not os.path.exists('example_pic'): os.makedirs('example_pic/') with tf.Session() as",
"-*- import os import tensorflow as tf if not os.path.exists('example_pic'): os.makedirs('example_pic/') with tf.Session()",
"= tf.train.string_input_producer(filename, shuffle=False, num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader = tf.WholeFileReader() key, value = reader.read(filename_queue)",
"i = 0 while True: i += 1 image_data = sess.run(value) with open('example_pic/test_%d.jpg'",
"image_data = sess.run(value) with open('example_pic/test_%d.jpg' % i, 'wb') as f: f.write(image_data) # 程序最后会抛出一个OutOfRangeError,这是epoch跑完,队列关闭的标志",
"0 while True: i += 1 image_data = sess.run(value) with open('example_pic/test_%d.jpg' % i,",
"filename = ['A.jpg', 'B.jpg', 'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5) #",
"# 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads = tf.train.start_queue_runners(sess=sess) i = 0 while True: i += 1",
"threads = tf.train.start_queue_runners(sess=sess) i = 0 while True: i += 1 image_data =",
"-*- coding: utf-8 -*- import os import tensorflow as tf if not os.path.exists('example_pic'):",
"string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader = tf.WholeFileReader() key, value",
"os.makedirs('example_pic/') with tf.Session() as sess: filename = ['A.jpg', 'B.jpg', 'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue",
"= tf.train.start_queue_runners(sess=sess) i = 0 while True: i += 1 image_data = sess.run(value)",
"使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads = tf.train.start_queue_runners(sess=sess) i = 0 while True: i += 1 image_data",
"tf.train.start_queue_runners(sess=sess) i = 0 while True: i += 1 image_data = sess.run(value) with",
"= 0 while True: i += 1 image_data = sess.run(value) with open('example_pic/test_%d.jpg' %",
"= ['A.jpg', 'B.jpg', 'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value)",
"utf-8 -*- import os import tensorflow as tf if not os.path.exists('example_pic'): os.makedirs('example_pic/') with",
"value = reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads = tf.train.start_queue_runners(sess=sess) i =",
"tf if not os.path.exists('example_pic'): os.makedirs('example_pic/') with tf.Session() as sess: filename = ['A.jpg', 'B.jpg',",
"'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader = tf.WholeFileReader()",
"#!/usr/bin/python # -*- coding: utf-8 -*- import os import tensorflow as tf if",
"<filename>lecture_dl_21_examples/002_cifar10/01_dataset_test.py<gh_stars>1-10 #!/usr/bin/python # -*- coding: utf-8 -*- import os import tensorflow as tf",
"coding: utf-8 -*- import os import tensorflow as tf if not os.path.exists('example_pic'): os.makedirs('example_pic/')",
"+= 1 image_data = sess.run(value) with open('example_pic/test_%d.jpg' % i, 'wb') as f: f.write(image_data)",
"with tf.Session() as sess: filename = ['A.jpg', 'B.jpg', 'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue =",
"shuffle=False, num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader = tf.WholeFileReader() key, value = reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化",
"['A.jpg', 'B.jpg', 'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader",
"# reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader = tf.WholeFileReader() key, value = reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() #",
"tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads = tf.train.start_queue_runners(sess=sess) i = 0 while True: i +=",
"# tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads = tf.train.start_queue_runners(sess=sess) i = 0 while True:",
"i += 1 image_data = sess.run(value) with open('example_pic/test_%d.jpg' % i, 'wb') as f:",
"# -*- coding: utf-8 -*- import os import tensorflow as tf if not",
"tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads = tf.train.start_queue_runners(sess=sess) i = 0 while True: i",
"if not os.path.exists('example_pic'): os.makedirs('example_pic/') with tf.Session() as sess: filename = ['A.jpg', 'B.jpg', 'C.jpg']",
"tensorflow as tf if not os.path.exists('example_pic'): os.makedirs('example_pic/') with tf.Session() as sess: filename =",
"os.path.exists('example_pic'): os.makedirs('example_pic/') with tf.Session() as sess: filename = ['A.jpg', 'B.jpg', 'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期",
"# string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader = tf.WholeFileReader() key,",
"not os.path.exists('example_pic'): os.makedirs('example_pic/') with tf.Session() as sess: filename = ['A.jpg', 'B.jpg', 'C.jpg'] #",
"True: i += 1 image_data = sess.run(value) with open('example_pic/test_%d.jpg' % i, 'wb') as",
"1 image_data = sess.run(value) with open('example_pic/test_%d.jpg' % i, 'wb') as f: f.write(image_data) #",
"= tf.WholeFileReader() key, value = reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads =",
"os import tensorflow as tf if not os.path.exists('example_pic'): os.makedirs('example_pic/') with tf.Session() as sess:",
"as tf if not os.path.exists('example_pic'): os.makedirs('example_pic/') with tf.Session() as sess: filename = ['A.jpg',",
"tf.train.string_input_producer(filename, shuffle=False, num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader = tf.WholeFileReader() key, value = reader.read(filename_queue) #",
"reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader = tf.WholeFileReader() key, value = reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列",
"'B.jpg', 'C.jpg'] # string_input_producer会产生一个文件名队列,shuffle=False不打乱数据顺序,num_epochs训练周期 filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5) # reader从文件名队列中读数据,对应的方法是reader.read--输出文件名(key)和该文件内容(value) reader =",
"while True: i += 1 image_data = sess.run(value) with open('example_pic/test_%d.jpg' % i, 'wb')",
"= reader.read(filename_queue) # tf.train.string_input_producer定义了一个epoch变量(num_epochs不为None),要对它进行初始化 tf.local_variables_initializer().run() # 使用start_queue_runners之后,才会真正把tensor推入到文件名队列 threads = tf.train.start_queue_runners(sess=sess) i = 0"
] |
[
"0b0), 0) self.assertEqual(count_unequal_bits(0b1, 0b1), 0) self.assertEqual(count_unequal_bits(0b01, 0b10), 2) self.assertEqual(count_unequal_bits(0b001, 0b110), 3) if __name__",
"tests for q0505.py.\"\"\" import unittest from src.q0505 import count_unequal_bits class TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self):",
"unittest from src.q0505 import count_unequal_bits class TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits, -1, 1)",
"def test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits, -1, 1) self.assertEqual(count_unequal_bits(0b0, 0b0), 0) self.assertEqual(count_unequal_bits(0b1, 0b1), 0) self.assertEqual(count_unequal_bits(0b01,",
"count_unequal_bits class TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits, -1, 1) self.assertEqual(count_unequal_bits(0b0, 0b0), 0) self.assertEqual(count_unequal_bits(0b1,",
"from src.q0505 import count_unequal_bits class TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits, -1, 1) self.assertEqual(count_unequal_bits(0b0,",
"src.q0505 import count_unequal_bits class TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits, -1, 1) self.assertEqual(count_unequal_bits(0b0, 0b0),",
"for q0505.py.\"\"\" import unittest from src.q0505 import count_unequal_bits class TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self): self.assertRaises(ValueError,",
"0) self.assertEqual(count_unequal_bits(0b1, 0b1), 0) self.assertEqual(count_unequal_bits(0b01, 0b10), 2) self.assertEqual(count_unequal_bits(0b001, 0b110), 3) if __name__ ==",
"0b1), 0) self.assertEqual(count_unequal_bits(0b01, 0b10), 2) self.assertEqual(count_unequal_bits(0b001, 0b110), 3) if __name__ == '__main__': unittest.main()",
"-1, 1) self.assertEqual(count_unequal_bits(0b0, 0b0), 0) self.assertEqual(count_unequal_bits(0b1, 0b1), 0) self.assertEqual(count_unequal_bits(0b01, 0b10), 2) self.assertEqual(count_unequal_bits(0b001, 0b110),",
"self.assertRaises(ValueError, count_unequal_bits, -1, 1) self.assertEqual(count_unequal_bits(0b0, 0b0), 0) self.assertEqual(count_unequal_bits(0b1, 0b1), 0) self.assertEqual(count_unequal_bits(0b01, 0b10), 2)",
"import unittest from src.q0505 import count_unequal_bits class TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits, -1,",
"<filename>tests/test_q0505.py \"\"\"Unit tests for q0505.py.\"\"\" import unittest from src.q0505 import count_unequal_bits class TestCountUnequalBits(unittest.TestCase):",
"class TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits, -1, 1) self.assertEqual(count_unequal_bits(0b0, 0b0), 0) self.assertEqual(count_unequal_bits(0b1, 0b1),",
"q0505.py.\"\"\" import unittest from src.q0505 import count_unequal_bits class TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits,",
"count_unequal_bits, -1, 1) self.assertEqual(count_unequal_bits(0b0, 0b0), 0) self.assertEqual(count_unequal_bits(0b1, 0b1), 0) self.assertEqual(count_unequal_bits(0b01, 0b10), 2) self.assertEqual(count_unequal_bits(0b001,",
"self.assertEqual(count_unequal_bits(0b0, 0b0), 0) self.assertEqual(count_unequal_bits(0b1, 0b1), 0) self.assertEqual(count_unequal_bits(0b01, 0b10), 2) self.assertEqual(count_unequal_bits(0b001, 0b110), 3) if",
"test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits, -1, 1) self.assertEqual(count_unequal_bits(0b0, 0b0), 0) self.assertEqual(count_unequal_bits(0b1, 0b1), 0) self.assertEqual(count_unequal_bits(0b01, 0b10),",
"1) self.assertEqual(count_unequal_bits(0b0, 0b0), 0) self.assertEqual(count_unequal_bits(0b1, 0b1), 0) self.assertEqual(count_unequal_bits(0b01, 0b10), 2) self.assertEqual(count_unequal_bits(0b001, 0b110), 3)",
"\"\"\"Unit tests for q0505.py.\"\"\" import unittest from src.q0505 import count_unequal_bits class TestCountUnequalBits(unittest.TestCase): def",
"import count_unequal_bits class TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits, -1, 1) self.assertEqual(count_unequal_bits(0b0, 0b0), 0)",
"TestCountUnequalBits(unittest.TestCase): def test_count_unequal_bits(self): self.assertRaises(ValueError, count_unequal_bits, -1, 1) self.assertEqual(count_unequal_bits(0b0, 0b0), 0) self.assertEqual(count_unequal_bits(0b1, 0b1), 0)",
"self.assertEqual(count_unequal_bits(0b1, 0b1), 0) self.assertEqual(count_unequal_bits(0b01, 0b10), 2) self.assertEqual(count_unequal_bits(0b001, 0b110), 3) if __name__ == '__main__':"
] |
[
"of this comparison will be truePositives(B) and falsePositives(B) (this is falsePosMode). \"\"\" hpTests",
"%9s, %9s, %9s, %9s' % ('dataset', 'Precision', 'Recall', 'F-score', 'TP (A)', 'TP (B)',",
"+ 'B', True) falsePosSelf = getItem(pairs, 'falsePos' + suffix, True) falseNegSelf = getItem(pairs,",
"+ self.falsePos) if (self.truePosRegionB + self.falsePosRegion) == 0: self.precisionRegion = float('nan') else: self.precisionRegion",
"print('') sortedPairs = sorted(pairs, key = lambda x: pairs[x].niceNames) for pair in sortedPairs:",
"+= int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed file established regions p.truePosRegionA",
"truePosSelfA), (obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut),",
"walks the tree to add data to the pairs dict. falsePosMode vs truePosMode:",
"%9s, %9s, %9s, %9s' % ('Overall (w/o self) inside', precision, recall, 2 *",
"fStr = 'nan' else: precStr = '%.5f' % p.precision fStr = '%.5f' %",
"+ recall), truePosA, truePosB, falsePos, falseNeg) print '%35s, %10s, %10s, %10s, %9s, %9s,",
"%10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self)', precisionSelf, recallSelf, 2 *",
"print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % ('%s inside' % p.niceNames,",
"else: precRegOutStr = '%.5f' % p.precisionRegionOutside fRegOutStr = '%.5f' % (2 * ((p.precisionRegionOutside",
"suffix + 'A', False) truePosB = getItem(pairs, 'truePos' + suffix + 'B', False)",
"falseNegSelfOut) else: suffix = '' truePosA = getItem(pairs, 'truePos' + suffix + 'A',",
"'truePos' + suffix + 'B', True) falsePosSelf = getItem(pairs, 'falsePos' + suffix, True)",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR",
"not None) assert(speciesB is not None) self.species = set([speciesA, speciesB]) self.truePosA = 0",
"(seqB, seqA)] return None def reportPairs(pairs, options): print('') sortedPairs = sorted(pairs, key =",
"%10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self) outside', precisionSelfOut, recallSelfOut, 2",
"('Overall (w/ self) outside', precisionSelfOut, recallSelfOut, 2 * ((precisionSelfOut * recallSelfOut) / (precisionSelfOut",
"contained in file stored in options.xml \"\"\" try: tree = ET.parse(options.xml) except xml.parsers.expat.ExpatError:",
"tests = hpTests.findall('homologyTest') for t in tests: seqA = t.attrib['sequenceA'].split('.')[0] seqB = t.attrib['sequenceB'].split('.')[0]",
"%9s' % ('Overall (w/o self) inside', precision, recall, 2 * (precision * recall)",
"recall = float(truePosA) / (truePosA + falseNeg) if (truePosSelfB + falsePosSelf) == 0:",
"not exist' % options.xml) def addPairData(pairs, homTests, falsePosMode = False): \"\"\" given the",
"= t.attrib['sequenceA'].split('.')[0] seqB = t.attrib['sequenceB'].split('.')[0] if seqA == 'self' or seqB == 'self':",
"obsFalsePosOut = 0 obsFalseNegOut = 0 obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf",
"the results of this comparison will be truePositives(A) and falseNegatives(A). the second homology",
"B->A self.falsePosRegion = 0 self.falseNegRegion = 0 self.truePosRegionOutsideA = 0 # wrt A->B",
"falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut,",
"pairs[pair] p.calcRecall() p.calcPrecision() if p.precision == -1.0 or (p.precision + p.recall) == 0:",
"(w/ self)', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) / (precisionSelf + recallSelf)),",
"+ self.falsePosRegionOutside) == 0: self.precisionRegionOutside = float('nan') else: self.precisionRegionOutside = (float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB",
"p.falseNegRegionOutside else: obsTruePosA += p.truePosRegionA obsTruePosB += p.truePosRegionB obsFalsePos += p.falsePosRegion obsFalseNeg +=",
"to permit persons to whom the Software is # furnished to do so,",
"Copyright (C) 2009-2011 by # <NAME> (<EMAIL>, <EMAIL>) # ... and other members",
"+ suffix, True) if (truePosB + falsePos) == 0: precision = float('nan') else:",
"p.truePosRegionOutsideA obsTruePosOutB += p.truePosRegionOutsideB obsFalsePosOut += p.falsePosRegionOutside obsFalseNegOut += p.falseNegRegionOutside obsTruePosASelf += obsTruePosA",
"if seqA == seqB: pass # do not compare a genome to itself",
"pairs): # Check to see if the pair (seqA, seqB) is stored in",
"= getItem(pairs, 'truePosRegionOutsideA', True) truePosSelfOutB = getItem(pairs, 'truePosRegionOutsideB', True) falsePosSelfOut = getItem(pairs, 'falsePosRegionOutside',",
"+ suffix, False) truePosSelfA = getItem(pairs, 'truePos' + suffix + 'A', True) truePosSelfB",
"falseNegSelfOut) else: sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, pairs, options) print",
"truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options) print '%35s, %10s, %10s,",
"> 0 or p.truePosRegionB > 0 or p.falsePosRegion > 0 or p.falseNegRegion >",
"obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 for pair in pairs:",
"self.truePosA = 0 # with respect to the A->B comparison self.truePosB = 0",
"part of the xml tree `homTests', addPairData() walks the tree to add data",
"and this permission notice shall be included in # all copies or substantial",
"+= int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed file established regions p.truePosRegionB",
"0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 obsTruePosASelfOut = 0 obsTruePosBSelfOut = 0",
"else: suffix = '' truePosA = getItem(pairs, 'truePos' + suffix + 'A', False)",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION",
"(truePosSelfB + falsePosSelf) if (truePosSelfA + falseNegSelf) == 0: recallSelf = float('nan') else:",
"aggregate sequences continue p = findPair(seqA, seqB, pairs) if p is None: p",
"self) inside', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) / (precisionSelf + recallSelf)),",
"compare a genome to itself # continue if t.attrib['sequenceA'] == 'aggregate' or t.attrib['sequenceB']",
"names = list(self.species) names = sorted(names, key = lambda x: x[3:]) # ignore",
"'truePos' + suffix + 'A', True) truePosSelfB = getItem(pairs, 'truePos' + suffix +",
"in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosOutA, truePosOutA), (obsTruePosOutB, truePosOutB),",
"+= obsTruePosOutA obsTruePosBSelfOut += obsTruePosOutB obsFalsePosSelfOut += obsFalsePosOut obsFalseNegSelfOut += obsFalseNegOut for obs,",
"falsePosMode = False): \"\"\" given the dict `pairs' and a part of the",
"if (self.truePosRegionOutsideB + self.falsePosRegionOutside) == 0: self.precisionRegionOutside = float('nan') else: self.precisionRegionOutside = (float(self.truePosRegionOutsideB)",
"hpTests = homTests.find('homologyPairTests') tests = hpTests.findall('homologyTest') for t in tests: seqA = t.attrib['sequenceA'].split('.')[0]",
"obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 for",
"second homology test in the mC output is B->A and the results of",
"dict. falsePosMode vs truePosMode: the first homology test in the mafComparator output is",
"falseNegSelfOut, pairs, options) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' %",
"p.recall) == 0: precStr = 'nan' fStr = 'nan' else: precStr = '%.5f'",
"(seqA, seqB) in pairs: # if '%s-%s' % (seqB, seqA) in pairs: #",
"isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf,",
"findPair(seqA, seqB, pairs) if p is None: p = ComparisonPair(seqA, seqB) pairs['%s-%s' %",
"% ('Overall (w/ self) outside', precisionSelfOut, recallSelfOut, 2 * ((precisionSelfOut * recallSelfOut) /",
"p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside)) def summarize(options): \"\"\" summarize() summizes the information contained in",
"= 0 # region numbers are for comparisons using .bed files self.truePosRegionA =",
"pairs: # raise RuntimeError('Duplicate pair found in `pairs\\' dict: %s-%s' % (seqA, seqB))",
"self.falsePos) == 0: self.precision = float('nan') else: self.precision = float(self.truePosB) / (self.truePosB +",
"falsePosSelf = getItem(pairs, 'falsePos' + suffix, True) falseNegSelf = getItem(pairs, 'falseNeg' + suffix,",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN",
"'truePosRegionOutsideB', True) falsePosSelfOut = getItem(pairs, 'falsePosRegionOutside', True) falseNegSelfOut = getItem(pairs, 'falseNegRegionOutside', True) precisionOut",
"exist' % options.xml) def addPairData(pairs, homTests, falsePosMode = False): \"\"\" given the dict",
"= 0 # wrt B->A self.falsePosRegionOutside = 0 self.falseNegRegionOutside = 0 self.precision =",
"(seqB, seqA) in pairs: # if '%s-%s' % (seqA, seqB) in pairs: #",
"float('nan') else: self.precision = float(self.truePosB) / (self.truePosB + self.falsePos) if (self.truePosRegionB + self.falsePosRegion)",
"= 'xml', help = 'location of mafComparator output xml to summarize.') def checkOptions(options,",
"CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"= 0 obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf =",
"outside' % p.niceNames, precRegOutStr, p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside)) def summarize(options): \"\"\"",
"parser.add_option('--xml', dest = 'xml', help = 'location of mafComparator output xml to summarize.')",
"== 0: self.recallRegion = float('nan') else: self.recallRegion = float(self.truePosRegionA) / (self.truePosRegionA + self.falseNegRegion)",
"%9d' % ('%s outside' % p.niceNames, precRegOutStr, p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside))",
"in file stored in options.xml \"\"\" try: tree = ET.parse(options.xml) except xml.parsers.expat.ExpatError: raise",
"obsFalseNegSelf = 0 obsTruePosASelfOut = 0 obsTruePosBSelfOut = 0 obsFalsePosSelfOut = 0 obsFalseNegSelfOut",
"('%s inside' % p.niceNames, precRegStr, p.recallRegion, fRegStr, p.truePosRegionA, p.truePosRegionB, p.falsePosRegion, p.falseNegRegion)) print('%35s %10s",
"getItem(pairs, 'truePos' + suffix + 'A', True) truePosSelfB = getItem(pairs, 'truePos' + suffix",
"def sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosASelf, truePosBSelf, falsePosSelf, falseNegSelf, pairs, options): # Each",
"obsFalseNeg for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg),",
"'Region' truePosOutA = getItem(pairs, 'truePosRegionOutsideA', False) truePosOutB = getItem(pairs, 'truePosRegionOutsideB', False) falseNegOut =",
"else: sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, pairs, options) print '%35s,",
"(float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB + self.falsePosRegionOutside)) def calcRecall(self): # Recall is calculated as #",
"+ 'A', True) truePosSelfB = getItem(pairs, 'truePos' + suffix + 'B', True) falsePosSelf",
"DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"self.falsePosRegionOutside = 0 self.falseNegRegionOutside = 0 self.precision = None self.recall = None self.precisionRegion",
"self.truePosRegionA = 0 # wrt A->B self.truePosRegionB = 0 # wrt B->A self.falsePosRegion",
"is not None: # bed file established regions p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion +=",
"p.recallRegion) == 0: precRegStr = 'nan' fRegStr = 'nan' else: precRegStr = '%.5f'",
"should be the sum of # the numbers contained in the column corresponding",
"be truePositives(B) and falsePositives(B) (this is falsePosMode). \"\"\" hpTests = homTests.find('homologyPairTests') tests =",
"p.__dict__[item] return ans def main(): usage = ('usage: %prog \\n\\n' '%prog \\n') parser",
"to a region \"\"\" for pair in pairs: p = pairs[pair] if p.truePosRegionA",
"B->A comparison self.falsePos = 0 self.falseNeg = 0 # region numbers are for",
"seqB) in pairs: # raise RuntimeError('Duplicate pair found in `pairs\\' dict: %s-%s' %",
"obsFalsePosSelf = 0 obsFalseNegSelf = 0 for pair in pairs: p = pairs[pair]",
"fRegStr = '%.5f' % (2 * ((p.precisionRegion * p.recallRegion)/ (p.precisionRegion + p.recallRegion))) if",
"NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"pairs: p = pairs[pair] if not alignSelf: if len(p.species) == 1: continue ans",
"software and associated documentation files (the \"Software\"), to deal # in the Software",
"will be truePositives(B) and falsePositives(B) (this is falsePosMode). \"\"\" hpTests = homTests.find('homologyPairTests') tests",
"mafComparator output is A->B and the results of this comparison will be truePositives(A)",
"True def getItem(pairs, item, alignSelf): ans = 0 for pair in pairs: p",
"== 0: self.recall = float('nan') else: self.recall = float(self.truePosA) / (self.truePosA + self.falseNeg)",
"(obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),]: assert(obs == exp) def isRegionMode(pairs): \"\"\" Detects",
"(self.truePosB + self.falsePos) if (self.truePosRegionB + self.falsePosRegion) == 0: self.precisionRegion = float('nan') else:",
"False) truePosSelfA = getItem(pairs, 'truePos' + suffix + 'A', True) truePosSelfB = getItem(pairs,",
"'%s-%s' % (seqB, seqA) in pairs: # raise RuntimeError('Duplicate pair found in `pairs\\'",
"pairs = {} addPairData(pairs, homTests[0]) addPairData(pairs, homTests[1], falsePosMode = True) if isRegionMode(pairs): #",
"= 'self-%s' % names[0] def calcPrecision(self): # Precision is calculated as # TP_B",
"p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed",
"this comparison will be truePositives(A) and falseNegatives(A). the second homology test in the",
"* p.recall)/ (p.precision + p.recall))) if p.precisionRegion == -1.0 or (p.precisionRegion + p.recallRegion)",
"# lab (BME Dept. UCSC) # # Permission is hereby granted, free of",
"and to permit persons to whom the Software is # furnished to do",
"float(self.truePosB) / (self.truePosB + self.falsePos) if (self.truePosRegionB + self.falsePosRegion) == 0: self.precisionRegion =",
"(truePosB + falsePos) == 0: precision = float('nan') else: precision = float(truePosB) /",
"here for convenience ################################################## # Copyright (C) 2009-2011 by # <NAME> (<EMAIL>, <EMAIL>)",
"comparisons using .bed files self.truePosRegionA = 0 # wrt A->B self.truePosRegionB = 0",
"0 # wrt A->B self.truePosRegionB = 0 # wrt B->A self.falsePosRegion = 0",
"float(self.truePosA) / (self.truePosA + self.falseNeg) if (self.truePosRegionA + self.falseNegRegion) == 0: self.recallRegion =",
"in `pairs\\' dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqA, seqB)] if",
"# furnished to do so, subject to the following conditions: # # The",
"the Software, and to permit persons to whom the Software is # furnished",
"falsePosSelf) if (truePosSelfA + falseNegSelf) == 0: recallSelf = float('nan') else: recallSelf =",
"+ falsePosSelfOut) recallSelfOut = float(truePosSelfOutA) / (truePosSelfOutA + falseNegSelfOut) else: suffix = ''",
"seqB = t.attrib['sequenceB'].split('.')[0] if seqA == 'self' or seqB == 'self': continue if",
"\"\"\" given the dict `pairs' and a part of the xml tree `homTests',",
"t.attrib['sequenceA'] == 'aggregate' or t.attrib['sequenceB'] == 'aggregate': # ignore the aggregate sequences continue",
"if t.find('aggregateResults').find('both') is not None: # bed file established regions p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue'])",
"falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options) print '%35s,",
"self.niceNames = '-'.join(names) if len(names) == 1: self.niceNames = 'self-%s' % names[0] def",
"= 0 obsFalseNeg = 0 obsTruePosOutA = 0 obsTruePosOutB = 0 obsFalsePosOut =",
"0: self.precision = float('nan') else: self.precision = float(self.truePosB) / (self.truePosB + self.falsePos) if",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"+= p.falsePosRegion obsFalseNegSelf += p.falseNegRegion obsTruePosASelfOut += p.truePosRegionOutsideA obsTruePosBSelfOut += p.truePosRegionOutsideB obsFalsePosSelfOut +=",
"+ falseNeg) == 0: recall = float('nan') else: recall = float(truePosA) / (truePosA",
"self.precisionRegion = None self.recallRegion = None self.precisionRegionOutside = None self.recallRegionOutside = None names",
"0 for pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosRegionA",
"# TP_B / (TP_B + FP) # We use the TP_B since FP",
"in options.xml \"\"\" try: tree = ET.parse(options.xml) except xml.parsers.expat.ExpatError: raise RuntimeError('Input xml, %s",
"fRegStr = 'nan' else: precRegStr = '%.5f' % p.precisionRegion fRegStr = '%.5f' %",
"+= int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA, seqB, pairs): #",
"falseNegSelfOut = getItem(pairs, 'falseNegRegionOutside', True) precisionOut = float(truePosOutB) / (truePosOutB + falsePosOut) recallOut",
"0 obsFalseNeg = 0 obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf = 0",
"self.falseNeg) if (self.truePosRegionA + self.falseNegRegion) == 0: self.recallRegion = float('nan') else: self.recallRegion =",
"\"outside\" status. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg =",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"the xml tree `homTests', addPairData() walks the tree to add data to the",
"%10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self) inside', precision,",
"UCSC) # # Permission is hereby granted, free of charge, to any person",
"obsTruePosBSelf += p.truePosRegionB obsFalsePosSelf += p.falsePosRegion obsFalseNegSelf += p.falseNegRegion obsTruePosASelfOut += p.truePosRegionOutsideA obsTruePosBSelfOut",
"obsTruePosOutB = 0 obsFalsePosOut = 0 obsFalseNegOut = 0 obsTruePosASelf = 0 obsTruePosBSelf",
"for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosASelf,",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT",
"None) self.species = set([speciesA, speciesB]) self.truePosA = 0 # with respect to the",
"+= int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: # the first homology",
"%9d %9d %9d %9d' % ('%s inside' % p.niceNames, precRegStr, p.recallRegion, fRegStr, p.truePosRegionA,",
"if seqA == 'self' or seqB == 'self': continue if seqA == seqB:",
"ignore the aggregate sequences continue p = findPair(seqA, seqB, pairs) if p is",
"'self': continue if seqA == seqB: pass # do not compare a genome",
"= 0 obsFalseNegOut = 0 obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf =",
"if (self.truePosB + self.falsePos) == 0: self.precision = float('nan') else: self.precision = float(self.truePosB)",
"0: recall = float('nan') else: recall = float(truePosA) / (truePosA + falseNeg) if",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"(TP_A + FN) # We use the TP_A since FN comes from the",
"obsFalseNegOut += p.falseNegRegionOutside obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf",
"if (truePosSelfA + falseNegSelf) == 0: recallSelf = float('nan') else: recallSelf = float(truePosSelfA)",
"falsePosSelfOut) recallSelfOut = float(truePosSelfOutA) / (truePosSelfOutA + falseNegSelfOut) else: suffix = '' truePosA",
"%10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self) outside', precisionOut, recallOut,",
"0 or p.truePosRegionB > 0 or p.falsePosRegion > 0 or p.falseNegRegion > 0:",
"to deal # in the Software without restriction, including without limitation the rights",
"to any person obtaining a copy # of this software and associated documentation",
"the column. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg =",
"= float('nan') else: recallSelf = float(truePosSelfA) / (truePosSelfA + falseNegSelf) print '%35s, %10s,",
"if '%s-%s' % (seqB, seqA) in pairs: # if '%s-%s' % (seqA, seqB)",
"(precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) reportPairs(pairs, options) def sanityCheckRegionMode(truePosA, truePosB, falsePos,",
"0: precStr = 'nan' fStr = 'nan' else: precStr = '%.5f' % p.precision",
"if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosA obsTruePosBSelf += p.truePosB obsFalsePosSelf += p.falsePos obsFalseNegSelf +=",
"None: # bed file established regions p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #",
"members of the Reconstruction Team of <NAME>'s # lab (BME Dept. UCSC) #",
"DEALINGS IN # THE SOFTWARE. ################################################## import xml.etree.ElementTree as ET import xml.parsers.expat from",
"else: self.recall = float(self.truePosA) / (self.truePosA + self.falseNeg) if (self.truePosRegionA + self.falseNegRegion) ==",
"for t in tests: seqA = t.attrib['sequenceA'].split('.')[0] seqB = t.attrib['sequenceB'].split('.')[0] if seqA ==",
"/ (truePosSelfOutB + falsePosSelfOut) recallSelfOut = float(truePosSelfOutA) / (truePosSelfOutA + falseNegSelfOut) else: suffix",
"(self.truePosB + self.falsePos) == 0: self.precision = float('nan') else: self.precision = float(self.truePosB) /",
"True) falsePosSelfOut = getItem(pairs, 'falsePosRegionOutside', True) falseNegSelfOut = getItem(pairs, 'falseNegRegionOutside', True) precisionOut =",
"for pair in pairs: p = pairs[pair] if not alignSelf: if len(p.species) ==",
"Actually belongs to https://github.com/dentearl/mwgAlignAnalysis # but was moved in here for convenience ##################################################",
"truePositives(A) and falseNegatives(A). the second homology test in the mC output is B->A",
"+= p.falseNegRegion obsTruePosOutA += p.truePosRegionOutsideA obsTruePosOutB += p.truePosRegionOutsideB obsFalsePosOut += p.falsePosRegionOutside obsFalseNegOut +=",
"+= obsTruePosOutB obsFalsePosSelfOut += obsFalsePosOut obsFalseNegSelfOut += obsFalseNegOut for obs, exp in [(obsTruePosA,",
"not compare a genome to itself # continue if t.attrib['sequenceA'] == 'aggregate' or",
"pairs[x].niceNames) for pair in sortedPairs: p = pairs[pair] p.calcRecall() p.calcPrecision() if p.precision ==",
"else: recall = float(truePosA) / (truePosA + falseNeg) if (truePosSelfB + falsePosSelf) ==",
"else: precStr = '%.5f' % p.precision fStr = '%.5f' % (2 * ((p.precision",
"output is B->A and the results of this comparison will be truePositives(B) and",
"seqB, pairs) if p is None: p = ComparisonPair(seqA, seqB) pairs['%s-%s' % (seqA,",
"summarize output of mafComparator for use with alignathon competetition. \"\"\" # Note: Actually",
"xml.parsers.expat.ExpatError: raise RuntimeError('Input xml, %s is not a well formed xml document.' %",
"= getItem(pairs, 'falsePos' + suffix, True) falseNegSelf = getItem(pairs, 'falseNeg' + suffix, True)",
"suffix = 'Region' truePosOutA = getItem(pairs, 'truePosRegionOutsideA', False) truePosOutB = getItem(pairs, 'truePosRegionOutsideB', False)",
"in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosASelf, truePosASelf), (obsTruePosBSelf, truePosBSelf),",
"addPairData(pairs, homTests, falsePosMode = False): \"\"\" given the dict `pairs' and a part",
"this software and associated documentation files (the \"Software\"), to deal # in the",
"t in tests: seqA = t.attrib['sequenceA'].split('.')[0] seqB = t.attrib['sequenceB'].split('.')[0] if seqA == 'self'",
"p.truePosA obsTruePosB += p.truePosB obsFalsePos += p.falsePos obsFalseNeg += p.falseNeg obsTruePosASelf += obsTruePosA",
"the pairs dict. falsePosMode vs truePosMode: the first homology test in the mafComparator",
"obsFalseNegSelf += obsFalseNeg for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos),",
"= '%.5f' % p.precisionRegionOutside fRegOutStr = '%.5f' % (2 * ((p.precisionRegionOutside * p.recallRegionOutside)/",
"(obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut), ]: assert(obs == exp) def sanityCheck(truePosA, truePosB, falsePos, falseNeg,",
"\"\"\" for pair in pairs: p = pairs[pair] if p.truePosRegionA > 0 or",
"or (p.precision + p.recall) == 0: precStr = 'nan' fStr = 'nan' else:",
"granted, free of charge, to any person obtaining a copy # of this",
"x[3:]) # ignore the \"sim\" part of the name self.niceNames = '-'.join(names) if",
"getItem(pairs, 'truePosRegionOutsideA', True) truePosSelfOutB = getItem(pairs, 'truePosRegionOutsideB', True) falsePosSelfOut = getItem(pairs, 'falsePosRegionOutside', True)",
"obsFalseNegSelf = 0 for pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf",
"the Reconstruction Team of <NAME>'s # lab (BME Dept. UCSC) # # Permission",
"the xml, A->B p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not",
"pair found in `pairs\\' dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqB,",
"# Permission is hereby granted, free of charge, to any person obtaining a",
"= 0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosASelf =",
"# raise RuntimeError('Duplicate pair found in `pairs\\' dict: %s-%s' % (seqA, seqB)) return",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"'A', False) truePosB = getItem(pairs, 'truePos' + suffix + 'B', False) falseNeg =",
"recallOut) / (precisionOut + recallOut)), truePosOutA, truePosOutA, falsePosOut, falseNegOut) print '%35s, %10s, %10s,",
"> 0 or p.falsePosRegion > 0 or p.falseNegRegion > 0: return True def",
"+= p.truePosRegionOutsideA obsTruePosBSelfOut += p.truePosRegionOutsideB obsFalsePosSelfOut += p.falsePosRegionOutside obsFalseNegSelfOut += p.falseNegRegionOutside else: obsTruePosA",
"addPairData() walks the tree to add data to the pairs dict. falsePosMode vs",
"fRegStr, p.truePosRegionA, p.truePosRegionB, p.falsePosRegion, p.falseNegRegion)) print('%35s %10s %10.5f %10s %9d %9d %9d %9d'",
"python \"\"\" comparatorSummarizer.py dent earl, dearl (a) soe ucsc edu 22 November 2011",
"falsePosSelf), (obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut), ]: assert(obs",
"0 self.falseNegRegionOutside = 0 self.precision = None self.recall = None self.precisionRegion = None",
"truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosOutA, truePosOutA), (obsTruePosOutB, truePosOutB), (obsFalsePosOut, falsePosOut), (obsFalseNegOut, falseNegOut),",
"truePosA, truePosB, falsePos, falseNeg) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s'",
"document.' % options.xml) root = tree.getroot() homTests = root.findall('homologyTests') pairs = {} addPairData(pairs,",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"falseNegOut) precisionSelfOut = float(truePosSelfOutB) / (truePosSelfOutB + falsePosSelfOut) recallSelfOut = float(truePosSelfOutA) / (truePosSelfOutA",
"without restriction, including without limitation the rights # to use, copy, modify, merge,",
"mafComparator then the xml will be in Region mode suffix = 'Region' truePosOutA",
"(TP_B + FP) # We use the TP_B since FP comes from the",
"inside' % p.niceNames, precRegStr, p.recallRegion, fRegStr, p.truePosRegionA, p.truePosRegionB, p.falsePosRegion, p.falseNegRegion)) print('%35s %10s %10.5f",
"data to the pairs dict. falsePosMode vs truePosMode: the first homology test in",
"+ self.falsePosRegion) == 0: self.precisionRegion = float('nan') else: self.precisionRegion = float(self.truePosRegionB) / (self.truePosRegionB",
"test in the xml, A->B p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both')",
"obsFalsePosSelf += p.falsePos obsFalseNegSelf += p.falseNeg else: obsTruePosA += p.truePosA obsTruePosB += p.truePosB",
"from the B->A comparison if (self.truePosB + self.falsePos) == 0: self.precision = float('nan')",
"= OptionParser(usage) initOptions(parser) options, args = parser.parse_args() checkOptions(options, args, parser) summarize(options) if __name__",
"p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: # the first homology test in",
"def initOptions(parser): parser.add_option('--xml', dest = 'xml', help = 'location of mafComparator output xml",
"assert(obs == exp) def sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosASelf, truePosBSelf, falsePosSelf, falseNegSelf, pairs,",
"xml, %s is not a well formed xml document.' % options.xml) root =",
"copies of the Software, and to permit persons to whom the Software is",
"(seqA, seqB) is stored in pairs. Return None if not, return the pair",
"if not alignSelf: if len(p.species) == 1: continue ans += p.__dict__[item] return ans",
"if t.find('aggregateResults').find('both') is not None: # bed file established regions p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue'])",
"falsePosSelfOut, falseNegSelfOut, pairs, options): # Each column of numbers reported in the rows",
"p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: # the first",
"the second homology test in the xml, B->A p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos +=",
"falsePosSelfOut, falseNegSelfOut) else: sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, pairs, options)",
"pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosA obsTruePosBSelf +=",
"self)', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) / (precisionSelf + recallSelf)), truePosSelfA,",
"= '%.5f' % p.precision fStr = '%.5f' % (2 * ((p.precision * p.recall)/",
"found in `pairs\\' dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqA, seqB)]",
"SOFTWARE. ################################################## import xml.etree.ElementTree as ET import xml.parsers.expat from optparse import OptionParser import",
".bed files self.truePosRegionA = 0 # wrt A->B self.truePosRegionB = 0 # wrt",
"= 0 obsTruePosASelfOut = 0 obsTruePosBSelfOut = 0 obsFalsePosSelfOut = 0 obsFalseNegSelfOut =",
"'truePosRegionOutsideA', True) truePosSelfOutB = getItem(pairs, 'truePosRegionOutsideB', True) falsePosSelfOut = getItem(pairs, 'falsePosRegionOutside', True) falseNegSelfOut",
"% ('Overall (w/o self) outside', precisionOut, recallOut, 2 * ((precisionOut * recallOut) /",
"% (seqA, seqB) in pairs: # raise RuntimeError('Duplicate pair found in `pairs\\' dict:",
"obtaining a copy # of this software and associated documentation files (the \"Software\"),",
"restrict tests to a region \"\"\" for pair in pairs: p = pairs[pair]",
"%10.5f %10s %9d %9d %9d %9d' % ('%s outside' % p.niceNames, precRegOutStr, p.recallRegionOutside,",
"t.find('aggregateResults').find('both') is not None: # bed file established regions p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion",
"== 0: precRegStr = 'nan' fRegStr = 'nan' else: precRegStr = '%.5f' %",
"%prog \\n\\n' '%prog \\n') parser = OptionParser(usage) initOptions(parser) options, args = parser.parse_args() checkOptions(options,",
"+= int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed file",
"`homTests', addPairData() walks the tree to add data to the pairs dict. falsePosMode",
"the results of this comparison will be truePositives(B) and falsePositives(B) (this is falsePosMode).",
"or t.attrib['sequenceB'] == 'aggregate': # ignore the aggregate sequences continue p = findPair(seqA,",
"(B)', 'FN (A)') if isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut,",
"recallSelf, 2 * ((precisionSelf * recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf,",
"if (self.truePosRegionA + self.falseNegRegion) == 0: self.recallRegion = float('nan') else: self.recallRegion = float(self.truePosRegionA)",
"TP_A / (TP_A + FN) # We use the TP_A since FN comes",
"int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed file established",
"else: obsTruePosA += p.truePosA obsTruePosB += p.truePosB obsFalsePos += p.falsePos obsFalseNeg += p.falseNeg",
"= 0 # wrt A->B self.truePosRegionB = 0 # wrt B->A self.falsePosRegion =",
"2 * ((precisionSelfOut * recallSelfOut) / (precisionSelfOut + recallSelfOut)), truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut)",
"= float('nan') else: self.recall = float(self.truePosA) / (self.truePosA + self.falseNeg) if (self.truePosRegionA +",
"+ recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s,",
"'%s-%s' % (seqB, seqA) in pairs: # if '%s-%s' % (seqA, seqB) in",
"falsePos), (obsFalseNeg, falseNeg), (obsTruePosASelf, truePosASelf), (obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),]: assert(obs ==",
"(p.precisionRegionOutside + p.recallRegionOutside) == 0: precRegOutStr = 'nan' fRegOutStr = 'nan' else: precRegOutStr",
"any person obtaining a copy # of this software and associated documentation files",
"for pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosRegionA obsTruePosBSelf",
"dest = 'xml', help = 'location of mafComparator output xml to summarize.') def",
"(seqA, seqB)) return pairs['%s-%s' % (seqB, seqA)] return None def reportPairs(pairs, options): print('')",
"reported in the rows labeled \"Overall\" should be the sum of # the",
"%9d %9d' % ('%s outside' % p.niceNames, precRegOutStr, p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside,",
"falsePosSelf) == 0: precisionSelf = float('nan') else: precisionSelf = float(truePosSelfB) / (truePosSelfB +",
"of this comparison will be truePositives(A) and falseNegatives(A). the second homology test in",
"not None) self.species = set([speciesA, speciesB]) self.truePosA = 0 # with respect to",
"= hpTests.findall('homologyTest') for t in tests: seqA = t.attrib['sequenceA'].split('.')[0] seqB = t.attrib['sequenceB'].split('.')[0] if",
"self.falsePosRegion) if (self.truePosRegionOutsideB + self.falsePosRegionOutside) == 0: self.precisionRegionOutside = float('nan') else: self.precisionRegionOutside =",
"float('nan') else: recallSelf = float(truePosSelfA) / (truePosSelfA + falseNegSelf) print '%35s, %10s, %10s,",
"= 0 obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 obsTruePosASelfOut =",
"True) falsePosSelf = getItem(pairs, 'falsePos' + suffix, True) falseNegSelf = getItem(pairs, 'falseNeg' +",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"+ self.falsePosRegionOutside)) def calcRecall(self): # Recall is calculated as # TP_A / (TP_A",
"TP_A since FN comes from the A->B comparison if (self.truePosA + self.falseNeg) ==",
"a copy # of this software and associated documentation files (the \"Software\"), to",
"p.precision == -1.0 or (p.precision + p.recall) == 0: precStr = 'nan' fStr",
"suffix + 'A', True) truePosSelfB = getItem(pairs, 'truePos' + suffix + 'B', True)",
"(self.truePosRegionB + self.falsePosRegion) if (self.truePosRegionOutsideB + self.falsePosRegionOutside) == 0: self.precisionRegionOutside = float('nan') else:",
"p.falsePos obsFalseNegSelf += p.falseNeg else: obsTruePosA += p.truePosA obsTruePosB += p.truePosB obsFalsePos +=",
"of the name self.niceNames = '-'.join(names) if len(names) == 1: self.niceNames = 'self-%s'",
"p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA, seqB, pairs): # Check to",
"suffix, False) truePosSelfA = getItem(pairs, 'truePos' + suffix + 'A', True) truePosSelfB =",
"(obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut), ]:",
"or p.truePosRegionB > 0 or p.falsePosRegion > 0 or p.falseNegRegion > 0: return",
"speciesB): assert(speciesA is not None) assert(speciesB is not None) self.species = set([speciesA, speciesB])",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #",
"(the \"Software\"), to deal # in the Software without restriction, including without limitation",
"continue p = findPair(seqA, seqB, pairs) if p is None: p = ComparisonPair(seqA,",
"(self.truePosRegionOutsideA + self.falseNegRegionOutside)) def initOptions(parser): parser.add_option('--xml', dest = 'xml', help = 'location of",
"IN # THE SOFTWARE. ################################################## import xml.etree.ElementTree as ET import xml.parsers.expat from optparse",
"return pairs['%s-%s' % (seqB, seqA)] return None def reportPairs(pairs, options): print('') sortedPairs =",
"'xml', help = 'location of mafComparator output xml to summarize.') def checkOptions(options, args,",
"charge, to any person obtaining a copy # of this software and associated",
"of # the numbers contained in the column corresponding to \"inside\" or \"outside\"",
"+= obsFalseNegOut for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg,",
"= pairs[pair] if not alignSelf: if len(p.species) == 1: continue ans += p.__dict__[item]",
"(C) 2009-2011 by # <NAME> (<EMAIL>, <EMAIL>) # ... and other members of",
"Return None if not, return the pair if so. if '%s-%s' % (seqA,",
"(obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),]: assert(obs == exp) def isRegionMode(pairs): \"\"\" Detects if a",
"a region \"\"\" for pair in pairs: p = pairs[pair] if p.truePosRegionA >",
"xml, B->A p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None:",
"(obsFalseNegOut, falseNegOut), (obsTruePosASelf, truePosSelfA), (obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut,",
"in Region mode suffix = 'Region' truePosOutA = getItem(pairs, 'truePosRegionOutsideA', False) truePosOutB =",
"0: precRegStr = 'nan' fRegStr = 'nan' else: precRegStr = '%.5f' % p.precisionRegion",
"'TP (B)', 'FP (B)', 'FN (A)') if isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA,",
"limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"= getItem(pairs, 'truePosRegionOutsideB', False) falseNegOut = getItem(pairs, 'falseNegRegionOutside', False) falsePosOut = getItem(pairs, 'falsePosRegionOutside',",
"in the xml, A->B p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is",
"truePosBSelf), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),]: assert(obs == exp) def isRegionMode(pairs): \"\"\" Detects if",
"wrt B->A self.falsePosRegionOutside = 0 self.falseNegRegionOutside = 0 self.precision = None self.recall =",
"= 'Region' truePosOutA = getItem(pairs, 'truePosRegionOutsideA', False) truePosOutB = getItem(pairs, 'truePosRegionOutsideB', False) falseNegOut",
"return True def getItem(pairs, item, alignSelf): ans = 0 for pair in pairs:",
"pairs['%s-%s' % (seqB, seqA)] return None def reportPairs(pairs, options): print('') sortedPairs = sorted(pairs,",
"p.falsePos obsFalseNeg += p.falseNeg obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos",
"== seqB: pass # do not compare a genome to itself # continue",
"= float('nan') else: recall = float(truePosA) / (truePosA + falseNeg) if (truePosSelfB +",
"/ (truePosSelfB + falsePosSelf) if (truePosSelfA + falseNegSelf) == 0: recallSelf = float('nan')",
"+ falsePos) if (truePosA + falseNeg) == 0: recall = float('nan') else: recall",
"in pairs: p = pairs[pair] if not alignSelf: if len(p.species) == 1: continue",
"0: precRegOutStr = 'nan' fRegOutStr = 'nan' else: precRegOutStr = '%.5f' % p.precisionRegionOutside",
"/ (truePosOutB + falsePosOut) recallOut = float(truePosOutA) / (truePosOutA + falseNegOut) precisionSelfOut =",
"falseNeg) if (truePosSelfB + falsePosSelf) == 0: precisionSelf = float('nan') else: precisionSelf =",
"used by mafComparator then the xml will be in Region mode suffix =",
"'falseNeg' + suffix, False) falsePos = getItem(pairs, 'falsePos' + suffix, False) truePosSelfA =",
"obsFalsePos obsFalseNegSelf += obsFalseNeg obsTruePosASelfOut += obsTruePosOutA obsTruePosBSelfOut += obsTruePosOutB obsFalsePosSelfOut += obsFalsePosOut",
"(truePosSelfA + falseNegSelf) == 0: recallSelf = float('nan') else: recallSelf = float(truePosSelfA) /",
"= 'location of mafComparator output xml to summarize.') def checkOptions(options, args, parser): if",
"if (self.truePosRegionOutsideA + self.falseNegRegionOutside) == 0: self.recallRegionOutside = float('nan') else: self.recallRegionOutside = (float(self.truePosRegionOutsideA)",
"%9s' % ('Overall (w/o self)', precision, recall, 2 * (precision * recall) /",
"the xml will be in Region mode suffix = 'Region' truePosOutA = getItem(pairs,",
"== 0: self.recallRegionOutside = float('nan') else: self.recallRegionOutside = (float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA + self.falseNegRegionOutside))",
"recallOut = float(truePosOutA) / (truePosOutA + falseNegOut) precisionSelfOut = float(truePosSelfOutB) / (truePosSelfOutB +",
"'nan' else: precRegStr = '%.5f' % p.precisionRegion fRegStr = '%.5f' % (2 *",
"'-'.join(names) if len(names) == 1: self.niceNames = 'self-%s' % names[0] def calcPrecision(self): #",
"/ (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) reportPairs(pairs, options) def sanityCheckRegionMode(truePosA, truePosB,",
"names[0] def calcPrecision(self): # Precision is calculated as # TP_B / (TP_B +",
"suffix = '' truePosA = getItem(pairs, 'truePos' + suffix + 'A', False) truePosB",
"False) falseNegOut = getItem(pairs, 'falseNegRegionOutside', False) falsePosOut = getItem(pairs, 'falsePosRegionOutside', False) truePosSelfOutA =",
"% ('Overall (w/ self) inside', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) /",
"truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosOutA, truePosOutA), (obsTruePosOutB, truePosOutB), (obsFalsePosOut, falsePosOut),",
"p.falseNeg obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"test in the mC output is B->A and the results of this comparison",
"contained in the column corresponding to \"inside\" or \"outside\" status. obsTruePosA = 0",
"EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"suffix, True) falseNegSelf = getItem(pairs, 'falseNeg' + suffix, True) if (truePosB + falsePos)",
"* recall) / (precision + recall), truePosA, truePosB, falsePos, falseNeg) print '%35s, %10s,",
"p.truePosRegionOutsideA obsTruePosBSelfOut += p.truePosRegionOutsideB obsFalsePosSelfOut += p.falsePosRegionOutside obsFalseNegSelfOut += p.falseNegRegionOutside else: obsTruePosA +=",
"]: assert(obs == exp) def sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosASelf, truePosBSelf, falsePosSelf, falseNegSelf,",
"print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self)",
"p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed",
"of numbers reported in the rows labeled \"Overall\" should be the sum of",
"in pairs: p = pairs[pair] if p.truePosRegionA > 0 or p.truePosRegionB > 0",
"def checkOptions(options, args, parser): if options.xml is None: parser.error('specify --xml') if not os.path.exists(options.xml):",
"0 # wrt B->A self.falsePosRegion = 0 self.falseNegRegion = 0 self.truePosRegionOutsideA = 0",
"the pair if so. if '%s-%s' % (seqA, seqB) in pairs: # if",
"= 'nan' fStr = 'nan' else: precStr = '%.5f' % p.precision fStr =",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE",
"%10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self) inside', precisionSelf, recallSelf, 2",
"precStr, p.recall, fStr, p.truePosA, p.truePosB, p.falsePos, p.falseNeg)) else: print('%35s %10s %10.5f %10s %9d",
"'Recall', 'F-score', 'TP (A)', 'TP (B)', 'FP (B)', 'FN (A)') if isRegionMode(pairs): sanityCheckRegionMode(truePosA,",
"obsTruePosOutA = 0 obsTruePosOutB = 0 obsFalsePosOut = 0 obsFalseNegOut = 0 obsTruePosASelf",
"precRegOutStr = 'nan' fRegOutStr = 'nan' else: precRegOutStr = '%.5f' % p.precisionRegionOutside fRegOutStr",
"= None self.precisionRegionOutside = None self.recallRegionOutside = None names = list(self.species) names =",
"as # TP_B / (TP_B + FP) # We use the TP_B since",
"# TP_A / (TP_A + FN) # We use the TP_A since FN",
"(self.truePosRegionOutsideB + self.falsePosRegionOutside) == 0: self.precisionRegionOutside = float('nan') else: self.precisionRegionOutside = (float(self.truePosRegionOutsideB) /",
"/ (truePosB + falsePos) if (truePosA + falseNeg) == 0: recall = float('nan')",
"obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 obsTruePosASelfOut",
"obsFalsePosOut obsFalseNegSelfOut += obsFalseNegOut for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos,",
"* recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) reportPairs(pairs, options) def",
"None def reportPairs(pairs, options): print('') sortedPairs = sorted(pairs, key = lambda x: pairs[x].niceNames)",
"seqA = t.attrib['sequenceA'].split('.')[0] seqB = t.attrib['sequenceB'].split('.')[0] if seqA == 'self' or seqB ==",
"# # Permission is hereby granted, free of charge, to any person obtaining",
"== 0: precision = float('nan') else: precision = float(truePosB) / (truePosB + falsePos)",
"precision, recall, 2 * (precision * recall) / (precision + recall), truePosA, truePosB,",
"p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosA obsTruePosBSelf += p.truePosB obsFalsePosSelf +=",
"if p.precisionRegion == -1.0 or (p.precisionRegion + p.recallRegion) == 0: precRegStr = 'nan'",
"= 0 # wrt A->B self.truePosRegionOutsideB = 0 # wrt B->A self.falsePosRegionOutside =",
"%9s' % ('dataset', 'Precision', 'Recall', 'F-score', 'TP (A)', 'TP (B)', 'FP (B)', 'FN",
"seqB)] if '%s-%s' % (seqB, seqA) in pairs: # if '%s-%s' % (seqA,",
"truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs,",
"self.recallRegion = float('nan') else: self.recallRegion = float(self.truePosRegionA) / (self.truePosRegionA + self.falseNegRegion) if (self.truePosRegionOutsideA",
"= (float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB + self.falsePosRegionOutside)) def calcRecall(self): # Recall is calculated as",
"exp) def isRegionMode(pairs): \"\"\" Detects if a BED was used to restrict tests",
"information contained in file stored in options.xml \"\"\" try: tree = ET.parse(options.xml) except",
"(obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosASelf, truePosASelf), (obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),]: assert(obs",
"(precisionOut + recallOut)), truePosOutA, truePosOutA, falsePosOut, falseNegOut) print '%35s, %10s, %10s, %10s, %9s,",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"= 0 for pair in pairs: p = pairs[pair] if not alignSelf: if",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"% p.precisionRegionOutside fRegOutStr = '%.5f' % (2 * ((p.precisionRegionOutside * p.recallRegionOutside)/ (p.precisionRegionOutside +",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"# with respect to the A->B comparison self.truePosB = 0 # with respect",
"0 self.falseNeg = 0 # region numbers are for comparisons using .bed files",
"the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"with respect to the B->A comparison self.falsePos = 0 self.falseNeg = 0 #",
"%9s, %9s, %9s' % ('dataset', 'Precision', 'Recall', 'F-score', 'TP (A)', 'TP (B)', 'FP",
"(2 * ((p.precisionRegionOutside * p.recallRegionOutside)/ (p.precisionRegionOutside + p.recallRegionOutside))) if not isRegionMode(pairs): print('%35s %10s",
"of the Software, and to permit persons to whom the Software is #",
"xml.etree.ElementTree as ET import xml.parsers.expat from optparse import OptionParser import os class ComparisonPair:",
"do not compare a genome to itself # continue if t.attrib['sequenceA'] == 'aggregate'",
"(a) soe ucsc edu 22 November 2011 Simple utility to summarize output of",
"p.falseNegRegion obsTruePosASelfOut += p.truePosRegionOutsideA obsTruePosBSelfOut += p.truePosRegionOutsideB obsFalsePosSelfOut += p.falsePosRegionOutside obsFalseNegSelfOut += p.falseNegRegionOutside",
"/ (precisionOut + recallOut)), truePosOutA, truePosOutA, falsePosOut, falseNegOut) print '%35s, %10s, %10s, %10s,",
"0 # with respect to the A->B comparison self.truePosB = 0 # with",
"+ self.falsePosRegion) if (self.truePosRegionOutsideB + self.falsePosRegionOutside) == 0: self.precisionRegionOutside = float('nan') else: self.precisionRegionOutside",
"and falsePositives(B) (this is falsePosMode). \"\"\" hpTests = homTests.find('homologyPairTests') tests = hpTests.findall('homologyTest') for",
"obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg for obs, exp in",
"getItem(pairs, 'falseNeg' + suffix, False) falsePos = getItem(pairs, 'falsePos' + suffix, False) truePosSelfA",
"and the results of this comparison will be truePositives(B) and falsePositives(B) (this is",
"+= p.truePosRegionA obsTruePosBSelf += p.truePosRegionB obsFalsePosSelf += p.falsePosRegion obsFalseNegSelf += p.falseNegRegion obsTruePosASelfOut +=",
"summarize.') def checkOptions(options, args, parser): if options.xml is None: parser.error('specify --xml') if not",
"seqB)) return pairs['%s-%s' % (seqA, seqB)] if '%s-%s' % (seqB, seqA) in pairs:",
"truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s'",
"+ self.falseNeg) == 0: self.recall = float('nan') else: self.recall = float(self.truePosA) / (self.truePosA",
"obsFalsePosSelfOut += p.falsePosRegionOutside obsFalseNegSelfOut += p.falseNegRegionOutside else: obsTruePosA += p.truePosRegionA obsTruePosB += p.truePosRegionB",
"((precisionSelfOut * recallSelfOut) / (precisionSelfOut + recallSelfOut)), truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut) else: sanityCheck(truePosA,",
"if '%s-%s' % (seqB, seqA) in pairs: # raise RuntimeError('Duplicate pair found in",
"including without limitation the rights # to use, copy, modify, merge, publish, distribute,",
"# Check to see if the pair (seqA, seqB) is stored in pairs.",
"(truePosA + falseNeg) if (truePosSelfB + falsePosSelf) == 0: precisionSelf = float('nan') else:",
"falsePosOut = getItem(pairs, 'falsePosRegionOutside', False) truePosSelfOutA = getItem(pairs, 'truePosRegionOutsideA', True) truePosSelfOutB = getItem(pairs,",
"precisionSelfOut = float(truePosSelfOutB) / (truePosSelfOutB + falsePosSelfOut) recallSelfOut = float(truePosSelfOutA) / (truePosSelfOutA +",
"== 0: self.precisionRegion = float('nan') else: self.precisionRegion = float(self.truePosRegionB) / (self.truePosRegionB + self.falsePosRegion)",
"and other members of the Reconstruction Team of <NAME>'s # lab (BME Dept.",
"+ 'B', False) falseNeg = getItem(pairs, 'falseNeg' + suffix, False) falsePos = getItem(pairs,",
"'nan' fStr = 'nan' else: precStr = '%.5f' % p.precision fStr = '%.5f'",
"B->A self.falsePosRegionOutside = 0 self.falseNegRegionOutside = 0 self.precision = None self.recall = None",
"to the pairs dict. falsePosMode vs truePosMode: the first homology test in the",
"float(truePosOutA) / (truePosOutA + falseNegOut) precisionSelfOut = float(truePosSelfOutB) / (truePosSelfOutB + falsePosSelfOut) recallSelfOut",
"+ 'A', False) truePosB = getItem(pairs, 'truePos' + suffix + 'B', False) falseNeg",
"parser.error('specify --xml') if not os.path.exists(options.xml): parser.error('--xml %s does not exist' % options.xml) def",
"+= p.truePosA obsTruePosBSelf += p.truePosB obsFalsePosSelf += p.falsePos obsFalseNegSelf += p.falseNeg else: obsTruePosA",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"options.xml) root = tree.getroot() homTests = root.findall('homologyTests') pairs = {} addPairData(pairs, homTests[0]) addPairData(pairs,",
"int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed file established",
"= getItem(pairs, 'falsePosRegionOutside', False) truePosSelfOutA = getItem(pairs, 'truePosRegionOutsideA', True) truePosSelfOutB = getItem(pairs, 'truePosRegionOutsideB',",
"this comparison will be truePositives(B) and falsePositives(B) (this is falsePosMode). \"\"\" hpTests =",
"truePosMode: the first homology test in the mafComparator output is A->B and the",
"precision = float(truePosB) / (truePosB + falsePos) if (truePosA + falseNeg) == 0:",
"obsFalseNeg = 0 obsTruePosOutA = 0 obsTruePosOutB = 0 obsFalsePosOut = 0 obsFalseNegOut",
"'%.5f' % p.precisionRegionOutside fRegOutStr = '%.5f' % (2 * ((p.precisionRegionOutside * p.recallRegionOutside)/ (p.precisionRegionOutside",
"of # the numbers contained in the column. obsTruePosA = 0 obsTruePosB =",
"0 for pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosA",
"'Precision', 'Recall', 'F-score', 'TP (A)', 'TP (B)', 'FP (B)', 'FN (A)') if isRegionMode(pairs):",
"A->B self.truePosRegionB = 0 # wrt B->A self.falsePosRegion = 0 self.falseNegRegion = 0",
"the Software is # furnished to do so, subject to the following conditions:",
"subject to the following conditions: # # The above copyright notice and this",
"if not os.path.exists(options.xml): parser.error('--xml %s does not exist' % options.xml) def addPairData(pairs, homTests,",
"TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"* ((p.precisionRegion * p.recallRegion)/ (p.precisionRegion + p.recallRegion))) if p.precisionRegionOutside == -1.0 or (p.precisionRegionOutside",
"dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqA, seqB)] if '%s-%s' %",
"p.precision fStr = '%.5f' % (2 * ((p.precision * p.recall)/ (p.precision + p.recall)))",
"obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg for obs, exp",
"second homology test in the xml, B->A p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse'])",
"+= int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: #",
"(obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut,",
"/ (self.truePosRegionB + self.falsePosRegion) if (self.truePosRegionOutsideB + self.falsePosRegionOutside) == 0: self.precisionRegionOutside = float('nan')",
"int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA, seqB, pairs): # Check",
"falsePos), (obsFalseNeg, falseNeg), (obsTruePosOutA, truePosOutA), (obsTruePosOutB, truePosOutB), (obsFalsePosOut, falsePosOut), (obsFalseNegOut, falseNegOut), (obsTruePosASelf, truePosSelfA),",
"p if falsePosMode: # the second homology test in the xml, B->A p.truePosB",
"= findPair(seqA, seqB, pairs) if p is None: p = ComparisonPair(seqA, seqB) pairs['%s-%s'",
"calculated as # TP_B / (TP_B + FP) # We use the TP_B",
"if p is None: p = ComparisonPair(seqA, seqB) pairs['%s-%s' % (seqA, seqB)] =",
"by # <NAME> (<EMAIL>, <EMAIL>) # ... and other members of the Reconstruction",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"else: self.precisionRegionOutside = (float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB + self.falsePosRegionOutside)) def calcRecall(self): # Recall is",
"+= p.truePosRegionB obsFalsePosSelf += p.falsePosRegion obsFalseNegSelf += p.falseNegRegion obsTruePosASelfOut += p.truePosRegionOutsideA obsTruePosBSelfOut +=",
"seqB, pairs): # Check to see if the pair (seqA, seqB) is stored",
"\\n\\n' '%prog \\n') parser = OptionParser(usage) initOptions(parser) options, args = parser.parse_args() checkOptions(options, args,",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies",
"p = findPair(seqA, seqB, pairs) if p is None: p = ComparisonPair(seqA, seqB)",
"(truePosSelfA + falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' %",
"'aggregate': # ignore the aggregate sequences continue p = findPair(seqA, seqB, pairs) if",
"tests: seqA = t.attrib['sequenceA'].split('.')[0] seqB = t.attrib['sequenceB'].split('.')[0] if seqA == 'self' or seqB",
"* recallOut) / (precisionOut + recallOut)), truePosOutA, truePosOutA, falsePosOut, falseNegOut) print '%35s, %10s,",
"is hereby granted, free of charge, to any person obtaining a copy #",
"obsFalsePos = 0 obsFalseNeg = 0 obsTruePosOutA = 0 obsTruePosOutB = 0 obsFalsePosOut",
"# if a BED was used by mafComparator then the xml will be",
"homTests, falsePosMode = False): \"\"\" given the dict `pairs' and a part of",
"obsTruePosASelfOut += obsTruePosOutA obsTruePosBSelfOut += obsTruePosOutB obsFalsePosSelfOut += obsFalsePosOut obsFalseNegSelfOut += obsFalseNegOut for",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"<EMAIL>) # ... and other members of the Reconstruction Team of <NAME>'s #",
"'%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self) outside',",
"p.truePosRegionB obsFalsePosSelf += p.falsePosRegion obsFalseNegSelf += p.falseNegRegion obsTruePosASelfOut += p.truePosRegionOutsideA obsTruePosBSelfOut += p.truePosRegionOutsideB",
"A->B comparison if (self.truePosA + self.falseNeg) == 0: self.recall = float('nan') else: self.recall",
"is None: parser.error('specify --xml') if not os.path.exists(options.xml): parser.error('--xml %s does not exist' %",
"= 0 # with respect to the A->B comparison self.truePosB = 0 #",
"obsTruePosOutB obsFalsePosSelfOut += obsFalsePosOut obsFalseNegSelfOut += obsFalseNegOut for obs, exp in [(obsTruePosA, truePosA),",
"/ (self.truePosRegionA + self.falseNegRegion) if (self.truePosRegionOutsideA + self.falseNegRegionOutside) == 0: self.recallRegionOutside = float('nan')",
"in pairs: # raise RuntimeError('Duplicate pair found in `pairs\\' dict: %s-%s' % (seqA,",
"None if not, return the pair if so. if '%s-%s' % (seqA, seqB)",
"+ p.recall))) if p.precisionRegion == -1.0 or (p.precisionRegion + p.recallRegion) == 0: precRegStr",
"November 2011 Simple utility to summarize output of mafComparator for use with alignathon",
"outside', precisionSelfOut, recallSelfOut, 2 * ((precisionSelfOut * recallSelfOut) / (precisionSelfOut + recallSelfOut)), truePosSelfOutA,",
"p.recallRegion, fRegStr, p.truePosRegionA, p.truePosRegionB, p.falsePosRegion, p.falseNegRegion)) print('%35s %10s %10.5f %10s %9d %9d %9d",
"p.falseNegRegion)) print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % ('%s outside' %",
"[(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosASelf, truePosASelf), (obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf,",
"falsePosMode: # the second homology test in the xml, B->A p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue'])",
"sum of # the numbers contained in the column corresponding to \"inside\" or",
"+ suffix, True) falseNegSelf = getItem(pairs, 'falseNeg' + suffix, True) if (truePosB +",
"so, subject to the following conditions: # # The above copyright notice and",
"ComparisonPair(seqA, seqB) pairs['%s-%s' % (seqA, seqB)] = p if falsePosMode: # the second",
"%10s %9d %9d %9d %9d' % ('%s inside' % p.niceNames, precRegStr, p.recallRegion, fRegStr,",
"# We use the TP_B since FP comes from the B->A comparison if",
"precisionOut, recallOut, 2 * ((precisionOut * recallOut) / (precisionOut + recallOut)), truePosOutA, truePosOutA,",
"falseNegSelf, pairs, options): # Each column of numbers reported in the rows labeled",
"'%prog \\n') parser = OptionParser(usage) initOptions(parser) options, args = parser.parse_args() checkOptions(options, args, parser)",
"p.truePosRegionA > 0 or p.truePosRegionB > 0 or p.falsePosRegion > 0 or p.falseNegRegion",
"in sortedPairs: p = pairs[pair] p.calcRecall() p.calcPrecision() if p.precision == -1.0 or (p.precision",
"getItem(pairs, 'falsePosRegionOutside', False) truePosSelfOutA = getItem(pairs, 'truePosRegionOutsideA', True) truePosSelfOutB = getItem(pairs, 'truePosRegionOutsideB', True)",
"copy # of this software and associated documentation files (the \"Software\"), to deal",
"falsePosOut), (obsFalseNegOut, falseNegOut), (obsTruePosASelf, truePosSelfA), (obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA),",
"pair (seqA, seqB) is stored in pairs. Return None if not, return the",
"% ('%s inside' % p.niceNames, precRegStr, p.recallRegion, fRegStr, p.truePosRegionA, p.truePosRegionB, p.falsePosRegion, p.falseNegRegion)) print('%35s",
"2011 Simple utility to summarize output of mafComparator for use with alignathon competetition.",
"%9s, %9s, %9s' % ('Overall (w/ self) inside', precisionSelf, recallSelf, 2 * ((precisionSelf",
"getItem(pairs, 'truePos' + suffix + 'B', True) falsePosSelf = getItem(pairs, 'falsePos' + suffix,",
"recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) reportPairs(pairs, options) def sanityCheckRegionMode(truePosA,",
"to \"inside\" or \"outside\" status. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos =",
"self.recallRegionOutside = (float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA + self.falseNegRegionOutside)) def initOptions(parser): parser.add_option('--xml', dest = 'xml',",
"p.truePosA, p.truePosB, p.falsePos, p.falseNeg)) else: print('%35s %10s %10.5f %10s %9d %9d %9d %9d'",
"`pairs\\' dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqB, seqA)] return None",
"files self.truePosRegionA = 0 # wrt A->B self.truePosRegionB = 0 # wrt B->A",
"in the mC output is B->A and the results of this comparison will",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ################################################## import",
"recallSelfOut) / (precisionSelfOut + recallSelfOut)), truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut) else: sanityCheck(truePosA, truePosB, falsePos,",
"obsFalseNegSelfOut += p.falseNegRegionOutside else: obsTruePosA += p.truePosRegionA obsTruePosB += p.truePosRegionB obsFalsePos += p.falsePosRegion",
"-1.0 or (p.precision + p.recall) == 0: precStr = 'nan' fStr = 'nan'",
"= None self.precisionRegion = None self.recallRegion = None self.precisionRegionOutside = None self.recallRegionOutside =",
"for pair in pairs: p = pairs[pair] if p.truePosRegionA > 0 or p.truePosRegionB",
"earl, dearl (a) soe ucsc edu 22 November 2011 Simple utility to summarize",
"sublicense, and/or sell # copies of the Software, and to permit persons to",
"addPairData(pairs, homTests[1], falsePosMode = True) if isRegionMode(pairs): # if a BED was used",
"= '%.5f' % (2 * ((p.precisionRegion * p.recallRegion)/ (p.precisionRegion + p.recallRegion))) if p.precisionRegionOutside",
"is stored in pairs. Return None if not, return the pair if so.",
"p.recallRegionOutside))) if not isRegionMode(pairs): print('%35s %10s %10.5f %10s %9d %9d %9d %9d' %",
"+= obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg obsTruePosASelfOut += obsTruePosOutA obsTruePosBSelfOut +=",
"self.precision = float('nan') else: self.precision = float(self.truePosB) / (self.truePosB + self.falsePos) if (self.truePosRegionB",
"ans += p.__dict__[item] return ans def main(): usage = ('usage: %prog \\n\\n' '%prog",
"self.falseNegRegionOutside = 0 self.precision = None self.recall = None self.precisionRegion = None self.recallRegion",
"pass # do not compare a genome to itself # continue if t.attrib['sequenceA']",
"+ falseNegOut) precisionSelfOut = float(truePosSelfOutB) / (truePosSelfOutB + falsePosSelfOut) recallSelfOut = float(truePosSelfOutA) /",
"was used by mafComparator then the xml will be in Region mode suffix",
"truePosSelfB, falsePosSelf, falseNegSelf, pairs, options) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s,",
"dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqB, seqA)] return None def",
"return the pair if so. if '%s-%s' % (seqA, seqB) in pairs: #",
"# THE SOFTWARE. ################################################## import xml.etree.ElementTree as ET import xml.parsers.expat from optparse import",
"0 obsFalseNegOut = 0 obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf = 0",
"# copies of the Software, and to permit persons to whom the Software",
"falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options): # Each column of numbers reported",
"p.falsePosRegionOutside obsFalseNegSelfOut += p.falseNegRegionOutside else: obsTruePosA += p.truePosRegionA obsTruePosB += p.truePosRegionB obsFalsePos +=",
"= 0 obsTruePosOutA = 0 obsTruePosOutB = 0 obsFalsePosOut = 0 obsFalseNegOut =",
"used to restrict tests to a region \"\"\" for pair in pairs: p",
"reportPairs(pairs, options) def sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB,",
"== 0: precStr = 'nan' fStr = 'nan' else: precStr = '%.5f' %",
"this permission notice shall be included in # all copies or substantial portions",
"0 self.precision = None self.recall = None self.precisionRegion = None self.recallRegion = None",
"obsFalseNegSelfOut += obsFalseNegOut for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos),",
"xml.parsers.expat from optparse import OptionParser import os class ComparisonPair: def __init__(self, speciesA, speciesB):",
"= getItem(pairs, 'falsePos' + suffix, False) truePosSelfA = getItem(pairs, 'truePos' + suffix +",
"falsePosSelf, falseNegSelf) reportPairs(pairs, options) def sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut,",
"first homology test in the mafComparator output is A->B and the results of",
"('dataset', 'Precision', 'Recall', 'F-score', 'TP (A)', 'TP (B)', 'FP (B)', 'FN (A)') if",
"'truePos' + suffix + 'B', False) falseNeg = getItem(pairs, 'falseNeg' + suffix, False)",
"% (p.niceNames, precStr, p.recall, fStr, p.truePosA, p.truePosB, p.falsePos, p.falseNeg)) else: print('%35s %10s %10.5f",
"= float('nan') else: self.recallRegionOutside = (float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA + self.falseNegRegionOutside)) def initOptions(parser): parser.add_option('--xml',",
"== 'self': continue if seqA == seqB: pass # do not compare a",
"A->B self.truePosRegionOutsideB = 0 # wrt B->A self.falsePosRegionOutside = 0 self.falseNegRegionOutside = 0",
"= tree.getroot() homTests = root.findall('homologyTests') pairs = {} addPairData(pairs, homTests[0]) addPairData(pairs, homTests[1], falsePosMode",
"OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ################################################## import xml.etree.ElementTree",
"in here for convenience ################################################## # Copyright (C) 2009-2011 by # <NAME> (<EMAIL>,",
"self.falseNeg = 0 # region numbers are for comparisons using .bed files self.truePosRegionA",
"print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self)",
"help = 'location of mafComparator output xml to summarize.') def checkOptions(options, args, parser):",
"float(truePosSelfA) / (truePosSelfA + falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s,",
"%9s, %9s, %9s, %9s' % ('Overall (w/ self) outside', precisionSelfOut, recallSelfOut, 2 *",
"use the TP_B since FP comes from the B->A comparison if (self.truePosB +",
"will be truePositives(A) and falseNegatives(A). the second homology test in the mC output",
"# wrt A->B self.truePosRegionOutsideB = 0 # wrt B->A self.falsePosRegionOutside = 0 self.falseNegRegionOutside",
"else: self.recallRegionOutside = (float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA + self.falseNegRegionOutside)) def initOptions(parser): parser.add_option('--xml', dest =",
"0 obsTruePosBSelfOut = 0 obsFalsePosSelfOut = 0 obsFalseNegSelfOut = 0 for pair in",
"('Overall (w/o self) outside', precisionOut, recallOut, 2 * ((precisionOut * recallOut) / (precisionOut",
"was used to restrict tests to a region \"\"\" for pair in pairs:",
"None: p = ComparisonPair(seqA, seqB) pairs['%s-%s' % (seqA, seqB)] = p if falsePosMode:",
"FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF",
"# if '%s-%s' % (seqA, seqB) in pairs: # raise RuntimeError('Duplicate pair found",
"p.truePosA obsTruePosBSelf += p.truePosB obsFalsePosSelf += p.falsePos obsFalseNegSelf += p.falseNeg else: obsTruePosA +=",
"merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to",
"and falseNegatives(A). the second homology test in the mC output is B->A and",
"float(truePosA) / (truePosA + falseNeg) if (truePosSelfB + falsePosSelf) == 0: precisionSelf =",
"= ComparisonPair(seqA, seqB) pairs['%s-%s' % (seqA, seqB)] = p if falsePosMode: # the",
"falsePosSelf, falseNegSelf, pairs, options) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s'",
"p.falsePosRegionOutside obsFalseNegOut += p.falseNegRegionOutside obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos",
"= 0 obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 for pair",
"%s does not exist' % options.xml) def addPairData(pairs, homTests, falsePosMode = False): \"\"\"",
"def main(): usage = ('usage: %prog \\n\\n' '%prog \\n') parser = OptionParser(usage) initOptions(parser)",
"contained in the column. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos = 0",
"comparatorSummarizer.py dent earl, dearl (a) soe ucsc edu 22 November 2011 Simple utility",
"suffix, False) falsePos = getItem(pairs, 'falsePos' + suffix, False) truePosSelfA = getItem(pairs, 'truePos'",
"('Overall (w/o self) inside', precision, recall, 2 * (precision * recall) / (precision",
"optparse import OptionParser import os class ComparisonPair: def __init__(self, speciesA, speciesB): assert(speciesA is",
"self.recall = None self.precisionRegion = None self.recallRegion = None self.precisionRegionOutside = None self.recallRegionOutside",
"(self.truePosRegionOutsideB + self.falsePosRegionOutside)) def calcRecall(self): # Recall is calculated as # TP_A /",
"to summarize.') def checkOptions(options, args, parser): if options.xml is None: parser.error('specify --xml') if",
"if (self.truePosA + self.falseNeg) == 0: self.recall = float('nan') else: self.recall = float(self.truePosA)",
"0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosOutA = 0",
"established regions p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside +=",
"+ self.falseNegRegionOutside) == 0: self.recallRegionOutside = float('nan') else: self.recallRegionOutside = (float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA",
"pair in pairs: p = pairs[pair] if p.truePosRegionA > 0 or p.truePosRegionB >",
"falseNegSelf),]: assert(obs == exp) def isRegionMode(pairs): \"\"\" Detects if a BED was used",
"(truePosB + falsePos) if (truePosA + falseNeg) == 0: recall = float('nan') else:",
"recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) reportPairs(pairs, options) def sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA,",
"homTests[0]) addPairData(pairs, homTests[1], falsePosMode = True) if isRegionMode(pairs): # if a BED was",
"pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosRegionA obsTruePosBSelf += p.truePosRegionB obsFalsePosSelf += p.falsePosRegion obsFalseNegSelf",
"is calculated as # TP_B / (TP_B + FP) # We use the",
"whom the Software is # furnished to do so, subject to the following",
"assert(obs == exp) def isRegionMode(pairs): \"\"\" Detects if a BED was used to",
"falseNeg, truePosASelf, truePosBSelf, falsePosSelf, falseNegSelf, pairs, options): # Each column of numbers reported",
"int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: # the first homology test",
"# ignore the aggregate sequences continue p = findPair(seqA, seqB, pairs) if p",
"# but was moved in here for convenience ################################################## # Copyright (C) 2009-2011",
"copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software,",
"falseNegOut = getItem(pairs, 'falseNegRegionOutside', False) falsePosOut = getItem(pairs, 'falsePosRegionOutside', False) truePosSelfOutA = getItem(pairs,",
"(truePosSelfB + falsePosSelf) == 0: precisionSelf = float('nan') else: precisionSelf = float(truePosSelfB) /",
"or (p.precisionRegionOutside + p.recallRegionOutside) == 0: precRegOutStr = 'nan' fRegOutStr = 'nan' else:",
"... and other members of the Reconstruction Team of <NAME>'s # lab (BME",
"'%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self) inside',",
"%9s, %9s, %9s' % ('Overall (w/o self) inside', precision, recall, 2 * (precision",
"is # furnished to do so, subject to the following conditions: # #",
"+= int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA,",
"p.precisionRegion == -1.0 or (p.precisionRegion + p.recallRegion) == 0: precRegStr = 'nan' fRegStr",
"None self.recallRegion = None self.precisionRegionOutside = None self.recallRegionOutside = None names = list(self.species)",
"falseNeg), (obsTruePosASelf, truePosASelf), (obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),]: assert(obs == exp) def",
"'%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self) outside',",
"the TP_B since FP comes from the B->A comparison if (self.truePosB + self.falsePos)",
"0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 for pair in pairs: p =",
"bed file established regions p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue'])",
"%9s, %9s' % ('Overall (w/o self)', precision, recall, 2 * (precision * recall)",
"parser): if options.xml is None: parser.error('specify --xml') if not os.path.exists(options.xml): parser.error('--xml %s does",
"xml, A->B p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None:",
"falseNegSelfOut, pairs, options): # Each column of numbers reported in the rows labeled",
"getItem(pairs, 'falseNegRegionOutside', False) falsePosOut = getItem(pairs, 'falsePosRegionOutside', False) truePosSelfOutA = getItem(pairs, 'truePosRegionOutsideA', True)",
"options.xml) def addPairData(pairs, homTests, falsePosMode = False): \"\"\" given the dict `pairs' and",
"test in the mafComparator output is A->B and the results of this comparison",
"truePosB = getItem(pairs, 'truePos' + suffix + 'B', False) falseNeg = getItem(pairs, 'falseNeg'",
"* ((p.precisionRegionOutside * p.recallRegionOutside)/ (p.precisionRegionOutside + p.recallRegionOutside))) if not isRegionMode(pairs): print('%35s %10s %10.5f",
"= getItem(pairs, 'falseNegRegionOutside', True) precisionOut = float(truePosOutB) / (truePosOutB + falsePosOut) recallOut =",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"len(p.species) == 1: continue ans += p.__dict__[item] return ans def main(): usage =",
"+= p.truePosRegionOutsideB obsFalsePosOut += p.falsePosRegionOutside obsFalseNegOut += p.falseNegRegionOutside obsTruePosASelf += obsTruePosA obsTruePosBSelf +=",
"obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg obsTruePosASelfOut",
"from the A->B comparison if (self.truePosA + self.falseNeg) == 0: self.recall = float('nan')",
"'location of mafComparator output xml to summarize.') def checkOptions(options, args, parser): if options.xml",
"seqB) is stored in pairs. Return None if not, return the pair if",
"is calculated as # TP_A / (TP_A + FN) # We use the",
"+= int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed file",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE.",
"True) if (truePosB + falsePos) == 0: precision = float('nan') else: precision =",
"%s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqA, seqB)] if '%s-%s' % (seqB,",
"truePosSelfB, falsePosSelf, falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' %",
"calcPrecision(self): # Precision is calculated as # TP_B / (TP_B + FP) #",
"lab (BME Dept. UCSC) # # Permission is hereby granted, free of charge,",
"options.xml \"\"\" try: tree = ET.parse(options.xml) except xml.parsers.expat.ExpatError: raise RuntimeError('Input xml, %s is",
"self)', precision, recall, 2 * (precision * recall) / (precision + recall), truePosA,",
"truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosASelf, truePosASelf), (obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),]:",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,",
"for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosOutA,",
"truePosOutA, truePosOutA, falsePosOut, falseNegOut) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s'",
"float(truePosSelfB) / (truePosSelfB + falsePosSelf) if (truePosSelfA + falseNegSelf) == 0: recallSelf =",
"exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosOutA, truePosOutA), (obsTruePosOutB,",
"obsFalseNegSelf += p.falseNegRegion obsTruePosASelfOut += p.truePosRegionOutsideA obsTruePosBSelfOut += p.truePosRegionOutsideB obsFalsePosSelfOut += p.falsePosRegionOutside obsFalseNegSelfOut",
"truePosOutA = getItem(pairs, 'truePosRegionOutsideA', False) truePosOutB = getItem(pairs, 'truePosRegionOutsideB', False) falseNegOut = getItem(pairs,",
"+= p.falsePosRegionOutside obsFalseNegOut += p.falseNegRegionOutside obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf +=",
"'nan' else: precRegOutStr = '%.5f' % p.precisionRegionOutside fRegOutStr = '%.5f' % (2 *",
"since FN comes from the A->B comparison if (self.truePosA + self.falseNeg) == 0:",
"precRegOutStr = '%.5f' % p.precisionRegionOutside fRegOutStr = '%.5f' % (2 * ((p.precisionRegionOutside *",
"truePosSelfB), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut),",
"= 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 obsTruePosASelfOut = 0 obsTruePosBSelfOut =",
"furnished to do so, subject to the following conditions: # # The above",
"def isRegionMode(pairs): \"\"\" Detects if a BED was used to restrict tests to",
"comparison if (self.truePosB + self.falsePos) == 0: self.precision = float('nan') else: self.precision =",
"(obsFalseNegSelf, falseNegSelf),]: assert(obs == exp) def isRegionMode(pairs): \"\"\" Detects if a BED was",
"utility to summarize output of mafComparator for use with alignathon competetition. \"\"\" #",
"{} addPairData(pairs, homTests[0]) addPairData(pairs, homTests[1], falsePosMode = True) if isRegionMode(pairs): # if a",
"22 November 2011 Simple utility to summarize output of mafComparator for use with",
"%9s' % ('Overall (w/ self) outside', precisionSelfOut, recallSelfOut, 2 * ((precisionSelfOut * recallSelfOut)",
"%10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self)', precision, recall, 2",
"getItem(pairs, 'falsePos' + suffix, False) truePosSelfA = getItem(pairs, 'truePos' + suffix + 'A',",
"homology test in the mafComparator output is A->B and the results of this",
"+ recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) reportPairs(pairs, options) def sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg,",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"# Each column of numbers reported in the rows labeled \"Overall\" should be",
"and the results of this comparison will be truePositives(A) and falseNegatives(A). the second",
"pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosRegionA obsTruePosBSelf +=",
"precRegStr = 'nan' fRegStr = 'nan' else: precRegStr = '%.5f' % p.precisionRegion fRegStr",
"int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA, seqB,",
"%9d' % (p.niceNames, precStr, p.recall, fStr, p.truePosA, p.truePosB, p.falsePos, p.falseNeg)) else: print('%35s %10s",
"be included in # all copies or substantial portions of the Software. #",
"recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) print '%35s, %10s, %10s,",
"0 for pair in pairs: p = pairs[pair] if not alignSelf: if len(p.species)",
"BED was used by mafComparator then the xml will be in Region mode",
"* p.recallRegionOutside)/ (p.precisionRegionOutside + p.recallRegionOutside))) if not isRegionMode(pairs): print('%35s %10s %10.5f %10s %9d",
"self.falseNegRegion) if (self.truePosRegionOutsideA + self.falseNegRegionOutside) == 0: self.recallRegionOutside = float('nan') else: self.recallRegionOutside =",
"self.recallRegion = None self.precisionRegionOutside = None self.recallRegionOutside = None names = list(self.species) names",
"# do not compare a genome to itself # continue if t.attrib['sequenceA'] ==",
"else: precRegStr = '%.5f' % p.precisionRegion fRegStr = '%.5f' % (2 * ((p.precisionRegion",
"False) falsePos = getItem(pairs, 'falsePos' + suffix, False) truePosSelfA = getItem(pairs, 'truePos' +",
"else: self.precision = float(self.truePosB) / (self.truePosB + self.falsePos) if (self.truePosRegionB + self.falsePosRegion) ==",
"(A)', 'TP (B)', 'FP (B)', 'FN (A)') if isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg,",
"with alignathon competetition. \"\"\" # Note: Actually belongs to https://github.com/dentearl/mwgAlignAnalysis # but was",
"= pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosA obsTruePosBSelf += p.truePosB obsFalsePosSelf += p.falsePos",
"seqB)) return pairs['%s-%s' % (seqB, seqA)] return None def reportPairs(pairs, options): print('') sortedPairs",
"sorted(names, key = lambda x: x[3:]) # ignore the \"sim\" part of the",
"'self' or seqB == 'self': continue if seqA == seqB: pass # do",
"see if the pair (seqA, seqB) is stored in pairs. Return None if",
"p = ComparisonPair(seqA, seqB) pairs['%s-%s' % (seqA, seqB)] = p if falsePosMode: #",
"Note: Actually belongs to https://github.com/dentearl/mwgAlignAnalysis # but was moved in here for convenience",
"else: self.precisionRegion = float(self.truePosRegionB) / (self.truePosRegionB + self.falsePosRegion) if (self.truePosRegionOutsideB + self.falsePosRegionOutside) ==",
"self.recall = float('nan') else: self.recall = float(self.truePosA) / (self.truePosA + self.falseNeg) if (self.truePosRegionA",
"falsePosMode vs truePosMode: the first homology test in the mafComparator output is A->B",
"is B->A and the results of this comparison will be truePositives(B) and falsePositives(B)",
"\"\"\" summarize() summizes the information contained in file stored in options.xml \"\"\" try:",
"obsFalseNeg = 0 obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf",
"\"\"\" # Note: Actually belongs to https://github.com/dentearl/mwgAlignAnalysis # but was moved in here",
"obsFalseNeg += p.falseNeg obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf",
"falsePosSelfOut = getItem(pairs, 'falsePosRegionOutside', True) falseNegSelfOut = getItem(pairs, 'falseNegRegionOutside', True) precisionOut = float(truePosOutB)",
"= 0 # with respect to the B->A comparison self.falsePos = 0 self.falseNeg",
"falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut,",
"pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosRegionA obsTruePosBSelf += p.truePosRegionB obsFalsePosSelf",
"falseNegSelf = getItem(pairs, 'falseNeg' + suffix, True) if (truePosB + falsePos) == 0:",
"0 obsFalseNegSelfOut = 0 for pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'):",
"outside', precisionOut, recallOut, 2 * ((precisionOut * recallOut) / (precisionOut + recallOut)), truePosOutA,",
"(truePosSelfOutB + falsePosSelfOut) recallSelfOut = float(truePosSelfOutA) / (truePosSelfOutA + falseNegSelfOut) else: suffix =",
"float('nan') else: self.recall = float(self.truePosA) / (self.truePosA + self.falseNeg) if (self.truePosRegionA + self.falseNegRegion)",
"alignathon competetition. \"\"\" # Note: Actually belongs to https://github.com/dentearl/mwgAlignAnalysis # but was moved",
"0 # with respect to the B->A comparison self.falsePos = 0 self.falseNeg =",
"pairs['%s-%s' % (seqA, seqB)] = p if falsePosMode: # the second homology test",
"truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, pairs, options) print '%35s, %10s, %10s, %10s, %9s, %9s,",
"truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s,",
"OptionParser(usage) initOptions(parser) options, args = parser.parse_args() checkOptions(options, args, parser) summarize(options) if __name__ ==",
"falseNeg, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, pairs, options) print '%35s, %10s, %10s, %10s, %9s,",
"(obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut), ]: assert(obs == exp) def",
"%9s, %9s, %9s, %9s' % ('Overall (w/o self) outside', precisionOut, recallOut, 2 *",
"truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options) print '%35s, %10s,",
"seqB: pass # do not compare a genome to itself # continue if",
"belongs to https://github.com/dentearl/mwgAlignAnalysis # but was moved in here for convenience ################################################## #",
"seqA)] return None def reportPairs(pairs, options): print('') sortedPairs = sorted(pairs, key = lambda",
"# Copyright (C) 2009-2011 by # <NAME> (<EMAIL>, <EMAIL>) # ... and other",
"'%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self)', precision,",
"getItem(pairs, 'falsePos' + suffix, True) falseNegSelf = getItem(pairs, 'falseNeg' + suffix, True) if",
"= root.findall('homologyTests') pairs = {} addPairData(pairs, homTests[0]) addPairData(pairs, homTests[1], falsePosMode = True) if",
"p.truePosRegionOutsideB obsFalsePosSelfOut += p.falsePosRegionOutside obsFalseNegSelfOut += p.falseNegRegionOutside else: obsTruePosA += p.truePosRegionA obsTruePosB +=",
"the mafComparator output is A->B and the results of this comparison will be",
"in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosA obsTruePosBSelf += p.truePosB",
"# wrt B->A self.falsePosRegionOutside = 0 self.falseNegRegionOutside = 0 self.precision = None self.recall",
"We use the TP_A since FN comes from the A->B comparison if (self.truePosA",
"+ falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('dataset',",
"(B)', 'FP (B)', 'FN (A)') if isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB,",
"assert(speciesB is not None) self.species = set([speciesA, speciesB]) self.truePosA = 0 # with",
"= {} addPairData(pairs, homTests[0]) addPairData(pairs, homTests[1], falsePosMode = True) if isRegionMode(pairs): # if",
"/ (self.truePosB + self.falsePos) if (self.truePosRegionB + self.falsePosRegion) == 0: self.precisionRegion = float('nan')",
"falsePos, falseNeg) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall",
"def reportPairs(pairs, options): print('') sortedPairs = sorted(pairs, key = lambda x: pairs[x].niceNames) for",
"+ self.falseNegRegion) == 0: self.recallRegion = float('nan') else: self.recallRegion = float(self.truePosRegionA) / (self.truePosRegionA",
"first homology test in the xml, A->B p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse'])",
"B->A p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: #",
"+= obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg for obs, exp in [(obsTruePosA,",
"homology test in the mC output is B->A and the results of this",
"copyright notice and this permission notice shall be included in # all copies",
"obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosOutA, truePosOutA),",
"or p.falsePosRegion > 0 or p.falseNegRegion > 0: return True def getItem(pairs, item,",
"= '' truePosA = getItem(pairs, 'truePos' + suffix + 'A', False) truePosB =",
"dict `pairs' and a part of the xml tree `homTests', addPairData() walks the",
"deal # in the Software without restriction, including without limitation the rights #",
"recallSelf = float(truePosSelfA) / (truePosSelfA + falseNegSelf) print '%35s, %10s, %10s, %10s, %9s,",
"0 or p.falsePosRegion > 0 or p.falseNegRegion > 0: return True def getItem(pairs,",
"as ET import xml.parsers.expat from optparse import OptionParser import os class ComparisonPair: def",
"if t.attrib['sequenceA'] == 'aggregate' or t.attrib['sequenceB'] == 'aggregate': # ignore the aggregate sequences",
"was moved in here for convenience ################################################## # Copyright (C) 2009-2011 by #",
"wrt B->A self.falsePosRegion = 0 self.falseNegRegion = 0 self.truePosRegionOutsideA = 0 # wrt",
"truePosSelfA = getItem(pairs, 'truePos' + suffix + 'A', True) truePosSelfB = getItem(pairs, 'truePos'",
"truePosA = getItem(pairs, 'truePos' + suffix + 'A', False) truePosB = getItem(pairs, 'truePos'",
"the first homology test in the mafComparator output is A->B and the results",
"TP_B / (TP_B + FP) # We use the TP_B since FP comes",
"* ((p.precision * p.recall)/ (p.precision + p.recall))) if p.precisionRegion == -1.0 or (p.precisionRegion",
"in tests: seqA = t.attrib['sequenceA'].split('.')[0] seqB = t.attrib['sequenceB'].split('.')[0] if seqA == 'self' or",
"% (seqA, seqB)] if '%s-%s' % (seqB, seqA) in pairs: # if '%s-%s'",
"competetition. \"\"\" # Note: Actually belongs to https://github.com/dentearl/mwgAlignAnalysis # but was moved in",
"= getItem(pairs, 'truePos' + suffix + 'B', False) falseNeg = getItem(pairs, 'falseNeg' +",
"/ (TP_A + FN) # We use the TP_A since FN comes from",
"options, args = parser.parse_args() checkOptions(options, args, parser) summarize(options) if __name__ == '__main__': main()",
"int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: # the",
"+ p.recallRegion))) if p.precisionRegionOutside == -1.0 or (p.precisionRegionOutside + p.recallRegionOutside) == 0: precRegOutStr",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"to whom the Software is # furnished to do so, subject to the",
"truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut), ]: assert(obs == exp) def sanityCheck(truePosA, truePosB, falsePos,",
"None self.precisionRegionOutside = None self.recallRegionOutside = None names = list(self.species) names = sorted(names,",
"initOptions(parser) options, args = parser.parse_args() checkOptions(options, args, parser) summarize(options) if __name__ == '__main__':",
"+ FN) # We use the TP_A since FN comes from the A->B",
"formed xml document.' % options.xml) root = tree.getroot() homTests = root.findall('homologyTests') pairs =",
"--xml') if not os.path.exists(options.xml): parser.error('--xml %s does not exist' % options.xml) def addPairData(pairs,",
"OR OTHER DEALINGS IN # THE SOFTWARE. ################################################## import xml.etree.ElementTree as ET import",
"/ (self.truePosA + self.falseNeg) if (self.truePosRegionA + self.falseNegRegion) == 0: self.recallRegion = float('nan')",
"pairs[pair] if not alignSelf: if len(p.species) == 1: continue ans += p.__dict__[item] return",
"as # TP_A / (TP_A + FN) # We use the TP_A since",
"import os class ComparisonPair: def __init__(self, speciesA, speciesB): assert(speciesA is not None) assert(speciesB",
"in pairs. Return None if not, return the pair if so. if '%s-%s'",
"self.falsePosRegionOutside) == 0: self.precisionRegionOutside = float('nan') else: self.precisionRegionOutside = (float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB +",
"%10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self)', precisionSelf, recallSelf,",
"falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options): # Each column of numbers",
"self.truePosB = 0 # with respect to the B->A comparison self.falsePos = 0",
"output is A->B and the results of this comparison will be truePositives(A) and",
"dearl (a) soe ucsc edu 22 November 2011 Simple utility to summarize output",
"print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self)',",
"seqB)] = p if falsePosMode: # the second homology test in the xml,",
"(obsTruePosOutB, truePosOutB), (obsFalsePosOut, falsePosOut), (obsFalseNegOut, falseNegOut), (obsTruePosASelf, truePosSelfA), (obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf,",
"= None self.recallRegionOutside = None names = list(self.species) names = sorted(names, key =",
"p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed file established regions",
"%9s' % ('Overall (w/o self) outside', precisionOut, recallOut, 2 * ((precisionOut * recallOut)",
"0: self.recallRegionOutside = float('nan') else: self.recallRegionOutside = (float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA + self.falseNegRegionOutside)) def",
"= getItem(pairs, 'truePosRegionOutsideB', True) falsePosSelfOut = getItem(pairs, 'falsePosRegionOutside', True) falseNegSelfOut = getItem(pairs, 'falseNegRegionOutside',",
"THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"% p.niceNames, precRegStr, p.recallRegion, fRegStr, p.truePosRegionA, p.truePosRegionB, p.falsePosRegion, p.falseNegRegion)) print('%35s %10s %10.5f %10s",
"= 0 obsTruePosOutB = 0 obsFalsePosOut = 0 obsFalseNegOut = 0 obsTruePosASelf =",
"# Recall is calculated as # TP_A / (TP_A + FN) # We",
"== -1.0 or (p.precision + p.recall) == 0: precStr = 'nan' fStr =",
"BED was used to restrict tests to a region \"\"\" for pair in",
"print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('dataset', 'Precision', 'Recall',",
"`pairs\\' dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqA, seqB)] if '%s-%s'",
"+= p.falsePos obsFalseNeg += p.falseNeg obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf +=",
"obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosOutA = 0 obsTruePosOutB",
"pairs, options) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall",
"p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else:",
"then the xml will be in Region mode suffix = 'Region' truePosOutA =",
"%10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self) outside', precisionSelfOut, recallSelfOut,",
"well formed xml document.' % options.xml) root = tree.getroot() homTests = root.findall('homologyTests') pairs",
"% (seqA, seqB) in pairs: # if '%s-%s' % (seqB, seqA) in pairs:",
"precisionOut = float(truePosOutB) / (truePosOutB + falsePosOut) recallOut = float(truePosOutA) / (truePosOutA +",
"truePosOutB), (obsFalsePosOut, falsePosOut), (obsFalseNegOut, falseNegOut), (obsTruePosASelf, truePosSelfA), (obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),",
"assert(speciesA is not None) assert(speciesB is not None) self.species = set([speciesA, speciesB]) self.truePosA",
"truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options): # Each column of",
"respect to the B->A comparison self.falsePos = 0 self.falseNeg = 0 # region",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"/ (truePosOutA + falseNegOut) precisionSelfOut = float(truePosSelfOutB) / (truePosSelfOutB + falsePosSelfOut) recallSelfOut =",
"False) truePosSelfOutA = getItem(pairs, 'truePosRegionOutsideA', True) truePosSelfOutB = getItem(pairs, 'truePosRegionOutsideB', True) falsePosSelfOut =",
"sell # copies of the Software, and to permit persons to whom the",
"obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB,",
"falsePosSelf), (obsFalseNegSelf, falseNegSelf),]: assert(obs == exp) def isRegionMode(pairs): \"\"\" Detects if a BED",
"not, return the pair if so. if '%s-%s' % (seqA, seqB) in pairs:",
"self.species = set([speciesA, speciesB]) self.truePosA = 0 # with respect to the A->B",
"%9s, %9s' % ('dataset', 'Precision', 'Recall', 'F-score', 'TP (A)', 'TP (B)', 'FP (B)',",
"float('nan') else: precision = float(truePosB) / (truePosB + falsePos) if (truePosA + falseNeg)",
"== 1: self.niceNames = 'self-%s' % names[0] def calcPrecision(self): # Precision is calculated",
"= float(truePosOutB) / (truePosOutB + falsePosOut) recallOut = float(truePosOutA) / (truePosOutA + falseNegOut)",
"suffix + 'B', True) falsePosSelf = getItem(pairs, 'falsePos' + suffix, True) falseNegSelf =",
"# all copies or substantial portions of the Software. # # THE SOFTWARE",
"(p.precision + p.recall))) if p.precisionRegion == -1.0 or (p.precisionRegion + p.recallRegion) == 0:",
"0 self.falseNegRegion = 0 self.truePosRegionOutsideA = 0 # wrt A->B self.truePosRegionOutsideB = 0",
"0 obsFalseNegSelf = 0 obsTruePosASelfOut = 0 obsTruePosBSelfOut = 0 obsFalsePosSelfOut = 0",
"= 0 obsTruePosBSelfOut = 0 obsFalsePosSelfOut = 0 obsFalseNegSelfOut = 0 for pair",
"0 or p.falseNegRegion > 0: return True def getItem(pairs, item, alignSelf): ans =",
"else: precisionSelf = float(truePosSelfB) / (truePosSelfB + falsePosSelf) if (truePosSelfA + falseNegSelf) ==",
"% (seqA, seqB)) return pairs['%s-%s' % (seqB, seqA)] return None def reportPairs(pairs, options):",
"(obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosOutA, truePosOutA), (obsTruePosOutB, truePosOutB), (obsFalsePosOut, falsePosOut), (obsFalseNegOut, falseNegOut), (obsTruePosASelf,",
"truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) reportPairs(pairs, options) def sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB,",
"OTHER DEALINGS IN # THE SOFTWARE. ################################################## import xml.etree.ElementTree as ET import xml.parsers.expat",
"all copies or substantial portions of the Software. # # THE SOFTWARE IS",
"'%.5f' % (2 * ((p.precision * p.recall)/ (p.precision + p.recall))) if p.precisionRegion ==",
"FP) # We use the TP_B since FP comes from the B->A comparison",
"True) falseNegSelf = getItem(pairs, 'falseNeg' + suffix, True) if (truePosB + falsePos) ==",
"ignore the \"sim\" part of the name self.niceNames = '-'.join(names) if len(names) ==",
"self.precisionRegionOutside = None self.recallRegionOutside = None names = list(self.species) names = sorted(names, key",
"(w/ self) outside', precisionSelfOut, recallSelfOut, 2 * ((precisionSelfOut * recallSelfOut) / (precisionSelfOut +",
"obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg obsTruePosASelfOut += obsTruePosOutA obsTruePosBSelfOut",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR",
"else: print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % ('%s inside' %",
"OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"tree.getroot() homTests = root.findall('homologyTests') pairs = {} addPairData(pairs, homTests[0]) addPairData(pairs, homTests[1], falsePosMode =",
"(precision + recall), truePosA, truePosB, falsePos, falseNeg) print '%35s, %10s, %10s, %10s, %9s,",
"if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosRegionA obsTruePosBSelf += p.truePosRegionB obsFalsePosSelf += p.falsePosRegion obsFalseNegSelf +=",
"files (the \"Software\"), to deal # in the Software without restriction, including without",
"self.truePosRegionB = 0 # wrt B->A self.falsePosRegion = 0 self.falseNegRegion = 0 self.truePosRegionOutsideA",
"falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut), ]: assert(obs == exp) def sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosASelf,",
"getItem(pairs, 'falsePosRegionOutside', True) falseNegSelfOut = getItem(pairs, 'falseNegRegionOutside', True) precisionOut = float(truePosOutB) / (truePosOutB",
"pairs[pair] if p.truePosRegionA > 0 or p.truePosRegionB > 0 or p.falsePosRegion > 0",
"fRegOutStr = '%.5f' % (2 * ((p.precisionRegionOutside * p.recallRegionOutside)/ (p.precisionRegionOutside + p.recallRegionOutside))) if",
"= homTests.find('homologyPairTests') tests = hpTests.findall('homologyTest') for t in tests: seqA = t.attrib['sequenceA'].split('.')[0] seqB",
"def calcPrecision(self): # Precision is calculated as # TP_B / (TP_B + FP)",
"following conditions: # # The above copyright notice and this permission notice shall",
"float(self.truePosRegionA) / (self.truePosRegionA + self.falseNegRegion) if (self.truePosRegionOutsideA + self.falseNegRegionOutside) == 0: self.recallRegionOutside =",
"seqB) pairs['%s-%s' % (seqA, seqB)] = p if falsePosMode: # the second homology",
"p.calcPrecision() if p.precision == -1.0 or (p.precision + p.recall) == 0: precStr =",
"sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA,",
"int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA, seqB, pairs): # Check to see if the pair (seqA,",
"The above copyright notice and this permission notice shall be included in #",
"(p.precisionRegion + p.recallRegion))) if p.precisionRegionOutside == -1.0 or (p.precisionRegionOutside + p.recallRegionOutside) == 0:",
"obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg for obs, exp in [(obsTruePosA, truePosA),",
"raise RuntimeError('Duplicate pair found in `pairs\\' dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s'",
"obsTruePosOutA obsTruePosBSelfOut += obsTruePosOutB obsFalsePosSelfOut += obsFalsePosOut obsFalseNegSelfOut += obsFalseNegOut for obs, exp",
"(p.precisionRegion + p.recallRegion) == 0: precRegStr = 'nan' fRegStr = 'nan' else: precRegStr",
"falseNegSelf) reportPairs(pairs, options) def sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA,",
"is not None: # bed file established regions p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion +=",
"(obsFalseNegSelfOut, falseNegSelfOut), ]: assert(obs == exp) def sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosASelf, truePosBSelf,",
"self.niceNames = 'self-%s' % names[0] def calcPrecision(self): # Precision is calculated as #",
"p.falsePosRegion obsFalseNegSelf += p.falseNegRegion obsTruePosASelfOut += p.truePosRegionOutsideA obsTruePosBSelfOut += p.truePosRegionOutsideB obsFalsePosSelfOut += p.falsePosRegionOutside",
"== exp) def sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosASelf, truePosBSelf, falsePosSelf, falseNegSelf, pairs, options):",
"%10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self)', precisionSelf, recallSelf, 2",
"pair in pairs: p = pairs[pair] if not alignSelf: if len(p.species) == 1:",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN",
"in the column corresponding to \"inside\" or \"outside\" status. obsTruePosA = 0 obsTruePosB",
"seqA) in pairs: # raise RuntimeError('Duplicate pair found in `pairs\\' dict: %s-%s' %",
"/ (TP_B + FP) # We use the TP_B since FP comes from",
"precisionSelf = float(truePosSelfB) / (truePosSelfB + falsePosSelf) if (truePosSelfA + falseNegSelf) == 0:",
"obsFalsePos += p.falsePos obsFalseNeg += p.falseNeg obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf",
"+= p.falseNeg obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf +=",
"(obsFalsePosOut, falsePosOut), (obsFalseNegOut, falseNegOut), (obsTruePosASelf, truePosSelfA), (obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut,",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"= float('nan') else: self.precisionRegionOutside = (float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB + self.falsePosRegionOutside)) def calcRecall(self): #",
"to https://github.com/dentearl/mwgAlignAnalysis # but was moved in here for convenience ################################################## # Copyright",
"= None names = list(self.species) names = sorted(names, key = lambda x: x[3:])",
"exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosASelf, truePosASelf), (obsTruePosBSelf,",
"%9s' % ('Overall (w/ self)', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) /",
"0 # region numbers are for comparisons using .bed files self.truePosRegionA = 0",
"= ET.parse(options.xml) except xml.parsers.expat.ExpatError: raise RuntimeError('Input xml, %s is not a well formed",
"results of this comparison will be truePositives(B) and falsePositives(B) (this is falsePosMode). \"\"\"",
"True) truePosSelfOutB = getItem(pairs, 'truePosRegionOutsideB', True) falsePosSelfOut = getItem(pairs, 'falsePosRegionOutside', True) falseNegSelfOut =",
"(<EMAIL>, <EMAIL>) # ... and other members of the Reconstruction Team of <NAME>'s",
"ET import xml.parsers.expat from optparse import OptionParser import os class ComparisonPair: def __init__(self,",
"+ self.falseNegRegion) if (self.truePosRegionOutsideA + self.falseNegRegionOutside) == 0: self.recallRegionOutside = float('nan') else: self.recallRegionOutside",
"to see if the pair (seqA, seqB) is stored in pairs. Return None",
"notice shall be included in # all copies or substantial portions of the",
"float(truePosOutB) / (truePosOutB + falsePosOut) recallOut = float(truePosOutA) / (truePosOutA + falseNegOut) precisionSelfOut",
"int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed file established regions p.truePosRegionB +=",
"p.falsePos, p.falseNeg)) else: print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % ('%s",
"NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"/ (truePosA + falseNeg) if (truePosSelfB + falsePosSelf) == 0: precisionSelf = float('nan')",
"pairs) if p is None: p = ComparisonPair(seqA, seqB) pairs['%s-%s' % (seqA, seqB)]",
"p.precisionRegionOutside == -1.0 or (p.precisionRegionOutside + p.recallRegionOutside) == 0: precRegOutStr = 'nan' fRegOutStr",
"= getItem(pairs, 'falsePosRegionOutside', True) falseNegSelfOut = getItem(pairs, 'falseNegRegionOutside', True) precisionOut = float(truePosOutB) /",
"getItem(pairs, 'falseNegRegionOutside', True) precisionOut = float(truePosOutB) / (truePosOutB + falsePosOut) recallOut = float(truePosOutA)",
"= 0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosASelf = 0 obsTruePosBSelf =",
"+= p.truePosRegionOutsideB obsFalsePosSelfOut += p.falsePosRegionOutside obsFalseNegSelfOut += p.falseNegRegionOutside else: obsTruePosA += p.truePosRegionA obsTruePosB",
"FP comes from the B->A comparison if (self.truePosB + self.falsePos) == 0: self.precision",
"self.truePosRegionOutsideB = 0 # wrt B->A self.falsePosRegionOutside = 0 self.falseNegRegionOutside = 0 self.precision",
"= t.attrib['sequenceB'].split('.')[0] if seqA == 'self' or seqB == 'self': continue if seqA",
"regions p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse'])",
"A->B p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: #",
"p.truePosRegionB > 0 or p.falsePosRegion > 0 or p.falseNegRegion > 0: return True",
"sortedPairs = sorted(pairs, key = lambda x: pairs[x].niceNames) for pair in sortedPairs: p",
"corresponding to \"inside\" or \"outside\" status. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos",
"\"\"\" comparatorSummarizer.py dent earl, dearl (a) soe ucsc edu 22 November 2011 Simple",
"Detects if a BED was used to restrict tests to a region \"\"\"",
"isRegionMode(pairs): \"\"\" Detects if a BED was used to restrict tests to a",
"or \"outside\" status. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg",
"the xml, B->A p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not",
"= getItem(pairs, 'truePos' + suffix + 'A', False) truePosB = getItem(pairs, 'truePos' +",
"obsTruePosBSelfOut += obsTruePosOutB obsFalsePosSelfOut += obsFalsePosOut obsFalseNegSelfOut += obsFalseNegOut for obs, exp in",
"%9s, %9s' % ('Overall (w/ self)', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf)",
"test in the xml, B->A p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both')",
"labeled \"Overall\" should be the sum of # the numbers contained in the",
"((precisionSelf * recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) reportPairs(pairs, options)",
"truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB,",
"0 obsFalsePosOut = 0 obsFalseNegOut = 0 obsTruePosASelf = 0 obsTruePosBSelf = 0",
"truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options): # Each column",
"'A', True) truePosSelfB = getItem(pairs, 'truePos' + suffix + 'B', True) falsePosSelf =",
"p.falsePosRegion, p.falseNegRegion)) print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % ('%s outside'",
"of mafComparator output xml to summarize.') def checkOptions(options, args, parser): if options.xml is",
"> 0 or p.falseNegRegion > 0: return True def getItem(pairs, item, alignSelf): ans",
"if len(names) == 1: self.niceNames = 'self-%s' % names[0] def calcPrecision(self): # Precision",
"= ('usage: %prog \\n\\n' '%prog \\n') parser = OptionParser(usage) initOptions(parser) options, args =",
"falsePos, falseNeg, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, pairs, options) print '%35s, %10s, %10s, %10s,",
"+ suffix, False) falsePos = getItem(pairs, 'falsePos' + suffix, False) truePosSelfA = getItem(pairs,",
"/ (truePosSelfA + falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s'",
"0 obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 obsTruePosASelfOut = 0",
"# wrt A->B self.truePosRegionB = 0 # wrt B->A self.falsePosRegion = 0 self.falseNegRegion",
"falseNeg) == 0: recall = float('nan') else: recall = float(truePosA) / (truePosA +",
"p.truePosRegionA obsTruePosB += p.truePosRegionB obsFalsePos += p.falsePosRegion obsFalseNeg += p.falseNegRegion obsTruePosOutA += p.truePosRegionOutsideA",
"'nan' fRegOutStr = 'nan' else: precRegOutStr = '%.5f' % p.precisionRegionOutside fRegOutStr = '%.5f'",
"# wrt B->A self.falsePosRegion = 0 self.falseNegRegion = 0 self.truePosRegionOutsideA = 0 #",
"<gh_stars>0 #!/usr/bin/env python \"\"\" comparatorSummarizer.py dent earl, dearl (a) soe ucsc edu 22",
"= None self.recallRegion = None self.precisionRegionOutside = None self.recallRegionOutside = None names =",
"%9s' % ('Overall (w/ self) inside', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf)",
"recallSelfOut)), truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut) else: sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosSelfA, truePosSelfB, falsePosSelf,",
"xml to summarize.') def checkOptions(options, args, parser): if options.xml is None: parser.error('specify --xml')",
"'falsePos' + suffix, False) truePosSelfA = getItem(pairs, 'truePos' + suffix + 'A', True)",
"if (truePosSelfB + falsePosSelf) == 0: precisionSelf = float('nan') else: precisionSelf = float(truePosSelfB)",
"ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"or seqB == 'self': continue if seqA == seqB: pass # do not",
"%10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self) inside', precisionSelf, recallSelf,",
"not alignSelf: if len(p.species) == 1: continue ans += p.__dict__[item] return ans def",
"= float(truePosSelfA) / (truePosSelfA + falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s,",
"truePosASelf, truePosBSelf, falsePosSelf, falseNegSelf, pairs, options): # Each column of numbers reported in",
"the A->B comparison if (self.truePosA + self.falseNeg) == 0: self.recall = float('nan') else:",
"return None def reportPairs(pairs, options): print('') sortedPairs = sorted(pairs, key = lambda x:",
"p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside)) def summarize(options): \"\"\" summarize() summizes the information contained in file",
"+= obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg obsTruePosASelfOut +=",
"using .bed files self.truePosRegionA = 0 # wrt A->B self.truePosRegionB = 0 #",
"* recallSelfOut) / (precisionSelfOut + recallSelfOut)), truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut) else: sanityCheck(truePosA, truePosB,",
"% (seqA, seqB)] = p if falsePosMode: # the second homology test in",
"p.falsePosRegionOutside, p.falseNegRegionOutside)) def summarize(options): \"\"\" summarize() summizes the information contained in file stored",
"falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/",
"% (2 * ((p.precisionRegion * p.recallRegion)/ (p.precisionRegion + p.recallRegion))) if p.precisionRegionOutside == -1.0",
"falsePosMode). \"\"\" hpTests = homTests.find('homologyPairTests') tests = hpTests.findall('homologyTest') for t in tests: seqA",
"the numbers contained in the column. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos",
"to the following conditions: # # The above copyright notice and this permission",
"(truePosA + falseNeg) == 0: recall = float('nan') else: recall = float(truePosA) /",
"self.falsePosRegion) == 0: self.precisionRegion = float('nan') else: self.precisionRegion = float(self.truePosRegionB) / (self.truePosRegionB +",
"key = lambda x: x[3:]) # ignore the \"sim\" part of the name",
"Team of <NAME>'s # lab (BME Dept. UCSC) # # Permission is hereby",
"True) if isRegionMode(pairs): # if a BED was used by mafComparator then the",
"None self.recall = None self.precisionRegion = None self.recallRegion = None self.precisionRegionOutside = None",
"+ recallSelfOut)), truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut) else: sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosSelfA, truePosSelfB,",
"pairs, options): # Each column of numbers reported in the rows labeled \"Overall\"",
"column. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg = 0",
"recallOut, 2 * ((precisionOut * recallOut) / (precisionOut + recallOut)), truePosOutA, truePosOutA, falsePosOut,",
"0 obsFalseNegSelf = 0 for pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'):",
"obsTruePosASelf += p.truePosA obsTruePosBSelf += p.truePosB obsFalsePosSelf += p.falsePos obsFalseNegSelf += p.falseNeg else:",
"mode suffix = 'Region' truePosOutA = getItem(pairs, 'truePosRegionOutsideA', False) truePosOutB = getItem(pairs, 'truePosRegionOutsideB',",
"%9s, %9s' % ('Overall (w/o self) outside', precisionOut, recallOut, 2 * ((precisionOut *",
"len(names) == 1: self.niceNames = 'self-%s' % names[0] def calcPrecision(self): # Precision is",
"(seqA, seqB)] if '%s-%s' % (seqB, seqA) in pairs: # if '%s-%s' %",
"in pairs: # if '%s-%s' % (seqA, seqB) in pairs: # raise RuntimeError('Duplicate",
"(p.niceNames, precStr, p.recall, fStr, p.truePosA, p.truePosB, p.falsePos, p.falseNeg)) else: print('%35s %10s %10.5f %10s",
"((p.precisionRegion * p.recallRegion)/ (p.precisionRegion + p.recallRegion))) if p.precisionRegionOutside == -1.0 or (p.precisionRegionOutside +",
"= False): \"\"\" given the dict `pairs' and a part of the xml",
"int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed file established regions p.truePosRegionA +=",
"obsTruePosASelf += p.truePosRegionA obsTruePosBSelf += p.truePosRegionB obsFalsePosSelf += p.falsePosRegion obsFalseNegSelf += p.falseNegRegion obsTruePosASelfOut",
"not os.path.exists(options.xml): parser.error('--xml %s does not exist' % options.xml) def addPairData(pairs, homTests, falsePosMode",
"== 0: self.precision = float('nan') else: self.precision = float(self.truePosB) / (self.truePosB + self.falsePos)",
"not None: # bed file established regions p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse'])",
"%10s %9d %9d %9d %9d' % (p.niceNames, precStr, p.recall, fStr, p.truePosA, p.truePosB, p.falsePos,",
"alignSelf): ans = 0 for pair in pairs: p = pairs[pair] if not",
"fStr = '%.5f' % (2 * ((p.precision * p.recall)/ (p.precision + p.recall))) if",
"ucsc edu 22 November 2011 Simple utility to summarize output of mafComparator for",
"/ (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) print '%35s, %10s, %10s, %10s,",
"Software is # furnished to do so, subject to the following conditions: #",
"in the xml, B->A p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is",
"== exp) def isRegionMode(pairs): \"\"\" Detects if a BED was used to restrict",
"0 self.truePosRegionOutsideA = 0 # wrt A->B self.truePosRegionOutsideB = 0 # wrt B->A",
"p.recallRegion))) if p.precisionRegionOutside == -1.0 or (p.precisionRegionOutside + p.recallRegionOutside) == 0: precRegOutStr =",
"args, parser): if options.xml is None: parser.error('specify --xml') if not os.path.exists(options.xml): parser.error('--xml %s",
"pairs: # if '%s-%s' % (seqA, seqB) in pairs: # raise RuntimeError('Duplicate pair",
"'nan' else: precStr = '%.5f' % p.precision fStr = '%.5f' % (2 *",
"seqB) in pairs: # if '%s-%s' % (seqB, seqA) in pairs: # raise",
"%9s, %9s, %9s' % ('Overall (w/o self) outside', precisionOut, recallOut, 2 * ((precisionOut",
"truePosSelfB, falsePosSelf, falseNegSelf) reportPairs(pairs, options) def sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut,",
"t.attrib['sequenceA'].split('.')[0] seqB = t.attrib['sequenceB'].split('.')[0] if seqA == 'self' or seqB == 'self': continue",
"in pairs: # if '%s-%s' % (seqB, seqA) in pairs: # raise RuntimeError('Duplicate",
"(obsTruePosASelf, truePosASelf), (obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),]: assert(obs == exp) def isRegionMode(pairs):",
"+ recallOut)), truePosOutA, truePosOutA, falsePosOut, falseNegOut) print '%35s, %10s, %10s, %10s, %9s, %9s,",
"a BED was used to restrict tests to a region \"\"\" for pair",
"0: self.recallRegion = float('nan') else: self.recallRegion = float(self.truePosRegionA) / (self.truePosRegionA + self.falseNegRegion) if",
"%10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self) inside', precision, recall,",
"float('nan') else: self.recallRegionOutside = (float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA + self.falseNegRegionOutside)) def initOptions(parser): parser.add_option('--xml', dest",
"Precision is calculated as # TP_B / (TP_B + FP) # We use",
"pairs['%s-%s' % (seqA, seqB)] if '%s-%s' % (seqB, seqA) in pairs: # if",
"% ('%s outside' % p.niceNames, precRegOutStr, p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside)) def",
"p.truePosRegionB, p.falsePosRegion, p.falseNegRegion)) print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % ('%s",
"int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: # the first homology test in the xml, A->B p.truePosA +=",
"# ... and other members of the Reconstruction Team of <NAME>'s # lab",
"% (2 * ((p.precision * p.recall)/ (p.precision + p.recall))) if p.precisionRegion == -1.0",
"speciesB]) self.truePosA = 0 # with respect to the A->B comparison self.truePosB =",
"'%.5f' % (2 * ((p.precisionRegionOutside * p.recallRegionOutside)/ (p.precisionRegionOutside + p.recallRegionOutside))) if not isRegionMode(pairs):",
"(precisionSelfOut + recallSelfOut)), truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut) else: sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosSelfA,",
"(BME Dept. UCSC) # # Permission is hereby granted, free of charge, to",
"falseNeg) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o",
"the sum of # the numbers contained in the column corresponding to \"inside\"",
"(self.truePosRegionA + self.falseNegRegion) if (self.truePosRegionOutsideA + self.falseNegRegionOutside) == 0: self.recallRegionOutside = float('nan') else:",
"(obsFalseNeg, falseNeg), (obsTruePosASelf, truePosASelf), (obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),]: assert(obs == exp)",
"None: parser.error('specify --xml') if not os.path.exists(options.xml): parser.error('--xml %s does not exist' % options.xml)",
"the name self.niceNames = '-'.join(names) if len(names) == 1: self.niceNames = 'self-%s' %",
"obsFalseNegOut for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg),",
"0 obsTruePosASelfOut = 0 obsTruePosBSelfOut = 0 obsFalsePosSelfOut = 0 obsFalseNegSelfOut = 0",
"be the sum of # the numbers contained in the column. obsTruePosA =",
"obsFalseNegSelf += obsFalseNeg obsTruePosASelfOut += obsTruePosOutA obsTruePosBSelfOut += obsTruePosOutB obsFalsePosSelfOut += obsFalsePosOut obsFalseNegSelfOut",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"= 0 for pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf +=",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"if (truePosA + falseNeg) == 0: recall = float('nan') else: recall = float(truePosA)",
"not None: # bed file established regions p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse'])",
"wrt A->B self.truePosRegionOutsideB = 0 # wrt B->A self.falsePosRegionOutside = 0 self.falseNegRegionOutside =",
"comparison will be truePositives(A) and falseNegatives(A). the second homology test in the mC",
"+ suffix + 'A', False) truePosB = getItem(pairs, 'truePos' + suffix + 'B',",
"'B', False) falseNeg = getItem(pairs, 'falseNeg' + suffix, False) falsePos = getItem(pairs, 'falsePos'",
"try: tree = ET.parse(options.xml) except xml.parsers.expat.ExpatError: raise RuntimeError('Input xml, %s is not a",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the",
"+ p.recallRegion) == 0: precRegStr = 'nan' fRegStr = 'nan' else: precRegStr =",
"% ('Overall (w/ self)', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) / (precisionSelf",
"the following conditions: # # The above copyright notice and this permission notice",
"0 obsTruePosOutB = 0 obsFalsePosOut = 0 obsFalseNegOut = 0 obsTruePosASelf = 0",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND",
"= (float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA + self.falseNegRegionOutside)) def initOptions(parser): parser.add_option('--xml', dest = 'xml', help",
"0: self.recall = float('nan') else: self.recall = float(self.truePosA) / (self.truePosA + self.falseNeg) if",
"rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #",
"+= int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: # the first homology test in the xml, A->B p.truePosA",
"to summarize output of mafComparator for use with alignathon competetition. \"\"\" # Note:",
"+= p.falseNegRegionOutside obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf +=",
"file established regions p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside",
"pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosA obsTruePosBSelf += p.truePosB obsFalsePosSelf",
"== 0: self.precisionRegionOutside = float('nan') else: self.precisionRegionOutside = (float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB + self.falsePosRegionOutside))",
"OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"== 0: precRegOutStr = 'nan' fRegOutStr = 'nan' else: precRegOutStr = '%.5f' %",
"the column corresponding to \"inside\" or \"outside\" status. obsTruePosA = 0 obsTruePosB =",
"bed file established regions p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue'])",
"\"inside\" or \"outside\" status. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos = 0",
"to do so, subject to the following conditions: # # The above copyright",
"findPair(seqA, seqB, pairs): # Check to see if the pair (seqA, seqB) is",
"(w/o self) inside', precision, recall, 2 * (precision * recall) / (precision +",
"of the Reconstruction Team of <NAME>'s # lab (BME Dept. UCSC) # #",
"is not None) assert(speciesB is not None) self.species = set([speciesA, speciesB]) self.truePosA =",
"= 0 obsFalseNegSelf = 0 obsTruePosASelfOut = 0 obsTruePosBSelfOut = 0 obsFalsePosSelfOut =",
"= 0 obsFalsePosSelfOut = 0 obsFalseNegSelfOut = 0 for pair in pairs: p",
"self.precisionRegionOutside = (float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB + self.falsePosRegionOutside)) def calcRecall(self): # Recall is calculated",
"None: # bed file established regions p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB",
"== 'aggregate' or t.attrib['sequenceB'] == 'aggregate': # ignore the aggregate sequences continue p",
"################################################## import xml.etree.ElementTree as ET import xml.parsers.expat from optparse import OptionParser import os",
"falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options) print '%35s, %10s, %10s, %10s,",
"# bed file established regions p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA +=",
"FN) # We use the TP_A since FN comes from the A->B comparison",
"('%s outside' % p.niceNames, precRegOutStr, p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside)) def summarize(options):",
"False) falseNeg = getItem(pairs, 'falseNeg' + suffix, False) falsePos = getItem(pairs, 'falsePos' +",
"import OptionParser import os class ComparisonPair: def __init__(self, speciesA, speciesB): assert(speciesA is not",
"lambda x: pairs[x].niceNames) for pair in sortedPairs: p = pairs[pair] p.calcRecall() p.calcPrecision() if",
"0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosASelf = 0",
"B->A and the results of this comparison will be truePositives(B) and falsePositives(B) (this",
"p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosRegionA obsTruePosBSelf += p.truePosRegionB obsFalsePosSelf +=",
"= list(self.species) names = sorted(names, key = lambda x: x[3:]) # ignore the",
"precRegStr, p.recallRegion, fRegStr, p.truePosRegionA, p.truePosRegionB, p.falsePosRegion, p.falseNegRegion)) print('%35s %10s %10.5f %10s %9d %9d",
"(self.truePosA + self.falseNeg) == 0: self.recall = float('nan') else: self.recall = float(self.truePosA) /",
"recallSelf = float('nan') else: recallSelf = float(truePosSelfA) / (truePosSelfA + falseNegSelf) print '%35s,",
"except xml.parsers.expat.ExpatError: raise RuntimeError('Input xml, %s is not a well formed xml document.'",
"%10.5f %10s %9d %9d %9d %9d' % (p.niceNames, precStr, p.recall, fStr, p.truePosA, p.truePosB,",
"p.recall))) if p.precisionRegion == -1.0 or (p.precisionRegion + p.recallRegion) == 0: precRegStr =",
"add data to the pairs dict. falsePosMode vs truePosMode: the first homology test",
"a genome to itself # continue if t.attrib['sequenceA'] == 'aggregate' or t.attrib['sequenceB'] ==",
"without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense,",
"(float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA + self.falseNegRegionOutside)) def initOptions(parser): parser.add_option('--xml', dest = 'xml', help =",
"precRegStr = '%.5f' % p.precisionRegion fRegStr = '%.5f' % (2 * ((p.precisionRegion *",
"options) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o",
"p.recallRegionOutside)/ (p.precisionRegionOutside + p.recallRegionOutside))) if not isRegionMode(pairs): print('%35s %10s %10.5f %10s %9d %9d",
"but was moved in here for convenience ################################################## # Copyright (C) 2009-2011 by",
"Dept. UCSC) # # Permission is hereby granted, free of charge, to any",
"use with alignathon competetition. \"\"\" # Note: Actually belongs to https://github.com/dentearl/mwgAlignAnalysis # but",
"of <NAME>'s # lab (BME Dept. UCSC) # # Permission is hereby granted,",
"truePosSelfOutB, falsePosSelfOut, falseNegSelfOut) else: sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, pairs,",
"falsePosMode = True) if isRegionMode(pairs): # if a BED was used by mafComparator",
"print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % (p.niceNames, precStr, p.recall, fStr,",
"is falsePosMode). \"\"\" hpTests = homTests.find('homologyPairTests') tests = hpTests.findall('homologyTest') for t in tests:",
"the numbers contained in the column corresponding to \"inside\" or \"outside\" status. obsTruePosA",
"True) truePosSelfB = getItem(pairs, 'truePos' + suffix + 'B', True) falsePosSelf = getItem(pairs,",
"\"\"\" try: tree = ET.parse(options.xml) except xml.parsers.expat.ExpatError: raise RuntimeError('Input xml, %s is not",
"fStr, p.truePosA, p.truePosB, p.falsePos, p.falseNeg)) else: print('%35s %10s %10.5f %10s %9d %9d %9d",
"= pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosRegionA obsTruePosBSelf += p.truePosRegionB obsFalsePosSelf += p.falsePosRegion",
"xml document.' % options.xml) root = tree.getroot() homTests = root.findall('homologyTests') pairs = {}",
"else: obsTruePosA += p.truePosRegionA obsTruePosB += p.truePosRegionB obsFalsePos += p.falsePosRegion obsFalseNeg += p.falseNegRegion",
"permission notice shall be included in # all copies or substantial portions of",
"+= p.truePosA obsTruePosB += p.truePosB obsFalsePos += p.falsePos obsFalseNeg += p.falseNeg obsTruePosASelf +=",
"edu 22 November 2011 Simple utility to summarize output of mafComparator for use",
"return ans def main(): usage = ('usage: %prog \\n\\n' '%prog \\n') parser =",
"recallSelfOut = float(truePosSelfOutA) / (truePosSelfOutA + falseNegSelfOut) else: suffix = '' truePosA =",
"usage = ('usage: %prog \\n\\n' '%prog \\n') parser = OptionParser(usage) initOptions(parser) options, args",
"getItem(pairs, 'truePos' + suffix + 'A', False) truePosB = getItem(pairs, 'truePos' + suffix",
"if a BED was used to restrict tests to a region \"\"\" for",
"precisionSelfOut, recallSelfOut, 2 * ((precisionSelfOut * recallSelfOut) / (precisionSelfOut + recallSelfOut)), truePosSelfOutA, truePosSelfOutB,",
"Simple utility to summarize output of mafComparator for use with alignathon competetition. \"\"\"",
"alignSelf: if len(p.species) == 1: continue ans += p.__dict__[item] return ans def main():",
"+= p.truePosRegionA obsTruePosB += p.truePosRegionB obsFalsePos += p.falsePosRegion obsFalseNeg += p.falseNegRegion obsTruePosOutA +=",
"('Overall (w/ self)', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) / (precisionSelf +",
"of mafComparator for use with alignathon competetition. \"\"\" # Note: Actually belongs to",
"obsFalseNegOut = 0 obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf",
"p.precisionRegion fRegStr = '%.5f' % (2 * ((p.precisionRegion * p.recallRegion)/ (p.precisionRegion + p.recallRegion)))",
"+= obsFalsePosOut obsFalseNegSelfOut += obsFalseNegOut for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB),",
"recallSelfOut, 2 * ((precisionSelfOut * recallSelfOut) / (precisionSelfOut + recallSelfOut)), truePosSelfOutA, truePosSelfOutB, falsePosSelfOut,",
"= 0 self.falseNeg = 0 # region numbers are for comparisons using .bed",
"recall) / (precision + recall), truePosA, truePosB, falsePos, falseNeg) print '%35s, %10s, %10s,",
"p.falseNegRegion obsTruePosOutA += p.truePosRegionOutsideA obsTruePosOutB += p.truePosRegionOutsideB obsFalsePosOut += p.falsePosRegionOutside obsFalseNegOut += p.falseNegRegionOutside",
"float(truePosB) / (truePosB + falsePos) if (truePosA + falseNeg) == 0: recall =",
"homology test in the xml, A->B p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if",
"(truePosSelfOutA + falseNegSelfOut) else: suffix = '' truePosA = getItem(pairs, 'truePos' + suffix",
"= 'nan' else: precRegStr = '%.5f' % p.precisionRegion fRegStr = '%.5f' % (2",
"'falseNeg' + suffix, True) if (truePosB + falsePos) == 0: precision = float('nan')",
"shall be included in # all copies or substantial portions of the Software.",
"use the TP_A since FN comes from the A->B comparison if (self.truePosA +",
"speciesA, speciesB): assert(speciesA is not None) assert(speciesB is not None) self.species = set([speciesA,",
"float('nan') else: self.precisionRegionOutside = (float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB + self.falsePosRegionOutside)) def calcRecall(self): # Recall",
"# Precision is calculated as # TP_B / (TP_B + FP) # We",
"= 'nan' fRegOutStr = 'nan' else: precRegOutStr = '%.5f' % p.precisionRegionOutside fRegOutStr =",
"+ falsePosOut) recallOut = float(truePosOutA) / (truePosOutA + falseNegOut) precisionSelfOut = float(truePosSelfOutB) /",
"* ((precisionOut * recallOut) / (precisionOut + recallOut)), truePosOutA, truePosOutA, falsePosOut, falseNegOut) print",
"(seqA, seqB)] = p if falsePosMode: # the second homology test in the",
"modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"('Overall (w/o self)', precision, recall, 2 * (precision * recall) / (precision +",
"= float(truePosOutA) / (truePosOutA + falseNegOut) precisionSelfOut = float(truePosSelfOutB) / (truePosSelfOutB + falsePosSelfOut)",
"'%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self) inside',",
"by mafComparator then the xml will be in Region mode suffix = 'Region'",
"(w/o self) outside', precisionOut, recallOut, 2 * ((precisionOut * recallOut) / (precisionOut +",
"initOptions(parser): parser.add_option('--xml', dest = 'xml', help = 'location of mafComparator output xml to",
"'self-%s' % names[0] def calcPrecision(self): # Precision is calculated as # TP_B /",
"= float(truePosA) / (truePosA + falseNeg) if (truePosSelfB + falsePosSelf) == 0: precisionSelf",
"falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options): # Each",
"publish, distribute, sublicense, and/or sell # copies of the Software, and to permit",
"sequences continue p = findPair(seqA, seqB, pairs) if p is None: p =",
"<NAME>'s # lab (BME Dept. UCSC) # # Permission is hereby granted, free",
"= sorted(pairs, key = lambda x: pairs[x].niceNames) for pair in sortedPairs: p =",
"precision = float('nan') else: precision = float(truePosB) / (truePosB + falsePos) if (truePosA",
"the A->B comparison self.truePosB = 0 # with respect to the B->A comparison",
"for convenience ################################################## # Copyright (C) 2009-2011 by # <NAME> (<EMAIL>, <EMAIL>) #",
"sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosASelf, truePosBSelf, falsePosSelf, falseNegSelf, pairs, options): # Each column",
"falsePosOut, falseNegOut) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall",
"addPairData(pairs, homTests[0]) addPairData(pairs, homTests[1], falsePosMode = True) if isRegionMode(pairs): # if a BED",
"seqB == 'self': continue if seqA == seqB: pass # do not compare",
"+ self.falseNeg) if (self.truePosRegionA + self.falseNegRegion) == 0: self.recallRegion = float('nan') else: self.recallRegion",
"> 0: return True def getItem(pairs, item, alignSelf): ans = 0 for pair",
"= getItem(pairs, 'truePos' + suffix + 'A', True) truePosSelfB = getItem(pairs, 'truePos' +",
"pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosA obsTruePosBSelf += p.truePosB obsFalsePosSelf += p.falsePos obsFalseNegSelf",
"homTests[1], falsePosMode = True) if isRegionMode(pairs): # if a BED was used by",
"* (precision * recall) / (precision + recall), truePosA, truePosB, falsePos, falseNeg) print",
"p = pairs[pair] if p.truePosRegionA > 0 or p.truePosRegionB > 0 or p.falsePosRegion",
"= 'nan' else: precStr = '%.5f' % p.precision fStr = '%.5f' % (2",
"(seqB, seqA) in pairs: # raise RuntimeError('Duplicate pair found in `pairs\\' dict: %s-%s'",
"+= p.falsePosRegion obsFalseNeg += p.falseNegRegion obsTruePosOutA += p.truePosRegionOutsideA obsTruePosOutB += p.truePosRegionOutsideB obsFalsePosOut +=",
"p.calcRecall() p.calcPrecision() if p.precision == -1.0 or (p.precision + p.recall) == 0: precStr",
"%s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqB, seqA)] return None def reportPairs(pairs,",
"# <NAME> (<EMAIL>, <EMAIL>) # ... and other members of the Reconstruction Team",
"+= obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg for obs,",
"import xml.parsers.expat from optparse import OptionParser import os class ComparisonPair: def __init__(self, speciesA,",
"== 1: continue ans += p.__dict__[item] return ans def main(): usage = ('usage:",
"%10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self)', precision, recall, 2 *",
"= lambda x: x[3:]) # ignore the \"sim\" part of the name self.niceNames",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"seqA == seqB: pass # do not compare a genome to itself #",
"+ p.recall) == 0: precStr = 'nan' fStr = 'nan' else: precStr =",
"(obsFalseNeg, falseNeg), (obsTruePosOutA, truePosOutA), (obsTruePosOutB, truePosOutB), (obsFalsePosOut, falsePosOut), (obsFalseNegOut, falseNegOut), (obsTruePosASelf, truePosSelfA), (obsTruePosBSelf,",
"% ('Overall (w/o self)', precision, recall, 2 * (precision * recall) / (precision",
"= 0 obsFalseNegSelf = 0 for pair in pairs: p = pairs[pair] if",
"= float('nan') else: precisionSelf = float(truePosSelfB) / (truePosSelfB + falsePosSelf) if (truePosSelfA +",
"obsTruePosA = 0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosASelf",
"falseNegOut), (obsTruePosASelf, truePosSelfA), (obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB),",
"/ (precisionSelfOut + recallSelfOut)), truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut) else: sanityCheck(truePosA, truePosB, falsePos, falseNeg,",
"p.falsePosRegion > 0 or p.falseNegRegion > 0: return True def getItem(pairs, item, alignSelf):",
"We use the TP_B since FP comes from the B->A comparison if (self.truePosB",
"lambda x: x[3:]) # ignore the \"sim\" part of the name self.niceNames =",
"(obsTruePosOutA, truePosOutA), (obsTruePosOutB, truePosOutB), (obsFalsePosOut, falsePosOut), (obsFalseNegOut, falseNegOut), (obsTruePosASelf, truePosSelfA), (obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf,",
"numbers contained in the column corresponding to \"inside\" or \"outside\" status. obsTruePosA =",
"(obsTruePosASelf, truePosSelfA), (obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut,",
"Reconstruction Team of <NAME>'s # lab (BME Dept. UCSC) # # Permission is",
"0 obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 for pair in",
"= lambda x: pairs[x].niceNames) for pair in sortedPairs: p = pairs[pair] p.calcRecall() p.calcPrecision()",
"= float('nan') else: precision = float(truePosB) / (truePosB + falsePos) if (truePosA +",
"obsTruePosASelfOut = 0 obsTruePosBSelfOut = 0 obsFalsePosSelfOut = 0 obsFalseNegSelfOut = 0 for",
"# in the Software without restriction, including without limitation the rights # to",
"* ((precisionSelf * recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) print",
"%10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self) outside', precisionOut, recallOut, 2",
"<NAME> (<EMAIL>, <EMAIL>) # ... and other members of the Reconstruction Team of",
"+ falsePosSelf) == 0: precisionSelf = float('nan') else: precisionSelf = float(truePosSelfB) / (truePosSelfB",
"reportPairs(pairs, options): print('') sortedPairs = sorted(pairs, key = lambda x: pairs[x].niceNames) for pair",
"given the dict `pairs' and a part of the xml tree `homTests', addPairData()",
"of the xml tree `homTests', addPairData() walks the tree to add data to",
"= set([speciesA, speciesB]) self.truePosA = 0 # with respect to the A->B comparison",
"None) assert(speciesB is not None) self.species = set([speciesA, speciesB]) self.truePosA = 0 #",
"homTests = root.findall('homologyTests') pairs = {} addPairData(pairs, homTests[0]) addPairData(pairs, homTests[1], falsePosMode = True)",
"the mC output is B->A and the results of this comparison will be",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #",
"or p.falseNegRegion > 0: return True def getItem(pairs, item, alignSelf): ans = 0",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS",
"options) def sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf,",
"to restrict tests to a region \"\"\" for pair in pairs: p =",
"= 0 self.truePosRegionOutsideA = 0 # wrt A->B self.truePosRegionOutsideB = 0 # wrt",
"# if '%s-%s' % (seqB, seqA) in pairs: # raise RuntimeError('Duplicate pair found",
"self.falsePosRegion = 0 self.falseNegRegion = 0 self.truePosRegionOutsideA = 0 # wrt A->B self.truePosRegionOutsideB",
"comparison self.truePosB = 0 # with respect to the B->A comparison self.falsePos =",
"truePosB, falsePos, falseNeg, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, pairs, options) print '%35s, %10s, %10s,",
"False): \"\"\" given the dict `pairs' and a part of the xml tree",
"column corresponding to \"inside\" or \"outside\" status. obsTruePosA = 0 obsTruePosB = 0",
"truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options): # Each column of numbers reported in the",
"options): # Each column of numbers reported in the rows labeled \"Overall\" should",
"convenience ################################################## # Copyright (C) 2009-2011 by # <NAME> (<EMAIL>, <EMAIL>) # ...",
"p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if t.find('aggregateResults').find('both') is not None: # bed file established regions",
"0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosASelf = 0 obsTruePosBSelf = 0",
"status. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg = 0",
"+= p.truePosB obsFalsePos += p.falsePos obsFalseNeg += p.falseNeg obsTruePosASelf += obsTruePosA obsTruePosBSelf +=",
"+= p.falsePosRegionOutside obsFalseNegSelfOut += p.falseNegRegionOutside else: obsTruePosA += p.truePosRegionA obsTruePosB += p.truePosRegionB obsFalsePos",
"self.recallRegionOutside = float('nan') else: self.recallRegionOutside = (float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA + self.falseNegRegionOutside)) def initOptions(parser):",
"falsePos) if (truePosA + falseNeg) == 0: recall = float('nan') else: recall =",
"xml tree `homTests', addPairData() walks the tree to add data to the pairs",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE",
"(precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) print '%35s, %10s, %10s, %10s, %9s,",
"p.truePosB obsFalsePosSelf += p.falsePos obsFalseNegSelf += p.falseNeg else: obsTruePosA += p.truePosA obsTruePosB +=",
"'aggregate' or t.attrib['sequenceB'] == 'aggregate': # ignore the aggregate sequences continue p =",
"pairs dict. falsePosMode vs truePosMode: the first homology test in the mafComparator output",
"obsTruePosA += p.truePosA obsTruePosB += p.truePosB obsFalsePos += p.falsePos obsFalseNeg += p.falseNeg obsTruePosASelf",
"sorted(pairs, key = lambda x: pairs[x].niceNames) for pair in sortedPairs: p = pairs[pair]",
"\"Overall\" should be the sum of # the numbers contained in the column.",
"item, alignSelf): ans = 0 for pair in pairs: p = pairs[pair] if",
"+ p.recallRegionOutside) == 0: precRegOutStr = 'nan' fRegOutStr = 'nan' else: precRegOutStr =",
"= float(self.truePosB) / (self.truePosB + self.falsePos) if (self.truePosRegionB + self.falsePosRegion) == 0: self.precisionRegion",
"self.falsePos = 0 self.falseNeg = 0 # region numbers are for comparisons using",
"WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"%9d %9d' % ('%s inside' % p.niceNames, precRegStr, p.recallRegion, fRegStr, p.truePosRegionA, p.truePosRegionB, p.falsePosRegion,",
"Check to see if the pair (seqA, seqB) is stored in pairs. Return",
"'%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self)', precisionSelf,",
"if options.xml is None: parser.error('specify --xml') if not os.path.exists(options.xml): parser.error('--xml %s does not",
"obsTruePosA += p.truePosRegionA obsTruePosB += p.truePosRegionB obsFalsePos += p.falsePosRegion obsFalseNeg += p.falseNegRegion obsTruePosOutA",
"numbers are for comparisons using .bed files self.truePosRegionA = 0 # wrt A->B",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER",
"float(truePosSelfOutA) / (truePosSelfOutA + falseNegSelfOut) else: suffix = '' truePosA = getItem(pairs, 'truePos'",
"if p.precision == -1.0 or (p.precision + p.recall) == 0: precStr = 'nan'",
"(p.precision + p.recall) == 0: precStr = 'nan' fStr = 'nan' else: precStr",
"tree to add data to the pairs dict. falsePosMode vs truePosMode: the first",
"= '%.5f' % (2 * ((p.precision * p.recall)/ (p.precision + p.recall))) if p.precisionRegion",
"obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg obsTruePosASelfOut += obsTruePosOutA obsTruePosBSelfOut += obsTruePosOutB",
"obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosASelf, truePosASelf),",
"copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED",
"(self.truePosRegionB + self.falsePosRegion) == 0: self.precisionRegion = float('nan') else: self.precisionRegion = float(self.truePosRegionB) /",
"calcRecall(self): # Recall is calculated as # TP_A / (TP_A + FN) #",
"tree `homTests', addPairData() walks the tree to add data to the pairs dict.",
"(truePosOutB + falsePosOut) recallOut = float(truePosOutA) / (truePosOutA + falseNegOut) precisionSelfOut = float(truePosSelfOutB)",
"precisionSelf = float('nan') else: precisionSelf = float(truePosSelfB) / (truePosSelfB + falsePosSelf) if (truePosSelfA",
"TP_B since FP comes from the B->A comparison if (self.truePosB + self.falsePos) ==",
"the pair (seqA, seqB) is stored in pairs. Return None if not, return",
"else: recallSelf = float(truePosSelfA) / (truePosSelfA + falseNegSelf) print '%35s, %10s, %10s, %10s,",
"main(): usage = ('usage: %prog \\n\\n' '%prog \\n') parser = OptionParser(usage) initOptions(parser) options,",
"obsTruePosOutB += p.truePosRegionOutsideB obsFalsePosOut += p.falsePosRegionOutside obsFalseNegOut += p.falseNegRegionOutside obsTruePosASelf += obsTruePosA obsTruePosBSelf",
"__init__(self, speciesA, speciesB): assert(speciesA is not None) assert(speciesB is not None) self.species =",
"Recall is calculated as # TP_A / (TP_A + FN) # We use",
"# bed file established regions p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB +=",
"# the numbers contained in the column corresponding to \"inside\" or \"outside\" status.",
"obsTruePosB += p.truePosB obsFalsePos += p.falsePos obsFalseNeg += p.falseNeg obsTruePosASelf += obsTruePosA obsTruePosBSelf",
"falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('dataset', 'Precision',",
"'B', True) falsePosSelf = getItem(pairs, 'falsePos' + suffix, True) falseNegSelf = getItem(pairs, 'falseNeg'",
"(p.precisionRegionOutside + p.recallRegionOutside))) if not isRegionMode(pairs): print('%35s %10s %10.5f %10s %9d %9d %9d",
"'falsePosRegionOutside', True) falseNegSelfOut = getItem(pairs, 'falseNegRegionOutside', True) precisionOut = float(truePosOutB) / (truePosOutB +",
"if len(p.species) == 1: continue ans += p.__dict__[item] return ans def main(): usage",
"since FP comes from the B->A comparison if (self.truePosB + self.falsePos) == 0:",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"if not, return the pair if so. if '%s-%s' % (seqA, seqB) in",
"float(truePosSelfOutB) / (truePosSelfOutB + falsePosSelfOut) recallSelfOut = float(truePosSelfOutA) / (truePosSelfOutA + falseNegSelfOut) else:",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"Software without restriction, including without limitation the rights # to use, copy, modify,",
"0: self.precisionRegion = float('nan') else: self.precisionRegion = float(self.truePosRegionB) / (self.truePosRegionB + self.falsePosRegion) if",
"= float('nan') else: self.precisionRegion = float(self.truePosRegionB) / (self.truePosRegionB + self.falsePosRegion) if (self.truePosRegionOutsideB +",
"+= p.truePosRegionOutsideA obsTruePosOutB += p.truePosRegionOutsideB obsFalsePosOut += p.falsePosRegionOutside obsFalseNegOut += p.falseNegRegionOutside obsTruePosASelf +=",
"self) outside', precisionSelfOut, recallSelfOut, 2 * ((precisionSelfOut * recallSelfOut) / (precisionSelfOut + recallSelfOut)),",
"truePosASelf), (obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf, falseNegSelf),]: assert(obs == exp) def isRegionMode(pairs): \"\"\"",
"# The above copyright notice and this permission notice shall be included in",
"################################################## # Copyright (C) 2009-2011 by # <NAME> (<EMAIL>, <EMAIL>) # ... and",
"# of this software and associated documentation files (the \"Software\"), to deal #",
"obsFalseNeg += p.falseNegRegion obsTruePosOutA += p.truePosRegionOutsideA obsTruePosOutB += p.truePosRegionOutsideB obsFalsePosOut += p.falsePosRegionOutside obsFalseNegOut",
"to the B->A comparison self.falsePos = 0 self.falseNeg = 0 # region numbers",
"/ (self.truePosRegionOutsideB + self.falsePosRegionOutside)) def calcRecall(self): # Recall is calculated as # TP_A",
"substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options) print '%35s, %10s, %10s, %10s, %9s,",
"itself # continue if t.attrib['sequenceA'] == 'aggregate' or t.attrib['sequenceB'] == 'aggregate': # ignore",
"if isRegionMode(pairs): # if a BED was used by mafComparator then the xml",
"summizes the information contained in file stored in options.xml \"\"\" try: tree =",
"truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options)",
"obsFalseNegSelf += p.falseNeg else: obsTruePosA += p.truePosA obsTruePosB += p.truePosB obsFalsePos += p.falsePos",
"if a BED was used by mafComparator then the xml will be in",
"https://github.com/dentearl/mwgAlignAnalysis # but was moved in here for convenience ################################################## # Copyright (C)",
"%9s, %9s' % ('Overall (w/ self) inside', precisionSelf, recallSelf, 2 * ((precisionSelf *",
"restriction, including without limitation the rights # to use, copy, modify, merge, publish,",
"/ (precision + recall), truePosA, truePosB, falsePos, falseNeg) print '%35s, %10s, %10s, %10s,",
"recall), truePosA, truePosB, falsePos, falseNeg) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s,",
"float('nan') else: precisionSelf = float(truePosSelfB) / (truePosSelfB + falsePosSelf) if (truePosSelfA + falseNegSelf)",
"truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options): # Each column of numbers reported in",
"(self.truePosA + self.falseNeg) if (self.truePosRegionA + self.falseNegRegion) == 0: self.recallRegion = float('nan') else:",
"A->B and the results of this comparison will be truePositives(A) and falseNegatives(A). the",
"+ self.falseNegRegionOutside)) def initOptions(parser): parser.add_option('--xml', dest = 'xml', help = 'location of mafComparator",
"self.falsePosRegionOutside)) def calcRecall(self): # Recall is calculated as # TP_A / (TP_A +",
"mC output is B->A and the results of this comparison will be truePositives(B)",
"suffix + 'B', False) falseNeg = getItem(pairs, 'falseNeg' + suffix, False) falsePos =",
"if '%s-%s' % (seqA, seqB) in pairs: # if '%s-%s' % (seqB, seqA)",
"%9s, %9s, %9s' % ('Overall (w/o self)', precision, recall, 2 * (precision *",
"= 0 self.falseNegRegion = 0 self.truePosRegionOutsideA = 0 # wrt A->B self.truePosRegionOutsideB =",
"% p.precisionRegion fRegStr = '%.5f' % (2 * ((p.precisionRegion * p.recallRegion)/ (p.precisionRegion +",
"p.recallRegion)/ (p.precisionRegion + p.recallRegion))) if p.precisionRegionOutside == -1.0 or (p.precisionRegionOutside + p.recallRegionOutside) ==",
"= pairs[pair] p.calcRecall() p.calcPrecision() if p.precision == -1.0 or (p.precision + p.recall) ==",
"%10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('dataset', 'Precision', 'Recall', 'F-score', 'TP",
"p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def",
"# ignore the \"sim\" part of the name self.niceNames = '-'.join(names) if len(names)",
"-1.0 or (p.precisionRegion + p.recallRegion) == 0: precRegStr = 'nan' fRegStr = 'nan'",
"options): print('') sortedPairs = sorted(pairs, key = lambda x: pairs[x].niceNames) for pair in",
"are for comparisons using .bed files self.truePosRegionA = 0 # wrt A->B self.truePosRegionB",
"xml will be in Region mode suffix = 'Region' truePosOutA = getItem(pairs, 'truePosRegionOutsideA',",
"((p.precision * p.recall)/ (p.precision + p.recall))) if p.precisionRegion == -1.0 or (p.precisionRegion +",
"x: x[3:]) # ignore the \"sim\" part of the name self.niceNames = '-'.join(names)",
"float('nan') else: self.precisionRegion = float(self.truePosRegionB) / (self.truePosRegionB + self.falsePosRegion) if (self.truePosRegionOutsideB + self.falsePosRegionOutside)",
"p.truePosRegionB obsFalsePos += p.falsePosRegion obsFalseNeg += p.falseNegRegion obsTruePosOutA += p.truePosRegionOutsideA obsTruePosOutB += p.truePosRegionOutsideB",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR",
"rows labeled \"Overall\" should be the sum of # the numbers contained in",
"truePosB, falsePos, falseNeg, truePosASelf, truePosBSelf, falsePosSelf, falseNegSelf, pairs, options): # Each column of",
"% options.xml) root = tree.getroot() homTests = root.findall('homologyTests') pairs = {} addPairData(pairs, homTests[0])",
"obsFalsePos += p.falsePosRegion obsFalseNeg += p.falseNegRegion obsTruePosOutA += p.truePosRegionOutsideA obsTruePosOutB += p.truePosRegionOutsideB obsFalsePosOut",
"0: return True def getItem(pairs, item, alignSelf): ans = 0 for pair in",
"self.precisionRegion = float(self.truePosRegionB) / (self.truePosRegionB + self.falsePosRegion) if (self.truePosRegionOutsideB + self.falsePosRegionOutside) == 0:",
"p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosA obsTruePosBSelf += p.truePosB obsFalsePosSelf += p.falsePos obsFalseNegSelf += p.falseNeg",
"1: continue ans += p.__dict__[item] return ans def main(): usage = ('usage: %prog",
"2 * ((precisionOut * recallOut) / (precisionOut + recallOut)), truePosOutA, truePosOutA, falsePosOut, falseNegOut)",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ##################################################",
"+= obsFalseNeg obsTruePosASelfOut += obsTruePosOutA obsTruePosBSelfOut += obsTruePosOutB obsFalsePosSelfOut += obsFalsePosOut obsFalseNegSelfOut +=",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"seqA) in pairs: # if '%s-%s' % (seqA, seqB) in pairs: # raise",
"falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut), ]: assert(obs == exp)",
"+ falseNegSelfOut) else: suffix = '' truePosA = getItem(pairs, 'truePos' + suffix +",
"is not None) self.species = set([speciesA, speciesB]) self.truePosA = 0 # with respect",
"falseNegatives(A). the second homology test in the mC output is B->A and the",
"self.precision = float(self.truePosB) / (self.truePosB + self.falsePos) if (self.truePosRegionB + self.falsePosRegion) == 0:",
"% options.xml) def addPairData(pairs, homTests, falsePosMode = False): \"\"\" given the dict `pairs'",
"'%s-%s' % (seqA, seqB) in pairs: # if '%s-%s' % (seqB, seqA) in",
"precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB,",
"associated documentation files (the \"Software\"), to deal # in the Software without restriction,",
"'%s-%s' % (seqA, seqB) in pairs: # raise RuntimeError('Duplicate pair found in `pairs\\'",
"if falsePosMode: # the second homology test in the xml, B->A p.truePosB +=",
"RuntimeError('Duplicate pair found in `pairs\\' dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' %",
"checkOptions(options, args, parser): if options.xml is None: parser.error('specify --xml') if not os.path.exists(options.xml): parser.error('--xml",
"OptionParser import os class ComparisonPair: def __init__(self, speciesA, speciesB): assert(speciesA is not None)",
"of this software and associated documentation files (the \"Software\"), to deal # in",
"obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg obsTruePosASelfOut += obsTruePosOutA",
"+ suffix + 'A', True) truePosSelfB = getItem(pairs, 'truePos' + suffix + 'B',",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"# We use the TP_A since FN comes from the A->B comparison if",
"FN comes from the A->B comparison if (self.truePosA + self.falseNeg) == 0: self.recall",
"ans def main(): usage = ('usage: %prog \\n\\n' '%prog \\n') parser = OptionParser(usage)",
"(precision * recall) / (precision + recall), truePosA, truePosB, falsePos, falseNeg) print '%35s,",
"'%.5f' % p.precision fStr = '%.5f' % (2 * ((p.precision * p.recall)/ (p.precision",
"isRegionMode(pairs): # if a BED was used by mafComparator then the xml will",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of",
"def __init__(self, speciesA, speciesB): assert(speciesA is not None) assert(speciesB is not None) self.species",
"recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s,",
"getItem(pairs, 'truePos' + suffix + 'B', False) falseNeg = getItem(pairs, 'falseNeg' + suffix,",
"0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosOutA = 0 obsTruePosOutB = 0",
"return pairs['%s-%s' % (seqA, seqB)] if '%s-%s' % (seqB, seqA) in pairs: #",
"obsFalsePos = 0 obsFalseNeg = 0 obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf",
"the dict `pairs' and a part of the xml tree `homTests', addPairData() walks",
"p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside)) def summarize(options): \"\"\" summarize() summizes the information",
"if the pair (seqA, seqB) is stored in pairs. Return None if not,",
"print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self)',",
"p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosRegionA obsTruePosBSelf += p.truePosRegionB obsFalsePosSelf += p.falsePosRegion obsFalseNegSelf += p.falseNegRegion",
"stored in options.xml \"\"\" try: tree = ET.parse(options.xml) except xml.parsers.expat.ExpatError: raise RuntimeError('Input xml,",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"# the numbers contained in the column. obsTruePosA = 0 obsTruePosB = 0",
"the Software without restriction, including without limitation the rights # to use, copy,",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"if '%s-%s' % (seqA, seqB) in pairs: # raise RuntimeError('Duplicate pair found in",
"'falseNegRegionOutside', False) falsePosOut = getItem(pairs, 'falsePosRegionOutside', False) truePosSelfOutA = getItem(pairs, 'truePosRegionOutsideA', True) truePosSelfOutB",
"person obtaining a copy # of this software and associated documentation files (the",
"(w/o self)', precision, recall, 2 * (precision * recall) / (precision + recall),",
"vs truePosMode: the first homology test in the mafComparator output is A->B and",
"falsePosSelfOut, falseNegSelfOut, pairs, options) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s'",
"+= p.falseNegRegionOutside else: obsTruePosA += p.truePosRegionA obsTruePosB += p.truePosRegionB obsFalsePos += p.falsePosRegion obsFalseNeg",
"fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside)) def summarize(options): \"\"\" summarize() summizes the information contained",
"def summarize(options): \"\"\" summarize() summizes the information contained in file stored in options.xml",
"(self.truePosRegionOutsideA + self.falseNegRegionOutside) == 0: self.recallRegionOutside = float('nan') else: self.recallRegionOutside = (float(self.truePosRegionOutsideA) /",
"t.attrib['sequenceB'].split('.')[0] if seqA == 'self' or seqB == 'self': continue if seqA ==",
"def findPair(seqA, seqB, pairs): # Check to see if the pair (seqA, seqB)",
"+= p.falseNeg else: obsTruePosA += p.truePosA obsTruePosB += p.truePosB obsFalsePos += p.falsePos obsFalseNeg",
"(obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosASelf, truePosASelf), (obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf, falsePosSelf), (obsFalseNegSelf,",
"else: precision = float(truePosB) / (truePosB + falsePos) if (truePosA + falseNeg) ==",
"above copyright notice and this permission notice shall be included in # all",
"((p.precisionRegionOutside * p.recallRegionOutside)/ (p.precisionRegionOutside + p.recallRegionOutside))) if not isRegionMode(pairs): print('%35s %10s %10.5f %10s",
"file stored in options.xml \"\"\" try: tree = ET.parse(options.xml) except xml.parsers.expat.ExpatError: raise RuntimeError('Input",
"THE SOFTWARE. ################################################## import xml.etree.ElementTree as ET import xml.parsers.expat from optparse import OptionParser",
"precStr = '%.5f' % p.precision fStr = '%.5f' % (2 * ((p.precision *",
"obsFalsePos obsFalseNegSelf += obsFalseNeg for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos,",
"# with respect to the B->A comparison self.falsePos = 0 self.falseNeg = 0",
"persons to whom the Software is # furnished to do so, subject to",
"if not isRegionMode(pairs): print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % (p.niceNames,",
"= 0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosOutA = 0 obsTruePosOutB =",
"conditions: # # The above copyright notice and this permission notice shall be",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A",
"%10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self) outside', precisionSelfOut,",
"OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"documentation files (the \"Software\"), to deal # in the Software without restriction, including",
"(truePosOutA + falseNegOut) precisionSelfOut = float(truePosSelfOutB) / (truePosSelfOutB + falsePosSelfOut) recallSelfOut = float(truePosSelfOutA)",
"x: pairs[x].niceNames) for pair in sortedPairs: p = pairs[pair] p.calcRecall() p.calcPrecision() if p.precision",
"or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"'%.5f' % (2 * ((p.precisionRegion * p.recallRegion)/ (p.precisionRegion + p.recallRegion))) if p.precisionRegionOutside ==",
"self.falseNegRegion = 0 self.truePosRegionOutsideA = 0 # wrt A->B self.truePosRegionOutsideB = 0 #",
"ans = 0 for pair in pairs: p = pairs[pair] if not alignSelf:",
"a BED was used by mafComparator then the xml will be in Region",
"continue ans += p.__dict__[item] return ans def main(): usage = ('usage: %prog \\n\\n'",
"notice and this permission notice shall be included in # all copies or",
"of charge, to any person obtaining a copy # of this software and",
"for comparisons using .bed files self.truePosRegionA = 0 # wrt A->B self.truePosRegionB =",
"% names[0] def calcPrecision(self): # Precision is calculated as # TP_B / (TP_B",
"truePositives(B) and falsePositives(B) (this is falsePosMode). \"\"\" hpTests = homTests.find('homologyPairTests') tests = hpTests.findall('homologyTest')",
"p.niceNames, precRegOutStr, p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside)) def summarize(options): \"\"\" summarize() summizes",
"ET.parse(options.xml) except xml.parsers.expat.ExpatError: raise RuntimeError('Input xml, %s is not a well formed xml",
"%10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self) outside', precisionOut,",
"obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg obsTruePosASelfOut += obsTruePosOutA obsTruePosBSelfOut += obsTruePosOutB obsFalsePosSelfOut",
"if (truePosB + falsePos) == 0: precision = float('nan') else: precision = float(truePosB)",
"and a part of the xml tree `homTests', addPairData() walks the tree to",
"be truePositives(A) and falseNegatives(A). the second homology test in the mC output is",
"% p.niceNames, precRegOutStr, p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside)) def summarize(options): \"\"\" summarize()",
"= float(truePosSelfB) / (truePosSelfB + falsePosSelf) if (truePosSelfA + falseNegSelf) == 0: recallSelf",
"-1.0 or (p.precisionRegionOutside + p.recallRegionOutside) == 0: precRegOutStr = 'nan' fRegOutStr = 'nan'",
"print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % ('%s outside' % p.niceNames,",
"+= p.falseNegRegion obsTruePosASelfOut += p.truePosRegionOutsideA obsTruePosBSelfOut += p.truePosRegionOutsideB obsFalsePosSelfOut += p.falsePosRegionOutside obsFalseNegSelfOut +=",
"= float(truePosSelfOutB) / (truePosSelfOutB + falsePosSelfOut) recallSelfOut = float(truePosSelfOutA) / (truePosSelfOutA + falseNegSelfOut)",
"sum of # the numbers contained in the column. obsTruePosA = 0 obsTruePosB",
"included in # all copies or substantial portions of the Software. # #",
"p.recallRegionOutside) == 0: precRegOutStr = 'nan' fRegOutStr = 'nan' else: precRegOutStr = '%.5f'",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"getItem(pairs, 'truePosRegionOutsideB', False) falseNegOut = getItem(pairs, 'falseNegRegionOutside', False) falsePosOut = getItem(pairs, 'falsePosRegionOutside', False)",
"inside', precision, recall, 2 * (precision * recall) / (precision + recall), truePosA,",
"0: self.precisionRegionOutside = float('nan') else: self.precisionRegionOutside = (float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB + self.falsePosRegionOutside)) def",
"and associated documentation files (the \"Software\"), to deal # in the Software without",
"obsTruePosA = 0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosOutA",
"float(self.truePosRegionB) / (self.truePosRegionB + self.falsePosRegion) if (self.truePosRegionOutsideB + self.falsePosRegionOutside) == 0: self.precisionRegionOutside =",
"+ falseNegSelf) == 0: recallSelf = float('nan') else: recallSelf = float(truePosSelfA) / (truePosSelfA",
"'%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('dataset', 'Precision', 'Recall', 'F-score',",
"numbers contained in the column. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos =",
"+ self.falsePos) == 0: self.precision = float('nan') else: self.precision = float(self.truePosB) / (self.truePosB",
"moved in here for convenience ################################################## # Copyright (C) 2009-2011 by # <NAME>",
"%9s, %9s, %9s, %9s' % ('Overall (w/ self) inside', precisionSelf, recallSelf, 2 *",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"if (self.truePosRegionB + self.falsePosRegion) == 0: self.precisionRegion = float('nan') else: self.precisionRegion = float(self.truePosRegionB)",
"1: self.niceNames = 'self-%s' % names[0] def calcPrecision(self): # Precision is calculated as",
"%s is not a well formed xml document.' % options.xml) root = tree.getroot()",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"%9d %9d %9d %9d' % (p.niceNames, precStr, p.recall, fStr, p.truePosA, p.truePosB, p.falsePos, p.falseNeg))",
"p.truePosRegionA, p.truePosRegionB, p.falsePosRegion, p.falseNegRegion)) print('%35s %10s %10.5f %10s %9d %9d %9d %9d' %",
"p.falsePosRegion obsFalseNeg += p.falseNegRegion obsTruePosOutA += p.truePosRegionOutsideA obsTruePosOutB += p.truePosRegionOutsideB obsFalsePosOut += p.falsePosRegionOutside",
"self.precisionRegionOutside = float('nan') else: self.precisionRegionOutside = (float(self.truePosRegionOutsideB) / (self.truePosRegionOutsideB + self.falsePosRegionOutside)) def calcRecall(self):",
"obsFalsePosSelf = 0 obsFalseNegSelf = 0 obsTruePosASelfOut = 0 obsTruePosBSelfOut = 0 obsFalsePosSelfOut",
"mafComparator output xml to summarize.') def checkOptions(options, args, parser): if options.xml is None:",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"(2 * ((p.precision * p.recall)/ (p.precision + p.recall))) if p.precisionRegion == -1.0 or",
"obsTruePosASelfOut += p.truePosRegionOutsideA obsTruePosBSelfOut += p.truePosRegionOutsideB obsFalsePosSelfOut += p.falsePosRegionOutside obsFalseNegSelfOut += p.falseNegRegionOutside else:",
"def sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf,",
"'FN (A)') if isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA,",
"0 obsTruePosOutA = 0 obsTruePosOutB = 0 obsFalsePosOut = 0 obsFalseNegOut = 0",
"pairs: # if '%s-%s' % (seqB, seqA) in pairs: # raise RuntimeError('Duplicate pair",
"part of the name self.niceNames = '-'.join(names) if len(names) == 1: self.niceNames =",
"% p.precision fStr = '%.5f' % (2 * ((p.precision * p.recall)/ (p.precision +",
"falseNegSelfOut), ]: assert(obs == exp) def sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosASelf, truePosBSelf, falsePosSelf,",
"key = lambda x: pairs[x].niceNames) for pair in sortedPairs: p = pairs[pair] p.calcRecall()",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"output xml to summarize.') def checkOptions(options, args, parser): if options.xml is None: parser.error('specify",
"= getItem(pairs, 'truePosRegionOutsideA', False) truePosOutB = getItem(pairs, 'truePosRegionOutsideB', False) falseNegOut = getItem(pairs, 'falseNegRegionOutside',",
"%10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self)', precision, recall,",
"exp) def sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosASelf, truePosBSelf, falsePosSelf, falseNegSelf, pairs, options): #",
"self.truePosRegionOutsideA = 0 # wrt A->B self.truePosRegionOutsideB = 0 # wrt B->A self.falsePosRegionOutside",
"= 0 obsFalseNegSelfOut = 0 for pair in pairs: p = pairs[pair] if",
"recall, 2 * (precision * recall) / (precision + recall), truePosA, truePosB, falsePos,",
"truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options):",
"int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: # the first homology test in the xml,",
"== 0: recallSelf = float('nan') else: recallSelf = float(truePosSelfA) / (truePosSelfA + falseNegSelf)",
"= float(self.truePosA) / (self.truePosA + self.falseNeg) if (self.truePosRegionA + self.falseNegRegion) == 0: self.recallRegion",
"falseNegSelf) == 0: recallSelf = float('nan') else: recallSelf = float(truePosSelfA) / (truePosSelfA +",
"0: recallSelf = float('nan') else: recallSelf = float(truePosSelfA) / (truePosSelfA + falseNegSelf) print",
"getItem(pairs, 'falseNeg' + suffix, True) if (truePosB + falsePos) == 0: precision =",
"Each column of numbers reported in the rows labeled \"Overall\" should be the",
"list(self.species) names = sorted(names, key = lambda x: x[3:]) # ignore the \"sim\"",
"p.recall)/ (p.precision + p.recall))) if p.precisionRegion == -1.0 or (p.precisionRegion + p.recallRegion) ==",
"+ falseNeg) if (truePosSelfB + falsePosSelf) == 0: precisionSelf = float('nan') else: precisionSelf",
"p.falseNeg)) else: print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % ('%s inside'",
"p.precisionRegionOutside fRegOutStr = '%.5f' % (2 * ((p.precisionRegionOutside * p.recallRegionOutside)/ (p.precisionRegionOutside + p.recallRegionOutside)))",
"recallOut)), truePosOutA, truePosOutA, falsePosOut, falseNegOut) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s,",
"('Overall (w/ self) inside', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) / (precisionSelf",
"getItem(pairs, 'truePosRegionOutsideA', False) truePosOutB = getItem(pairs, 'truePosRegionOutsideB', False) falseNegOut = getItem(pairs, 'falseNegRegionOutside', False)",
"`pairs' and a part of the xml tree `homTests', addPairData() walks the tree",
"comparison will be truePositives(B) and falsePositives(B) (this is falsePosMode). \"\"\" hpTests = homTests.find('homologyPairTests')",
"import xml.etree.ElementTree as ET import xml.parsers.expat from optparse import OptionParser import os class",
"0 # wrt A->B self.truePosRegionOutsideB = 0 # wrt B->A self.falsePosRegionOutside = 0",
"+ suffix + 'B', False) falseNeg = getItem(pairs, 'falseNeg' + suffix, False) falsePos",
"truePosB, falsePos, falseNeg) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' %",
"%9d' % ('%s inside' % p.niceNames, precRegStr, p.recallRegion, fRegStr, p.truePosRegionA, p.truePosRegionB, p.falsePosRegion, p.falseNegRegion))",
"self.precisionRegion = float('nan') else: self.precisionRegion = float(self.truePosRegionB) / (self.truePosRegionB + self.falsePosRegion) if (self.truePosRegionOutsideB",
"+= obsFalseNeg for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg,",
"falsePos) == 0: precision = float('nan') else: precision = float(truePosB) / (truePosB +",
"pairs: p = pairs[pair] if p.truePosRegionA > 0 or p.truePosRegionB > 0 or",
"in the rows labeled \"Overall\" should be the sum of # the numbers",
"USE OR OTHER DEALINGS IN # THE SOFTWARE. ################################################## import xml.etree.ElementTree as ET",
"# region numbers are for comparisons using .bed files self.truePosRegionA = 0 #",
"obsFalseNeg obsTruePosASelfOut += obsTruePosOutA obsTruePosBSelfOut += obsTruePosOutB obsFalsePosSelfOut += obsFalsePosOut obsFalseNegSelfOut += obsFalseNegOut",
"== 0: precisionSelf = float('nan') else: precisionSelf = float(truePosSelfB) / (truePosSelfB + falsePosSelf)",
"= 'nan' fRegStr = 'nan' else: precRegStr = '%.5f' % p.precisionRegion fRegStr =",
"dent earl, dearl (a) soe ucsc edu 22 November 2011 Simple utility to",
"(seqA, seqB)) return pairs['%s-%s' % (seqA, seqB)] if '%s-%s' % (seqB, seqA) in",
"truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosASelf, truePosASelf), (obsTruePosBSelf, truePosBSelf), (obsFalsePosSelf, falsePosSelf),",
"%9s, %9s' % ('Overall (w/o self) inside', precision, recall, 2 * (precision *",
"numbers reported in the rows labeled \"Overall\" should be the sum of #",
"in # all copies or substantial portions of the Software. # # THE",
"A->B comparison self.truePosB = 0 # with respect to the B->A comparison self.falsePos",
"getItem(pairs, item, alignSelf): ans = 0 for pair in pairs: p = pairs[pair]",
"falseNeg), (obsTruePosOutA, truePosOutA), (obsTruePosOutB, truePosOutB), (obsFalsePosOut, falsePosOut), (obsFalseNegOut, falseNegOut), (obsTruePosASelf, truePosSelfA), (obsTruePosBSelf, truePosSelfB),",
"%10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/ self) inside', precisionSelf,",
"tests to a region \"\"\" for pair in pairs: p = pairs[pair] if",
"p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA, seqB, pairs):",
"falseNeg = getItem(pairs, 'falseNeg' + suffix, False) falsePos = getItem(pairs, 'falsePos' + suffix,",
"(obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosOutA, truePosOutA), (obsTruePosOutB, truePosOutB), (obsFalsePosOut, falsePosOut), (obsFalseNegOut,",
"%9d %9d %9d' % ('%s outside' % p.niceNames, precRegOutStr, p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB,",
"%10s, %9s, %9s, %9s, %9s' % ('Overall (w/o self) inside', precision, recall, 2",
"== 0: recall = float('nan') else: recall = float(truePosA) / (truePosA + falseNeg)",
"homology test in the xml, B->A p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos += int(t.find('aggregateResults').find('all').attrib['totalFalse']) if",
"pair in sortedPairs: p = pairs[pair] p.calcRecall() p.calcPrecision() if p.precision == -1.0 or",
"= float(self.truePosRegionA) / (self.truePosRegionA + self.falseNegRegion) if (self.truePosRegionOutsideA + self.falseNegRegionOutside) == 0: self.recallRegionOutside",
"truePosOutA, falsePosOut, falseNegOut) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' %",
"= float(truePosB) / (truePosB + falsePos) if (truePosA + falseNeg) == 0: recall",
"soe ucsc edu 22 November 2011 Simple utility to summarize output of mafComparator",
"p is None: p = ComparisonPair(seqA, seqB) pairs['%s-%s' % (seqA, seqB)] = p",
"== 'aggregate': # ignore the aggregate sequences continue p = findPair(seqA, seqB, pairs)",
"free of charge, to any person obtaining a copy # of this software",
"stored in pairs. Return None if not, return the pair if so. if",
"((precisionSelf * recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) print '%35s,",
"does not exist' % options.xml) def addPairData(pairs, homTests, falsePosMode = False): \"\"\" given",
"hpTests.findall('homologyTest') for t in tests: seqA = t.attrib['sequenceA'].split('.')[0] seqB = t.attrib['sequenceB'].split('.')[0] if seqA",
"% ('dataset', 'Precision', 'Recall', 'F-score', 'TP (A)', 'TP (B)', 'FP (B)', 'FN (A)')",
"if p.truePosRegionA > 0 or p.truePosRegionB > 0 or p.falsePosRegion > 0 or",
"will be in Region mode suffix = 'Region' truePosOutA = getItem(pairs, 'truePosRegionOutsideA', False)",
"a part of the xml tree `homTests', addPairData() walks the tree to add",
"p.niceNames, precRegStr, p.recallRegion, fRegStr, p.truePosRegionA, p.truePosRegionB, p.falsePosRegion, p.falseNegRegion)) print('%35s %10s %10.5f %10s %9d",
"2009-2011 by # <NAME> (<EMAIL>, <EMAIL>) # ... and other members of the",
"inside', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) / (precisionSelf + recallSelf)), truePosSelfA,",
"the information contained in file stored in options.xml \"\"\" try: tree = ET.parse(options.xml)",
"\"\"\" Detects if a BED was used to restrict tests to a region",
"(seqA, seqB) in pairs: # raise RuntimeError('Duplicate pair found in `pairs\\' dict: %s-%s'",
"2 * ((precisionSelf * recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf)",
"+= p.__dict__[item] return ans def main(): usage = ('usage: %prog \\n\\n' '%prog \\n')",
"p.falseNegRegion > 0: return True def getItem(pairs, item, alignSelf): ans = 0 for",
"root.findall('homologyTests') pairs = {} addPairData(pairs, homTests[0]) addPairData(pairs, homTests[1], falsePosMode = True) if isRegionMode(pairs):",
"pair found in `pairs\\' dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqA,",
"0 obsFalsePosSelfOut = 0 obsFalseNegSelfOut = 0 for pair in pairs: p =",
"obsFalsePosOut += p.falsePosRegionOutside obsFalseNegOut += p.falseNegRegionOutside obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf",
"p = pairs[pair] p.calcRecall() p.calcPrecision() if p.precision == -1.0 or (p.precision + p.recall)",
"(self.truePosRegionA + self.falseNegRegion) == 0: self.recallRegion = float('nan') else: self.recallRegion = float(self.truePosRegionA) /",
"falsePosSelf, falseNegSelf, pairs, options): # Each column of numbers reported in the rows",
"be in Region mode suffix = 'Region' truePosOutA = getItem(pairs, 'truePosRegionOutsideA', False) truePosOutB",
"summarize(options): \"\"\" summarize() summizes the information contained in file stored in options.xml \"\"\"",
"[(obsTruePosA, truePosA), (obsTruePosB, truePosB), (obsFalsePos, falsePos), (obsFalseNeg, falseNeg), (obsTruePosOutA, truePosOutA), (obsTruePosOutB, truePosOutB), (obsFalsePosOut,",
"\\n') parser = OptionParser(usage) initOptions(parser) options, args = parser.parse_args() checkOptions(options, args, parser) summarize(options)",
"THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"%9d %9d %9d' % (p.niceNames, precStr, p.recall, fStr, p.truePosA, p.truePosB, p.falsePos, p.falseNeg)) else:",
"0: precisionSelf = float('nan') else: precisionSelf = float(truePosSelfB) / (truePosSelfB + falsePosSelf) if",
"file established regions p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside",
"% (seqA, seqB)) return pairs['%s-%s' % (seqA, seqB)] if '%s-%s' % (seqB, seqA)",
"tree = ET.parse(options.xml) except xml.parsers.expat.ExpatError: raise RuntimeError('Input xml, %s is not a well",
"self) inside', precision, recall, 2 * (precision * recall) / (precision + recall),",
"(this is falsePosMode). \"\"\" hpTests = homTests.find('homologyPairTests') tests = hpTests.findall('homologyTest') for t in",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #",
"SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"= 0 self.precision = None self.recall = None self.precisionRegion = None self.recallRegion =",
"+= obsFalsePos obsFalseNegSelf += obsFalseNeg obsTruePosASelfOut += obsTruePosOutA obsTruePosBSelfOut += obsTruePosOutB obsFalsePosSelfOut +=",
"THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ################################################## import xml.etree.ElementTree as",
"'FP (B)', 'FN (A)') if isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut,",
"Software, and to permit persons to whom the Software is # furnished to",
"output of mafComparator for use with alignathon competetition. \"\"\" # Note: Actually belongs",
"* p.recallRegion)/ (p.precisionRegion + p.recallRegion))) if p.precisionRegionOutside == -1.0 or (p.precisionRegionOutside + p.recallRegionOutside)",
"'F-score', 'TP (A)', 'TP (B)', 'FP (B)', 'FN (A)') if isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB,",
"names = sorted(names, key = lambda x: x[3:]) # ignore the \"sim\" part",
"RuntimeError('Input xml, %s is not a well formed xml document.' % options.xml) root",
"p.falseNegRegionOutside obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg",
"if isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf,",
"from optparse import OptionParser import os class ComparisonPair: def __init__(self, speciesA, speciesB): assert(speciesA",
"= float('nan') else: self.precision = float(self.truePosB) / (self.truePosB + self.falsePos) if (self.truePosRegionB +",
"# Note: Actually belongs to https://github.com/dentearl/mwgAlignAnalysis # but was moved in here for",
"obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB obsFalsePosSelf += obsFalsePos obsFalseNegSelf += obsFalseNeg for",
"obsTruePosOutA += p.truePosRegionOutsideA obsTruePosOutB += p.truePosRegionOutsideB obsFalsePosOut += p.falsePosRegionOutside obsFalseNegOut += p.falseNegRegionOutside obsTruePosASelf",
"0 obsFalseNeg = 0 obsTruePosOutA = 0 obsTruePosOutB = 0 obsFalsePosOut = 0",
"truePosOutB = getItem(pairs, 'truePosRegionOutsideB', False) falseNegOut = getItem(pairs, 'falseNegRegionOutside', False) falsePosOut = getItem(pairs,",
"falsePos, falseNeg, truePosASelf, truePosBSelf, falsePosSelf, falseNegSelf, pairs, options): # Each column of numbers",
"obsFalsePosSelfOut = 0 obsFalseNegSelfOut = 0 for pair in pairs: p = pairs[pair]",
"seqA == 'self' or seqB == 'self': continue if seqA == seqB: pass",
"/ (truePosSelfOutA + falseNegSelfOut) else: suffix = '' truePosA = getItem(pairs, 'truePos' +",
"%9d %9d %9d %9d' % ('%s outside' % p.niceNames, precRegOutStr, p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA,",
"truePosSelfOutA = getItem(pairs, 'truePosRegionOutsideA', True) truePosSelfOutB = getItem(pairs, 'truePosRegionOutsideB', True) falsePosSelfOut = getItem(pairs,",
"obsFalsePosSelf += p.falsePosRegion obsFalseNegSelf += p.falseNegRegion obsTruePosASelfOut += p.truePosRegionOutsideA obsTruePosBSelfOut += p.truePosRegionOutsideB obsFalsePosSelfOut",
"%10s %9d %9d %9d %9d' % ('%s outside' % p.niceNames, precRegOutStr, p.recallRegionOutside, fRegOutStr,",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"# the second homology test in the xml, B->A p.truePosB += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falsePos",
"%9s, %9s, %9s, %9s' % ('Overall (w/ self)', precisionSelf, recallSelf, 2 * ((precisionSelf",
"pair if so. if '%s-%s' % (seqA, seqB) in pairs: # if '%s-%s'",
"+= p.falsePos obsFalseNegSelf += p.falseNeg else: obsTruePosA += p.truePosA obsTruePosB += p.truePosB obsFalsePos",
"to the A->B comparison self.truePosB = 0 # with respect to the B->A",
"+ p.recallRegionOutside))) if not isRegionMode(pairs): print('%35s %10s %10.5f %10s %9d %9d %9d %9d'",
"obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosASelf = 0 obsTruePosBSelf",
"name self.niceNames = '-'.join(names) if len(names) == 1: self.niceNames = 'self-%s' % names[0]",
"+ FP) # We use the TP_B since FP comes from the B->A",
"0 # wrt B->A self.falsePosRegionOutside = 0 self.falseNegRegionOutside = 0 self.precision = None",
"# continue if t.attrib['sequenceA'] == 'aggregate' or t.attrib['sequenceB'] == 'aggregate': # ignore the",
"float('nan') else: recall = float(truePosA) / (truePosA + falseNeg) if (truePosSelfB + falsePosSelf)",
"%10s %10.5f %10s %9d %9d %9d %9d' % ('%s inside' % p.niceNames, precRegStr,",
"the B->A comparison if (self.truePosB + self.falsePos) == 0: self.precision = float('nan') else:",
"falseNeg) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/",
"p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA, seqB, pairs): # Check to see if the",
"* ((precisionSelf * recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) reportPairs(pairs,",
"the sum of # the numbers contained in the column. obsTruePosA = 0",
"'%.5f' % p.precisionRegion fRegStr = '%.5f' % (2 * ((p.precisionRegion * p.recallRegion)/ (p.precisionRegion",
"in the Software without restriction, including without limitation the rights # to use,",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS",
"in the column. obsTruePosA = 0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg",
"obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 obsTruePosASelfOut = 0 obsTruePosBSelfOut",
"#!/usr/bin/env python \"\"\" comparatorSummarizer.py dent earl, dearl (a) soe ucsc edu 22 November",
"t.attrib['sequenceB'] == 'aggregate': # ignore the aggregate sequences continue p = findPair(seqA, seqB,",
"precRegOutStr, p.recallRegionOutside, fRegOutStr, p.truePosRegionOutsideA, p.truePosRegionOutsideB, p.falsePosRegionOutside, p.falseNegRegionOutside)) def summarize(options): \"\"\" summarize() summizes the",
"p.truePosRegionOutsideB obsFalsePosOut += p.falsePosRegionOutside obsFalseNegOut += p.falseNegRegionOutside obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB",
"'nan' fRegStr = 'nan' else: precRegStr = '%.5f' % p.precisionRegion fRegStr = '%.5f'",
"in the mafComparator output is A->B and the results of this comparison will",
"% (seqB, seqA)] return None def reportPairs(pairs, options): print('') sortedPairs = sorted(pairs, key",
"'TP (A)', 'TP (B)', 'FP (B)', 'FN (A)') if isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB, falsePos,",
"== -1.0 or (p.precisionRegion + p.recallRegion) == 0: precRegStr = 'nan' fRegStr =",
"if p.precisionRegionOutside == -1.0 or (p.precisionRegionOutside + p.recallRegionOutside) == 0: precRegOutStr = 'nan'",
"self.recallRegionOutside = None names = list(self.species) names = sorted(names, key = lambda x:",
"'falsePos' + suffix, True) falseNegSelf = getItem(pairs, 'falseNeg' + suffix, True) if (truePosB",
"the tree to add data to the pairs dict. falsePosMode vs truePosMode: the",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE",
"options.xml is None: parser.error('specify --xml') if not os.path.exists(options.xml): parser.error('--xml %s does not exist'",
"MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"((precisionOut * recallOut) / (precisionOut + recallOut)), truePosOutA, truePosOutA, falsePosOut, falseNegOut) print '%35s,",
"+= obsFalsePos obsFalseNegSelf += obsFalseNeg for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB, truePosB),",
"else: # the first homology test in the xml, A->B p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue'])",
"truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut) else: sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf,",
"p.falseNeg else: obsTruePosA += p.truePosA obsTruePosB += p.truePosB obsFalsePos += p.falsePos obsFalseNeg +=",
"float('nan') else: self.recallRegion = float(self.truePosRegionA) / (self.truePosRegionA + self.falseNegRegion) if (self.truePosRegionOutsideA + self.falseNegRegionOutside)",
"truePosSelfB = getItem(pairs, 'truePos' + suffix + 'B', True) falsePosSelf = getItem(pairs, 'falsePos'",
"self.falsePos) if (self.truePosRegionB + self.falsePosRegion) == 0: self.precisionRegion = float('nan') else: self.precisionRegion =",
"%10s, %9s, %9s, %9s, %9s' % ('dataset', 'Precision', 'Recall', 'F-score', 'TP (A)', 'TP",
"and/or sell # copies of the Software, and to permit persons to whom",
"== 'self' or seqB == 'self': continue if seqA == seqB: pass #",
"for pair in sortedPairs: p = pairs[pair] p.calcRecall() p.calcPrecision() if p.precision == -1.0",
"% (2 * ((p.precisionRegionOutside * p.recallRegionOutside)/ (p.precisionRegionOutside + p.recallRegionOutside))) if not isRegionMode(pairs): print('%35s",
"raise RuntimeError('Input xml, %s is not a well formed xml document.' % options.xml)",
"truePosOutA), (obsTruePosOutB, truePosOutB), (obsFalsePosOut, falsePosOut), (obsFalseNegOut, falseNegOut), (obsTruePosASelf, truePosSelfA), (obsTruePosBSelf, truePosSelfB), (obsFalsePosSelf, falsePosSelf),",
"sanityCheck(truePosA, truePosB, falsePos, falseNeg, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, pairs, options) print '%35s, %10s,",
"is None: p = ComparisonPair(seqA, seqB) pairs['%s-%s' % (seqA, seqB)] = p if",
"= getItem(pairs, 'falseNeg' + suffix, True) if (truePosB + falsePos) == 0: precision",
"Region mode suffix = 'Region' truePosOutA = getItem(pairs, 'truePosRegionOutsideA', False) truePosOutB = getItem(pairs,",
"False) falsePosOut = getItem(pairs, 'falsePosRegionOutside', False) truePosSelfOutA = getItem(pairs, 'truePosRegionOutsideA', True) truePosSelfOutB =",
"obsTruePosBSelf += p.truePosB obsFalsePosSelf += p.falsePos obsFalseNegSelf += p.falseNeg else: obsTruePosA += p.truePosA",
"'' truePosA = getItem(pairs, 'truePos' + suffix + 'A', False) truePosB = getItem(pairs,",
"%9s, %9s' % ('Overall (w/ self) outside', precisionSelfOut, recallSelfOut, 2 * ((precisionSelfOut *",
"obsFalseNegSelfOut = 0 for pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf",
"= '%.5f' % (2 * ((p.precisionRegionOutside * p.recallRegionOutside)/ (p.precisionRegionOutside + p.recallRegionOutside))) if not",
"def getItem(pairs, item, alignSelf): ans = 0 for pair in pairs: p =",
"the second homology test in the mC output is B->A and the results",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"== -1.0 or (p.precisionRegionOutside + p.recallRegionOutside) == 0: precRegOutStr = 'nan' fRegOutStr =",
"p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: # the first homology test in the xml, A->B",
"ComparisonPair: def __init__(self, speciesA, speciesB): assert(speciesA is not None) assert(speciesB is not None)",
"comes from the B->A comparison if (self.truePosB + self.falsePos) == 0: self.precision =",
"found in `pairs\\' dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqB, seqA)]",
"/ (self.truePosRegionOutsideA + self.falseNegRegionOutside)) def initOptions(parser): parser.add_option('--xml', dest = 'xml', help = 'location",
"+= p.truePosB obsFalsePosSelf += p.falsePos obsFalseNegSelf += p.falseNeg else: obsTruePosA += p.truePosA obsTruePosB",
"(2 * ((p.precisionRegion * p.recallRegion)/ (p.precisionRegion + p.recallRegion))) if p.precisionRegionOutside == -1.0 or",
"def addPairData(pairs, homTests, falsePosMode = False): \"\"\" given the dict `pairs' and a",
"root = tree.getroot() homTests = root.findall('homologyTests') pairs = {} addPairData(pairs, homTests[0]) addPairData(pairs, homTests[1],",
"falseNegOut) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall (w/",
"+ falsePosSelf) if (truePosSelfA + falseNegSelf) == 0: recallSelf = float('nan') else: recallSelf",
"# # The above copyright notice and this permission notice shall be included",
"with respect to the A->B comparison self.truePosB = 0 # with respect to",
"pairs. Return None if not, return the pair if so. if '%s-%s' %",
"\"Software\"), to deal # in the Software without restriction, including without limitation the",
"region numbers are for comparisons using .bed files self.truePosRegionA = 0 # wrt",
"= 0 obsTruePosB = 0 obsFalsePos = 0 obsFalseNeg = 0 obsTruePosOutA =",
"None names = list(self.species) names = sorted(names, key = lambda x: x[3:]) #",
"'falsePosRegionOutside', False) truePosSelfOutA = getItem(pairs, 'truePosRegionOutsideA', True) truePosSelfOutB = getItem(pairs, 'truePosRegionOutsideB', True) falsePosSelfOut",
"'truePosRegionOutsideB', False) falseNegOut = getItem(pairs, 'falseNegRegionOutside', False) falsePosOut = getItem(pairs, 'falsePosRegionOutside', False) truePosSelfOutA",
"(obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut), ]: assert(obs == exp) def sanityCheck(truePosA, truePosB,",
"getItem(pairs, 'truePosRegionOutsideB', True) falsePosSelfOut = getItem(pairs, 'falsePosRegionOutside', True) falseNegSelfOut = getItem(pairs, 'falseNegRegionOutside', True)",
"os class ComparisonPair: def __init__(self, speciesA, speciesB): assert(speciesA is not None) assert(speciesB is",
"falsePositives(B) (this is falsePosMode). \"\"\" hpTests = homTests.find('homologyPairTests') tests = hpTests.findall('homologyTest') for t",
"should be the sum of # the numbers contained in the column. obsTruePosA",
"True) falseNegSelfOut = getItem(pairs, 'falseNegRegionOutside', True) precisionOut = float(truePosOutB) / (truePosOutB + falsePosOut)",
"not isRegionMode(pairs): print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % (p.niceNames, precStr,",
"IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"distribute, sublicense, and/or sell # copies of the Software, and to permit persons",
"+ suffix + 'B', True) falsePosSelf = getItem(pairs, 'falsePos' + suffix, True) falseNegSelf",
"the \"sim\" part of the name self.niceNames = '-'.join(names) if len(names) == 1:",
"def calcRecall(self): # Recall is calculated as # TP_A / (TP_A + FN)",
"False) truePosB = getItem(pairs, 'truePos' + suffix + 'B', False) falseNeg = getItem(pairs,",
"falsePosOut) recallOut = float(truePosOutA) / (truePosOutA + falseNegOut) precisionSelfOut = float(truePosSelfOutB) / (truePosSelfOutB",
"p.recall, fStr, p.truePosA, p.truePosB, p.falsePos, p.falseNeg)) else: print('%35s %10s %10.5f %10s %9d %9d",
"\"\"\" hpTests = homTests.find('homologyPairTests') tests = hpTests.findall('homologyTest') for t in tests: seqA =",
"+= int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA, seqB, pairs): # Check to see",
"= getItem(pairs, 'truePos' + suffix + 'B', True) falsePosSelf = getItem(pairs, 'falsePos' +",
"obsTruePosBSelfOut += p.truePosRegionOutsideB obsFalsePosSelfOut += p.falsePosRegionOutside obsFalseNegSelfOut += p.falseNegRegionOutside else: obsTruePosA += p.truePosRegionA",
"be the sum of # the numbers contained in the column corresponding to",
"wrt A->B self.truePosRegionB = 0 # wrt B->A self.falsePosRegion = 0 self.falseNegRegion =",
"not a well formed xml document.' % options.xml) root = tree.getroot() homTests =",
"parser.error('--xml %s does not exist' % options.xml) def addPairData(pairs, homTests, falsePosMode = False):",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"% (seqB, seqA) in pairs: # if '%s-%s' % (seqA, seqB) in pairs:",
"falsePos = getItem(pairs, 'falsePos' + suffix, False) truePosSelfA = getItem(pairs, 'truePos' + suffix",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"'falseNegRegionOutside', True) precisionOut = float(truePosOutB) / (truePosOutB + falsePosOut) recallOut = float(truePosOutA) /",
"t.find('aggregateResults').find('both') is not None: # bed file established regions p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion",
"the aggregate sequences continue p = findPair(seqA, seqB, pairs) if p is None:",
"None self.precisionRegion = None self.recallRegion = None self.precisionRegionOutside = None self.recallRegionOutside = None",
"self.falseNeg) == 0: self.recall = float('nan') else: self.recall = float(self.truePosA) / (self.truePosA +",
"truePosBSelf, falsePosSelf, falseNegSelf, pairs, options): # Each column of numbers reported in the",
"p.falseNegRegionOutside)) def summarize(options): \"\"\" summarize() summizes the information contained in file stored in",
"= '%.5f' % p.precisionRegion fRegStr = '%.5f' % (2 * ((p.precisionRegion * p.recallRegion)/",
"continue if seqA == seqB: pass # do not compare a genome to",
"falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options): #",
"homTests.find('homologyPairTests') tests = hpTests.findall('homologyTest') for t in tests: seqA = t.attrib['sequenceA'].split('.')[0] seqB =",
"portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"self.falseNegRegion) == 0: self.recallRegion = float('nan') else: self.recallRegion = float(self.truePosRegionA) / (self.truePosRegionA +",
"established regions p.truePosRegionB += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falsePosRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideB += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside +=",
"do so, subject to the following conditions: # # The above copyright notice",
"+= int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falsePosRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) else: # the first homology test in the",
"self.falseNegRegionOutside) == 0: self.recallRegionOutside = float('nan') else: self.recallRegionOutside = (float(self.truePosRegionOutsideA) / (self.truePosRegionOutsideA +",
"(A)') if isRegionMode(pairs): sanityCheckRegionMode(truePosA, truePosB, falsePos, falseNeg, truePosOutA, truePosOutB, falsePosOut, falseNegOut, truePosSelfA, truePosSelfB,",
"else: self.recallRegion = float(self.truePosRegionA) / (self.truePosRegionA + self.falseNegRegion) if (self.truePosRegionOutsideA + self.falseNegRegionOutside) ==",
"= True) if isRegionMode(pairs): # if a BED was used by mafComparator then",
"column of numbers reported in the rows labeled \"Overall\" should be the sum",
"a well formed xml document.' % options.xml) root = tree.getroot() homTests = root.findall('homologyTests')",
"obsTruePosB += p.truePosRegionB obsFalsePos += p.falsePosRegion obsFalseNeg += p.falseNegRegion obsTruePosOutA += p.truePosRegionOutsideA obsTruePosOutB",
"fRegOutStr = 'nan' else: precRegOutStr = '%.5f' % p.precisionRegionOutside fRegOutStr = '%.5f' %",
"os.path.exists(options.xml): parser.error('--xml %s does not exist' % options.xml) def addPairData(pairs, homTests, falsePosMode =",
"permit persons to whom the Software is # furnished to do so, subject",
"p.truePosB obsFalsePos += p.falsePos obsFalseNeg += p.falseNeg obsTruePosASelf += obsTruePosA obsTruePosBSelf += obsTruePosB",
"+ falsePos) == 0: precision = float('nan') else: precision = float(truePosB) / (truePosB",
"self) outside', precisionOut, recallOut, 2 * ((precisionOut * recallOut) / (precisionOut + recallOut)),",
"to itself # continue if t.attrib['sequenceA'] == 'aggregate' or t.attrib['sequenceB'] == 'aggregate': #",
"respect to the A->B comparison self.truePosB = 0 # with respect to the",
"= 0 self.falseNegRegionOutside = 0 self.precision = None self.recall = None self.precisionRegion =",
"= getItem(pairs, 'falseNeg' + suffix, False) falsePos = getItem(pairs, 'falsePos' + suffix, False)",
"summarize() summizes the information contained in file stored in options.xml \"\"\" try: tree",
"= p if falsePosMode: # the second homology test in the xml, B->A",
"isRegionMode(pairs): print('%35s %10s %10.5f %10s %9d %9d %9d %9d' % (p.niceNames, precStr, p.recall,",
"= 'nan' else: precRegOutStr = '%.5f' % p.precisionRegionOutside fRegOutStr = '%.5f' % (2",
"% ('Overall (w/o self) inside', precision, recall, 2 * (precision * recall) /",
"0 obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0",
"parser = OptionParser(usage) initOptions(parser) options, args = parser.parse_args() checkOptions(options, args, parser) summarize(options) if",
"or (p.precisionRegion + p.recallRegion) == 0: precRegStr = 'nan' fRegStr = 'nan' else:",
"2 * (precision * recall) / (precision + recall), truePosA, truePosB, falsePos, falseNeg)",
"comparison if (self.truePosA + self.falseNeg) == 0: self.recall = float('nan') else: self.recall =",
"sortedPairs: p = pairs[pair] p.calcRecall() p.calcPrecision() if p.precision == -1.0 or (p.precision +",
"True) precisionOut = float(truePosOutB) / (truePosOutB + falsePosOut) recallOut = float(truePosOutA) / (truePosOutA",
"+= p.truePosRegionB obsFalsePos += p.falsePosRegion obsFalseNeg += p.falseNegRegion obsTruePosOutA += p.truePosRegionOutsideA obsTruePosOutB +=",
"truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options) print '%35s, %10s, %10s, %10s, %9s, %9s,",
"falsePosSelf, falseNegSelf) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' % ('Overall",
"to add data to the pairs dict. falsePosMode vs truePosMode: the first homology",
"B->A comparison if (self.truePosB + self.falsePos) == 0: self.precision = float('nan') else: self.precision",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS",
"* recallSelf) / (precisionSelf + recallSelf)), truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf) print '%35s, %10s,",
"= '-'.join(names) if len(names) == 1: self.niceNames = 'self-%s' % names[0] def calcPrecision(self):",
"is A->B and the results of this comparison will be truePositives(A) and falseNegatives(A).",
"%9s, %9s, %9s, %9s' % ('Overall (w/o self)', precision, recall, 2 * (precision",
"self.recall = float(self.truePosA) / (self.truePosA + self.falseNeg) if (self.truePosRegionA + self.falseNegRegion) == 0:",
"= float(self.truePosRegionB) / (self.truePosRegionB + self.falsePosRegion) if (self.truePosRegionOutsideB + self.falsePosRegionOutside) == 0: self.precisionRegionOutside",
"p.truePosRegionA obsTruePosBSelf += p.truePosRegionB obsFalsePosSelf += p.falsePosRegion obsFalseNegSelf += p.falseNegRegion obsTruePosASelfOut += p.truePosRegionOutsideA",
"the rows labeled \"Overall\" should be the sum of # the numbers contained",
"falsePosOut, falseNegOut, truePosSelfA, truePosSelfB, falsePosSelf, falseNegSelf, truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut, pairs, options) print",
"'truePos' + suffix + 'A', False) truePosB = getItem(pairs, 'truePos' + suffix +",
"= 0 # wrt B->A self.falsePosRegion = 0 self.falseNegRegion = 0 self.truePosRegionOutsideA =",
"('usage: %prog \\n\\n' '%prog \\n') parser = OptionParser(usage) initOptions(parser) options, args = parser.parse_args()",
"for use with alignathon competetition. \"\"\" # Note: Actually belongs to https://github.com/dentearl/mwgAlignAnalysis #",
"obsTruePosBSelfOut = 0 obsFalsePosSelfOut = 0 obsFalseNegSelfOut = 0 for pair in pairs:",
"0: precision = float('nan') else: precision = float(truePosB) / (truePosB + falsePos) if",
"so. if '%s-%s' % (seqA, seqB) in pairs: # if '%s-%s' % (seqB,",
"comes from the A->B comparison if (self.truePosA + self.falseNeg) == 0: self.recall =",
"False) truePosOutB = getItem(pairs, 'truePosRegionOutsideB', False) falseNegOut = getItem(pairs, 'falseNegRegionOutside', False) falsePosOut =",
"None self.recallRegionOutside = None names = list(self.species) names = sorted(names, key = lambda",
"self.recallRegion = float(self.truePosRegionA) / (self.truePosRegionA + self.falseNegRegion) if (self.truePosRegionOutsideA + self.falseNegRegionOutside) == 0:",
"= sorted(names, key = lambda x: x[3:]) # ignore the \"sim\" part of",
"truePosSelfOutB = getItem(pairs, 'truePosRegionOutsideB', True) falsePosSelfOut = getItem(pairs, 'falsePosRegionOutside', True) falseNegSelfOut = getItem(pairs,",
"\"Overall\" should be the sum of # the numbers contained in the column",
"in `pairs\\' dict: %s-%s' % (seqA, seqB)) return pairs['%s-%s' % (seqB, seqA)] return",
"\"sim\" part of the name self.niceNames = '-'.join(names) if len(names) == 1: self.niceNames",
"in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosRegionA obsTruePosBSelf += p.truePosRegionB",
"for pair in pairs: p = pairs[pair] if p.niceNames.startswith('self-'): obsTruePosASelf += p.truePosA obsTruePosBSelf",
"self.falseNegRegionOutside)) def initOptions(parser): parser.add_option('--xml', dest = 'xml', help = 'location of mafComparator output",
"continue if t.attrib['sequenceA'] == 'aggregate' or t.attrib['sequenceB'] == 'aggregate': # ignore the aggregate",
"= float(truePosSelfOutA) / (truePosSelfOutA + falseNegSelfOut) else: suffix = '' truePosA = getItem(pairs,",
"recall = float('nan') else: recall = float(truePosA) / (truePosA + falseNeg) if (truePosSelfB",
"the first homology test in the xml, A->B p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg +=",
"%10s %10.5f %10s %9d %9d %9d %9d' % ('%s outside' % p.niceNames, precRegOutStr,",
"genome to itself # continue if t.attrib['sequenceA'] == 'aggregate' or t.attrib['sequenceB'] == 'aggregate':",
"falseNegSelf, pairs, options) print '%35s, %10s, %10s, %10s, %9s, %9s, %9s, %9s' %",
"(w/ self) inside', precisionSelf, recallSelf, 2 * ((precisionSelf * recallSelf) / (precisionSelf +",
"region \"\"\" for pair in pairs: p = pairs[pair] if p.truePosRegionA > 0",
"calculated as # TP_A / (TP_A + FN) # We use the TP_A",
"%10s, %10s, %9s, %9s, %9s, %9s' % ('dataset', 'Precision', 'Recall', 'F-score', 'TP (A)',",
"%10.5f %10s %9d %9d %9d %9d' % ('%s inside' % p.niceNames, precRegStr, p.recallRegion,",
"%9d %9d' % (p.niceNames, precStr, p.recall, fStr, p.truePosA, p.truePosB, p.falsePos, p.falseNeg)) else: print('%35s",
"self.precision = None self.recall = None self.precisionRegion = None self.recallRegion = None self.precisionRegionOutside",
"* ((precisionSelfOut * recallSelfOut) / (precisionSelfOut + recallSelfOut)), truePosSelfOutA, truePosSelfOutB, falsePosSelfOut, falseNegSelfOut) else:",
"= 0 obsFalseNeg = 0 obsTruePosASelf = 0 obsTruePosBSelf = 0 obsFalsePosSelf =",
"other members of the Reconstruction Team of <NAME>'s # lab (BME Dept. UCSC)",
"is not a well formed xml document.' % options.xml) root = tree.getroot() homTests",
"int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA, seqB, pairs): # Check to see if",
"results of this comparison will be truePositives(A) and falseNegatives(A). the second homology test",
"truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut), ]: assert(obs == exp) def sanityCheck(truePosA,",
"regions p.truePosRegionA += int(t.find('aggregateResults').find('both').attrib['totalTrue']) p.falseNegRegion += int(t.find('aggregateResults').find('both').attrib['totalFalse']) p.truePosRegionOutsideA += int(t.find('aggregateResults').find('neither').attrib['totalTrue']) p.falseNegRegionOutside += int(t.find('aggregateResults').find('neither').attrib['totalFalse'])",
"if so. if '%s-%s' % (seqA, seqB) in pairs: # if '%s-%s' %",
"%9d %9d %9d' % ('%s inside' % p.niceNames, precRegStr, p.recallRegion, fRegStr, p.truePosRegionA, p.truePosRegionB,",
"= None self.recall = None self.precisionRegion = None self.recallRegion = None self.precisionRegionOutside =",
"%10s %10.5f %10s %9d %9d %9d %9d' % (p.niceNames, precStr, p.recall, fStr, p.truePosA,",
"= pairs[pair] if p.truePosRegionA > 0 or p.truePosRegionB > 0 or p.falsePosRegion >",
"p.truePosB, p.falsePos, p.falseNeg)) else: print('%35s %10s %10.5f %10s %9d %9d %9d %9d' %",
"(obsFalseNegSelf, falseNegSelf), (obsTruePosASelfOut, truePosSelfOutA), (obsTruePosBSelfOut, truePosSelfOutB), (obsFalsePosSelfOut, falsePosSelfOut), (obsFalseNegSelfOut, falseNegSelfOut), ]: assert(obs ==",
"the TP_A since FN comes from the A->B comparison if (self.truePosA + self.falseNeg)",
"class ComparisonPair: def __init__(self, speciesA, speciesB): assert(speciesA is not None) assert(speciesB is not",
"= 0 obsFalsePosSelf = 0 obsFalseNegSelf = 0 for pair in pairs: p",
"set([speciesA, speciesB]) self.truePosA = 0 # with respect to the A->B comparison self.truePosB",
"suffix, True) if (truePosB + falsePos) == 0: precision = float('nan') else: precision",
"p = pairs[pair] if not alignSelf: if len(p.species) == 1: continue ans +=",
"hereby granted, free of charge, to any person obtaining a copy # of",
"= float('nan') else: self.recallRegion = float(self.truePosRegionA) / (self.truePosRegionA + self.falseNegRegion) if (self.truePosRegionOutsideA +",
"precStr = 'nan' fStr = 'nan' else: precStr = '%.5f' % p.precision fStr",
"= 0 obsFalsePosOut = 0 obsFalseNegOut = 0 obsTruePosASelf = 0 obsTruePosBSelf =",
"obsFalsePosSelfOut += obsFalsePosOut obsFalseNegSelfOut += obsFalseNegOut for obs, exp in [(obsTruePosA, truePosA), (obsTruePosB,",
"'truePosRegionOutsideA', False) truePosOutB = getItem(pairs, 'truePosRegionOutsideB', False) falseNegOut = getItem(pairs, 'falseNegRegionOutside', False) falsePosOut",
"comparison self.falsePos = 0 self.falseNeg = 0 # region numbers are for comparisons",
"%9s, %9s, %9s' % ('Overall (w/ self)', precisionSelf, recallSelf, 2 * ((precisionSelf *",
"+= int(t.find('aggregateResults').find('neither').attrib['totalFalse']) def findPair(seqA, seqB, pairs): # Check to see if the pair",
"the B->A comparison self.falsePos = 0 self.falseNeg = 0 # region numbers are",
"# the first homology test in the xml, A->B p.truePosA += int(t.find('aggregateResults').find('all').attrib['totalTrue']) p.falseNeg",
"% (seqB, seqA) in pairs: # raise RuntimeError('Duplicate pair found in `pairs\\' dict:",
"= getItem(pairs, 'falseNegRegionOutside', False) falsePosOut = getItem(pairs, 'falsePosRegionOutside', False) truePosSelfOutA = getItem(pairs, 'truePosRegionOutsideA',",
"%9s, %9s, %9s' % ('Overall (w/ self) outside', precisionSelfOut, recallSelfOut, 2 * ((precisionSelfOut",
"mafComparator for use with alignathon competetition. \"\"\" # Note: Actually belongs to https://github.com/dentearl/mwgAlignAnalysis"
] |
[
"block.to_python({ 'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url == page.url assert value.link_text",
"be empty if the field is not required }) # This should not",
"{ 'times': [ {'weekday': 4}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 10))",
"datetime.date(2017, 12, 13) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday': 6}) == datetime.date(2017, 12, 17)",
"block = LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link': [{'type': 'url', 'value':",
"This must not be empty if the field is required }) with pytest.raises(ValidationError):",
"'', 'link': [] }) assert value.link_url == '' assert value.link_text == '' @pytest.mark.django_db",
"{ 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, match, ], } assert",
"wagtail_extensions.blocks import ( DepartmentBlock, ImagesBlock, LinkBlock, OpeningTimeBlock, OpeningTimesBlock, PhoneBlock ) @pytest.mark.django_db @pytest.fixture def",
"mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None, None) is None def test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({},",
"OpeningTimeBlock() openingtime.clean({'start': '08:00', 'end': '20:00', 'date': '2017-01-01'}) def test_openingtime_block_to_python_empty(): openingtime = OpeningTimeBlock() openingtime.to_python({'label':",
"ImagesBlock() assert block.get_context({'images': ['an image', 'another image', 'yet another image']})['column_width'] == 4 def",
"Page(title='A test page', slug=\"test\") homepage.add_child(instance=page) return page def test_department_block_clean_invalid(): department = DepartmentBlock() with",
"referenced by a PageChooserBlock has been deleted, the block value will be None.",
"= OpeningTimesBlock.time_keyfunc(value) assert out == (False, datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby): value =",
"'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text == '/hello/' def test_link_block_with_missing_streamblock():",
"# Homepage is created by Wagtail's initial migrations # But let's create our",
"True def test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({}) is None @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday': 2})",
"= block.to_python({ 'link': [{'type': 'page', 'value': None}] }) assert value.link_url == '' assert",
"OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00', 'weekday': '1'}) def test_openingtime_block_clean_no_weekday_or_date(): openingtime =",
"'end': '10:00'}) out = OpeningTimesBlock.time_keyfunc(value) assert out == (False, datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def",
"datetime.date(2017, 12, 17) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday': 7}) is None def test_openingtimes_block_time_keyfunc_specific():",
"= OpeningTimeBlock() openingtime.clean({'start': '08:00', 'end': '20:00', 'date': '2017-01-01'}) def test_openingtime_block_to_python_empty(): openingtime = OpeningTimeBlock()",
"datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby): value = {} mocked_groupby.return_value = [('first', [1, 4, 5]),",
"{'times': [1, 5, 10]} with patch.object(openingtimes, 'group_times') as mocked_group,\\ patch.object(openingtimes, 'opening_today') as mocked_today:",
"} assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) == match def test_openingtimes_block_get_time_for_date_times_no_match(): value = {",
"patch from django.core.exceptions import ValidationError from freezegun import freeze_time from phonenumber_field.phonenumber import PhoneNumber",
"DepartmentBlock() value = department.get_prep_value({'phones': ['', '+447528712345', '']}) assert value['phones'] == ['+447528712345'] def test_link_block_with_url():",
"OpeningTimeBlock() value = openingtime.to_python({'weekday': '7'}) assert value['label'] == OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label(): openingtime =",
"\"\"\" If a page referenced by a PageChooserBlock has been deleted, the block",
"= OpeningTimeBlock() label = 'Easter sunday' value = openingtime.to_python({'weekday': '7', 'label': label}) assert",
"World' def test_link_block_clean_for_required(): block = LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link':",
"'/hello/' def test_link_block_with_missing_streamblock(): block = LinkBlock() value = block.to_python({ 'text': '', 'link': []",
"'another image', 'yet another image']})['column_width'] == 4 def test_images_block_get_context_empty_list(): block = ImagesBlock() assert",
"been deleted, the block value will be None. \"\"\" block = LinkBlock() value",
"= OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00', 'weekday': '1'}) def test_openingtime_block_clean_no_weekday_or_date(): openingtime",
"Homepage is created by Wagtail's initial migrations # But let's create our own",
"test_link_block_with_url(): block = LinkBlock() value = block.to_python({ 'link': [{'type': 'url', 'value': '/hello/'}] })",
"value = block.to_python({ 'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url == page.url",
"from unittest.mock import patch from django.core.exceptions import ValidationError from freezegun import freeze_time from",
"{} mocked_groupby.return_value = [('first', [1, 4, 5]), ('second', [7, 10])] out = OpeningTimesBlock.group_times(value)",
"value.link_text == '/hello/' def test_link_block_with_url_and_text(): block = LinkBlock() value = block.to_python({ 'text': 'Hello",
"'weekday': ''}) # Pass without error def test_openingtime_block_to_python_cast_weekday(): openingtime = OpeningTimeBlock() value =",
"4}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 10)) == match def test_openingtimes_block_get_time_for_date_times_weekday():",
"= OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00'}) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid(): openingtime =",
"block value will be None. \"\"\" block = LinkBlock() value = block.to_python({ 'link':",
"openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017, 6, 28)) assert out == mocked_get.return_value def test_openingtimes_block_get_context(): openingtimes =",
"'' def test_images_block_get_context(): block = ImagesBlock() assert block.get_context({'images': ['an image', 'another image', 'yet",
"@freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'}) def test_openingtime_block_clean_end_before_start(): openingtime",
"OpeningTimeBlock.next_date({}) is None @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday': 2}) == datetime.date(2017, 12, 13)",
"our own child page for testing with. homepage = Page.objects.get(url_path='/home/') page = Page(title='A",
"'value': None}] }) assert value.link_url == '' assert value.link_text == '' @pytest.mark.django_db def",
"out == [[1, 4, 5], [7, 10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None,",
"as mocked_get: value = 'test' out = openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017, 6, 28)) assert",
"is None def test_openingtimes_block_time_keyfunc_specific(): openingtime = OpeningTimeBlock() value = openingtime.to_python({}) with patch.object(openingtime, 'single_date',",
"datetime.date(2017, 12, 10)) is None def test_openingtimes_block_get_time_for_date_times_date(): match = {'date': datetime.date(2017, 12, 10)}",
"is value def test_openingtimes_block_time_keyfunc_non_specific(): value = OpeningTimeBlock().to_python({'closed': False, 'start': '5:00', 'end': '10:00'}) out",
"LinkBlock() value = block.to_python({ 'text': '', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert",
"testing with. homepage = Page.objects.get(url_path='/home/') page = Page(title='A test page', slug=\"test\") homepage.add_child(instance=page) return",
"department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers(): department = DepartmentBlock() value = department.get_prep_value({'phones': ['', '+447528712345', '']}) assert",
"'Hello World' def test_link_block_with_empty_string_text(): block = LinkBlock() value = block.to_python({ 'text': '', 'link':",
"block.to_python({ 'text': '', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/'",
"= Page(title='A test page', slug=\"test\") homepage.add_child(instance=page) return page def test_department_block_clean_invalid(): department = DepartmentBlock()",
"empty if the field is not required }) # This should not raise",
"OpeningTimeBlock.next_date({'weekday': 7}) is None def test_openingtimes_block_time_keyfunc_specific(): openingtime = OpeningTimeBlock() value = openingtime.to_python({}) with",
"'', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text",
"= department.get_prep_value({'phones': ['', '+447528712345', '']}) assert value['phones'] == ['+447528712345'] def test_link_block_with_url(): block =",
"== page.url assert value.link_text == 'Hello World' def test_link_block_clean_for_required(): block = LinkBlock() value",
"department = DepartmentBlock() department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers(): department = DepartmentBlock() value = department.get_prep_value({'phones': ['',",
"'<NAME>', 'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url == page.url assert value.link_text",
"openingtime = OpeningTimeBlock() openingtime.clean({'start': '08:00', 'end': '20:00', 'date': '2017-01-01'}) def test_openingtime_block_to_python_empty(): openingtime =",
"== '' @pytest.mark.django_db def test_link_block_with_page_and_text(page): block = LinkBlock() value = block.to_python({ 'text': '<NAME>',",
"test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12, 10)) is None def test_openingtimes_block_get_time_for_date_times_date(): match = {'date':",
"OpeningTimeBlock, OpeningTimesBlock, PhoneBlock ) @pytest.mark.django_db @pytest.fixture def page(): # Homepage is created by",
"test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date': 'some date'}) == True def test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday': 7}) ==",
"{'weekday': 2}, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) is None @freeze_time('2017-06-28') def",
"'single_date', return_value=True): out = OpeningTimesBlock.time_keyfunc(value) assert out is value def test_openingtimes_block_time_keyfunc_non_specific(): value =",
"'phones': ['+447528712345']}) def test_department_block_to_python_empty(): department = DepartmentBlock() department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers(): department = DepartmentBlock()",
"block.to_python({ 'text': 'Hello World', 'link': [] # This must not be empty if",
"openingtimes = OpeningTimesBlock with patch.object(openingtimes, 'get_time_for_date') as mocked_get: value = 'test' out =",
"openingtime.clean({'start': '08:00', 'end': '20:00', 'date': '2017-01-01'}) def test_openingtime_block_to_python_empty(): openingtime = OpeningTimeBlock() openingtime.to_python({'label': '',",
"12, 10)}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) == match def",
"@freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid(): openingtime = OpeningTimeBlock() openingtime.clean({'start': '08:00', 'end': '20:00', 'date': '2017-01-01'}) def",
"5, 10]} with patch.object(openingtimes, 'group_times') as mocked_group,\\ patch.object(openingtimes, 'opening_today') as mocked_today: ctx =",
"assert value.link_url == page.url assert value.link_text == page.title @pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page): \"\"\" If",
"def test_openingtimes_block_opening_today(): openingtimes = OpeningTimesBlock with patch.object(openingtimes, 'get_time_for_date') as mocked_get: value = 'test'",
"value['label'] == OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label(): openingtime = OpeningTimeBlock() label = 'Easter sunday' value",
"test_openingtime_block_clean_valid(): openingtime = OpeningTimeBlock() openingtime.clean({'start': '08:00', 'end': '20:00', 'date': '2017-01-01'}) def test_openingtime_block_to_python_empty(): openingtime",
"def test_link_block_with_url_and_text(): block = LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link': [{'type':",
"'start': None, 'end': None, 'weekday': ''}) # Pass without error def test_openingtime_block_to_python_cast_weekday(): openingtime",
"test_openingtimes_block_time_keyfunc_specific(): openingtime = OpeningTimeBlock() value = openingtime.to_python({}) with patch.object(openingtime, 'single_date', return_value=True): out =",
"value = {'times': [1, 5, 10]} with patch.object(openingtimes, 'group_times') as mocked_group,\\ patch.object(openingtimes, 'opening_today')",
"def test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday': 7}) is None def test_openingtimes_block_time_keyfunc_specific(): openingtime = OpeningTimeBlock() value",
"assert OpeningTimeBlock.next_date({}) is None @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday': 2}) == datetime.date(2017, 12,",
"== '' @pytest.mark.django_db def test_link_block_with_page(page): block = LinkBlock() value = block.to_python({ 'link': [{'type':",
"'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text == 'Hello World'",
"@pytest.mark.django_db def test_link_block_with_page(page): block = LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value':",
"], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) == match def test_openingtimes_block_get_time_for_date_times_no_match(): value =",
"= openingtime.to_python({'weekday': '5'}) assert value['weekday'] == 5 def test_openingtime_block_to_python_public_label(): openingtime = OpeningTimeBlock() value",
"OpeningTimeBlock().to_python({'closed': False, 'start': '5:00', 'end': '10:00'}) out = OpeningTimesBlock.time_keyfunc(value) assert out == (False,",
"block.to_python({ 'text': 'Hello World', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url ==",
"World' def test_link_block_with_empty_string_text(): block = LinkBlock() value = block.to_python({ 'text': '', 'link': [{'type':",
"= block.to_python({ 'text': 'Hello World', 'link': [] # This must not be empty",
"def test_link_block_with_url(): block = LinkBlock() value = block.to_python({ 'link': [{'type': 'url', 'value': '/hello/'}]",
"LinkBlock, OpeningTimeBlock, OpeningTimesBlock, PhoneBlock ) @pytest.mark.django_db @pytest.fixture def page(): # Homepage is created",
"test_link_block_with_empty_string_text(): block = LinkBlock() value = block.to_python({ 'text': '', 'link': [{'type': 'url', 'value':",
"['', '+447528712345', '']}) assert value['phones'] == ['+447528712345'] def test_link_block_with_url(): block = LinkBlock() value",
"'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, match, ], } assert OpeningTimesBlock.get_time_for_date(value,",
"{'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, {'weekday': 2}, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017,",
"assert value['phones'] == ['+447528712345'] def test_link_block_with_url(): block = LinkBlock() value = block.to_python({ 'link':",
"label def test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({}) == False def test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date': 'some date'})",
"== True def test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday': 7}) == True def test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({})",
"patch.object(openingtimes, 'opening_today') as mocked_today: ctx = openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5, 10]) mocked_today.assert_called_once_with(value) assert ctx['times']",
"'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text == '/hello/' def test_link_block_with_url_and_text():",
"'' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page(page): block = LinkBlock() value =",
"OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None, None) is None def test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017,",
"test_openingtimes_block_get_time_for_date_times_weekday(): match = {'weekday': 6} value = { 'times': [ {'weekday': 4}, {'date':",
"10)) is None def test_openingtimes_block_get_time_for_date_times_date(): match = {'date': datetime.date(2017, 12, 10)} value =",
"value = department.get_prep_value({'phones': ['', '+447528712345', '']}) assert value['phones'] == ['+447528712345'] def test_link_block_with_url(): block",
"DepartmentBlock() department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers(): department = DepartmentBlock() value = department.get_prep_value({'phones': ['', '+447528712345', '']})",
"value def test_openingtimes_block_time_keyfunc_non_specific(): value = OpeningTimeBlock().to_python({'closed': False, 'start': '5:00', 'end': '10:00'}) out =",
"['+447528712345'] def test_link_block_with_url(): block = LinkBlock() value = block.to_python({ 'link': [{'type': 'url', 'value':",
"'page', 'value': page.pk}] }) assert value.link_url == page.url assert value.link_text == 'Hello World'",
"== ['+447528712345'] def test_link_block_with_url(): block = LinkBlock() value = block.to_python({ 'link': [{'type': 'url',",
"mocked_today: ctx = openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5, 10]) mocked_today.assert_called_once_with(value) assert ctx['times'] == mocked_group.return_value assert",
"openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5, 10]) mocked_today.assert_called_once_with(value) assert ctx['times'] == mocked_group.return_value assert ctx['today'] == mocked_today.return_value",
"def test_link_block_with_page_that_no_longer_exists(page): \"\"\" If a page referenced by a PageChooserBlock has been deleted,",
"'value': page.pk}] }) assert value.link_url == page.url assert value.link_text == page.title @pytest.mark.django_db def",
"mocked_get: value = 'test' out = openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017, 6, 28)) assert out",
"openingtime.to_python({'weekday': '7'}) assert value['label'] == OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label(): openingtime = OpeningTimeBlock() label =",
"block.clean(value) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'}) def test_openingtime_block_clean_end_before_start():",
"5 def test_openingtime_block_to_python_public_label(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '7'}) assert value['label'] ==",
"4, 5]), ('second', [7, 10])] out = OpeningTimesBlock.group_times(value) assert out == [[1, 4,",
"page for testing with. homepage = Page.objects.get(url_path='/home/') page = Page(title='A test page', slug=\"test\")",
"assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page_and_text(page): block = LinkBlock() value = block.to_python({",
"= block.to_python({ 'text': '<NAME>', 'link': [] # Can be empty if the field",
"OpeningTimesBlock, PhoneBlock ) @pytest.mark.django_db @pytest.fixture def page(): # Homepage is created by Wagtail's",
"= DepartmentBlock() department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers(): department = DepartmentBlock() value = department.get_prep_value({'phones': ['', '+447528712345',",
"def test_openingtimes_block_time_keyfunc_specific(): openingtime = OpeningTimeBlock() value = openingtime.to_python({}) with patch.object(openingtime, 'single_date', return_value=True): out",
"department = DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>', 'phones': ['+447528712345']}) def test_department_block_to_python_empty(): department = DepartmentBlock() department.to_python({})",
"6}) == datetime.date(2017, 12, 17) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday': 7}) is None",
"4, 5], [7, 10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None, None) is None",
"10]) mocked_today.assert_called_once_with(value) assert ctx['times'] == mocked_group.return_value assert ctx['today'] == mocked_today.return_value def test_phone_block_get_prep_value(): phone",
"= LinkBlock() value = block.to_python({ 'text': '', 'link': [] }) assert value.link_url ==",
"child page for testing with. homepage = Page.objects.get(url_path='/home/') page = Page(title='A test page',",
"OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00'}) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid(): openingtime = OpeningTimeBlock()",
"def test_department_block_clean_invalid(): department = DepartmentBlock() with pytest.raises(ValidationError): department.clean({}) def test_department_block_clean_valid_with_both(): department = DepartmentBlock()",
"4}, {'date': datetime.date(2017, 12, 10)}, {'weekday': 2}, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12,",
"deleted, the block value will be None. \"\"\" block = LinkBlock() value =",
"test_openingtime_block_clean_date_in_past(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'}) def test_openingtime_block_clean_end_before_start(): openingtime = OpeningTimeBlock()",
"'link': [{'type': 'page', 'value': None}] }) assert value.link_url == '' assert value.link_text ==",
"openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '7'}) assert value['label'] == OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label():",
"= OpeningTimesBlock() value = {'times': [1, 5, 10]} with patch.object(openingtimes, 'group_times') as mocked_group,\\",
"ctx = openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5, 10]) mocked_today.assert_called_once_with(value) assert ctx['times'] == mocked_group.return_value assert ctx['today']",
"def test_openingtime_block_clean_end_before_start(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00', 'weekday': '1'})",
"{'weekday': 6} value = { 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)},",
"This should not raise an exception block.clean(value) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past(): openingtime = OpeningTimeBlock()",
"= openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5, 10]) mocked_today.assert_called_once_with(value) assert ctx['times'] == mocked_group.return_value assert ctx['today'] ==",
"'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, {'weekday': 2}, ], } assert",
"value = block.to_python({ 'link': [{'type': 'page', 'value': None}] }) assert value.link_url == ''",
"'1'}) def test_openingtime_block_clean_no_weekday_or_date(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00'}) @freeze_time(\"2017-01-01\")",
"mocked_group.return_value assert ctx['today'] == mocked_today.return_value def test_phone_block_get_prep_value(): phone = PhoneBlock() number = PhoneNumber.from_string('+447528712345')",
"test_link_block_with_missing_streamblock(): block = LinkBlock() value = block.to_python({ 'text': '', 'link': [] }) assert",
"4}, {'date': datetime.date(2017, 12, 10)}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17))",
"value.link_url == '' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page(page): block = LinkBlock()",
"def page(): # Homepage is created by Wagtail's initial migrations # But let's",
"block = LinkBlock(required=False) value = block.to_python({ 'text': '<NAME>', 'link': [] # Can be",
"phone.to_python('') == '' def test_images_block_get_context(): block = ImagesBlock() assert block.get_context({'images': ['an image', 'another",
"'end': '08:00'}) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid(): openingtime = OpeningTimeBlock() openingtime.clean({'start': '08:00', 'end': '20:00', 'date':",
"True def test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday': 7}) == True def test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({}) is",
"[] # Can be empty if the field is not required }) #",
"value = { 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, {'weekday': 2},",
"assert OpeningTimeBlock.next_date({'weekday': 6}) == datetime.date(2017, 12, 17) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday': 7})",
"= LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link': [] # This must",
"for testing with. homepage = Page.objects.get(url_path='/home/') page = Page(title='A test page', slug=\"test\") homepage.add_child(instance=page)",
"is None @freeze_time('2017-06-28') def test_openingtimes_block_opening_today(): openingtimes = OpeningTimesBlock with patch.object(openingtimes, 'get_time_for_date') as mocked_get:",
"value.link_url == '/hello/' assert value.link_text == '/hello/' def test_link_block_with_url_and_text(): block = LinkBlock() value",
"value['weekday'] == 5 def test_openingtime_block_to_python_public_label(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '7'}) assert",
"test_openingtimes_block_group_times(mocked_groupby): value = {} mocked_groupby.return_value = [('first', [1, 4, 5]), ('second', [7, 10])]",
"number_str = phone.get_prep_value(number) assert number_str == '+447528712345' def test_phone_block_to_python(): phone = PhoneBlock() number",
"10]} with patch.object(openingtimes, 'group_times') as mocked_group,\\ patch.object(openingtimes, 'opening_today') as mocked_today: ctx = openingtimes.get_context(value)",
"assert value.link_text == page.title @pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page): \"\"\" If a page referenced by",
"pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'}) def test_openingtime_block_clean_end_before_start(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end':",
"None @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday': 2}) == datetime.date(2017, 12, 13) @freeze_time(\"2017-12-13\") def",
"pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00'}) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid(): openingtime = OpeningTimeBlock() openingtime.clean({'start': '08:00',",
"value.link_text == '' @pytest.mark.django_db def test_link_block_with_page_and_text(page): block = LinkBlock() value = block.to_python({ 'text':",
"'/hello/' assert value.link_text == 'Hello World' def test_link_block_with_empty_string_text(): block = LinkBlock() value =",
"= block.to_python({ 'text': 'Hello World', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url",
"assert value.link_url == '/hello/' assert value.link_text == 'Hello World' def test_link_block_with_empty_string_text(): block =",
"value.link_url == page.url assert value.link_text == 'Hello World' def test_link_block_clean_for_required(): block = LinkBlock()",
"OpeningTimeBlock() label = 'Easter sunday' value = openingtime.to_python({'weekday': '7', 'label': label}) assert value['label']",
"def test_link_block_with_page_and_text(page): block = LinkBlock() value = block.to_python({ 'text': '<NAME>', 'link': [{'type': 'page',",
"block.get_context({'images': ['an image', 'another image', 'yet another image']})['column_width'] == 4 def test_images_block_get_context_empty_list(): block",
"image', 'another image', 'yet another image']})['column_width'] == 4 def test_images_block_get_context_empty_list(): block = ImagesBlock()",
"OpeningTimeBlock() openingtime.to_python({'label': '', 'date': None, 'closed': False, 'start': None, 'end': None, 'weekday': ''})",
"'+447528712345' def test_phone_block_to_python(): phone = PhoneBlock() number = phone.to_python('+447528712345') assert number == PhoneNumber.from_string('+447528712345')",
"assert value.link_url == '' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page_and_text(page): block =",
"None, 'closed': False, 'start': None, 'end': None, 'weekday': ''}) # Pass without error",
"field is required }) with pytest.raises(ValidationError): block.clean(value) def test_link_block_clean_for_not_required(): block = LinkBlock(required=False) value",
"'text': '', 'link': [] }) assert value.link_url == '' assert value.link_text == ''",
"[{'type': 'page', 'value': None}] }) assert value.link_url == '' assert value.link_text == ''",
"= {'date': datetime.date(2017, 12, 10)} value = { 'times': [ {'weekday': 4}, match,",
"== '/hello/' def test_link_block_with_missing_streamblock(): block = LinkBlock() value = block.to_python({ 'text': '', 'link':",
"\"\"\" block = LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value': None}] })",
"def test_openingtimes_block_get_time_for_date_times_weekday(): match = {'weekday': 6} value = { 'times': [ {'weekday': 4},",
"own child page for testing with. homepage = Page.objects.get(url_path='/home/') page = Page(title='A test",
"test_phone_block_get_prep_value(): phone = PhoneBlock() number = PhoneNumber.from_string('+447528712345') number_str = phone.get_prep_value(number) assert number_str ==",
"World', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text",
"patch.object(openingtimes, 'group_times') as mocked_group,\\ patch.object(openingtimes, 'opening_today') as mocked_today: ctx = openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5,",
"import PhoneNumber from wagtail.core.models import Page from wagtail_extensions.blocks import ( DepartmentBlock, ImagesBlock, LinkBlock,",
"created by Wagtail's initial migrations # But let's create our own child page",
"import ( DepartmentBlock, ImagesBlock, LinkBlock, OpeningTimeBlock, OpeningTimesBlock, PhoneBlock ) @pytest.mark.django_db @pytest.fixture def page():",
"[7, 10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None, None) is None def test_openingtimes_block_get_time_for_date_no_times():",
"= PhoneNumber.from_string('+447528712345') number_str = phone.get_prep_value(number) assert number_str == '+447528712345' def test_phone_block_to_python(): phone =",
"openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00'}) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid(): openingtime",
"= phone.get_prep_value(number) assert number_str == '+447528712345' def test_phone_block_to_python(): phone = PhoneBlock() number =",
"'yet another image']})['column_width'] == 4 def test_images_block_get_context_empty_list(): block = ImagesBlock() assert block.get_context({})['column_width'] ==",
"if the field is not required }) # This should not raise an",
"def test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday': 7}) == True def test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({}) is None",
"value = block.to_python({ 'text': '<NAME>', 'link': [] # Can be empty if the",
"is created by Wagtail's initial migrations # But let's create our own child",
"value = openingtime.to_python({'weekday': '5'}) assert value['weekday'] == 5 def test_openingtime_block_to_python_public_label(): openingtime = OpeningTimeBlock()",
"assert out is value def test_openingtimes_block_time_keyfunc_non_specific(): value = OpeningTimeBlock().to_python({'closed': False, 'start': '5:00', 'end':",
"= { 'times': [ {'weekday': 4}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12,",
"assert OpeningTimeBlock.next_date({'weekday': 7}) is None def test_openingtimes_block_time_keyfunc_specific(): openingtime = OpeningTimeBlock() value = openingtime.to_python({})",
"'/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text == '/hello/' def test_link_block_with_url_and_text(): block",
"== OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label(): openingtime = OpeningTimeBlock() label = 'Easter sunday' value =",
"DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>', 'phones': ['+447528712345']}) def test_department_block_to_python_empty(): department = DepartmentBlock() department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers():",
"OpeningTimeBlock.next_date({'weekday': 2}) == datetime.date(2017, 12, 13) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday': 6}) ==",
"import Page from wagtail_extensions.blocks import ( DepartmentBlock, ImagesBlock, LinkBlock, OpeningTimeBlock, OpeningTimesBlock, PhoneBlock )",
"}) assert value.link_url == '' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page_and_text(page): block",
"10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None, None) is None def test_openingtimes_block_get_time_for_date_no_times(): assert",
"pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00', 'weekday': '1'}) def test_openingtime_block_clean_no_weekday_or_date(): openingtime = OpeningTimeBlock() with",
"Page.objects.get(url_path='/home/') page = Page(title='A test page', slug=\"test\") homepage.add_child(instance=page) return page def test_department_block_clean_invalid(): department",
"LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url ==",
"5]), ('second', [7, 10])] out = OpeningTimesBlock.group_times(value) assert out == [[1, 4, 5],",
"# This should not raise an exception block.clean(value) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past(): openingtime =",
"{'weekday': 4}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 10)) == match def",
"def test_link_block_clean_for_not_required(): block = LinkBlock(required=False) value = block.to_python({ 'text': '<NAME>', 'link': [] #",
"'/hello/' assert value.link_text == '/hello/' def test_link_block_with_url_and_text(): block = LinkBlock() value = block.to_python({",
"slug=\"test\") homepage.add_child(instance=page) return page def test_department_block_clean_invalid(): department = DepartmentBlock() with pytest.raises(ValidationError): department.clean({}) def",
"with. homepage = Page.objects.get(url_path='/home/') page = Page(title='A test page', slug=\"test\") homepage.add_child(instance=page) return page",
"}) assert value.link_url == page.url assert value.link_text == page.title @pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page): \"\"\"",
"= LinkBlock() value = block.to_python({ 'text': '<NAME>', 'link': [{'type': 'page', 'value': page.pk}] })",
"{'date': datetime.date(2017, 12, 10)}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) ==",
"block = LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value': page.pk}] }) assert",
"28)) assert out == mocked_get.return_value def test_openingtimes_block_get_context(): openingtimes = OpeningTimesBlock() value = {'times':",
"with pytest.raises(ValidationError): department.clean({}) def test_department_block_clean_valid_with_both(): department = DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>', 'phones': ['+447528712345']}) def",
"number = phone.to_python('+447528712345') assert number == PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty(): phone = PhoneBlock() assert",
"'Hello World', 'link': [] # This must not be empty if the field",
"('second', [7, 10])] out = OpeningTimesBlock.group_times(value) assert out == [[1, 4, 5], [7,",
"test_images_block_get_context(): block = ImagesBlock() assert block.get_context({'images': ['an image', 'another image', 'yet another image']})['column_width']",
"OpeningTimeBlock.single_date({'weekday': 7}) == True def test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({}) is None @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today():",
"is not required }) # This should not raise an exception block.clean(value) @freeze_time(\"2017-01-01\")",
"def test_openingtime_block_to_python_empty(): openingtime = OpeningTimeBlock() openingtime.to_python({'label': '', 'date': None, 'closed': False, 'start': None,",
"OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label(): openingtime = OpeningTimeBlock() label = 'Easter sunday' value = openingtime.to_python({'weekday':",
"= 'test' out = openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017, 6, 28)) assert out == mocked_get.return_value",
"'08:00', 'weekday': '1'}) def test_openingtime_block_clean_no_weekday_or_date(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end':",
"'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text == '/hello/' def",
"'20:00', 'date': '2017-01-01'}) def test_openingtime_block_to_python_empty(): openingtime = OpeningTimeBlock() openingtime.to_python({'label': '', 'date': None, 'closed':",
"None def test_openingtimes_block_get_time_for_date_times_date(): match = {'date': datetime.date(2017, 12, 10)} value = { 'times':",
"None def test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12, 10)) is None def test_openingtimes_block_get_time_for_date_times_date(): match",
"test_link_block_with_page_that_no_longer_exists(page): \"\"\" If a page referenced by a PageChooserBlock has been deleted, the",
"False def test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date': 'some date'}) == True def test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday':",
"[ {'weekday': 4}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 10)) == match",
"value = 'test' out = openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017, 6, 28)) assert out ==",
"import ValidationError from freezegun import freeze_time from phonenumber_field.phonenumber import PhoneNumber from wagtail.core.models import",
"If a page referenced by a PageChooserBlock has been deleted, the block value",
"== (False, datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby): value = {} mocked_groupby.return_value = [('first',",
"be None. \"\"\" block = LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value':",
"mocked_get.assert_called_once_with(value, datetime.date(2017, 6, 28)) assert out == mocked_get.return_value def test_openingtimes_block_get_context(): openingtimes = OpeningTimesBlock()",
"def test_openingtimes_block_get_time_for_date_times_no_match(): value = { 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)},",
"LinkBlock() value = block.to_python({ 'text': '<NAME>', 'link': [{'type': 'page', 'value': page.pk}] }) assert",
"pytest from unittest.mock import patch from django.core.exceptions import ValidationError from freezegun import freeze_time",
"test_openingtime_block_clean_no_weekday_or_date(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00'}) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid():",
"page.title @pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page): \"\"\" If a page referenced by a PageChooserBlock has",
"@pytest.fixture def page(): # Homepage is created by Wagtail's initial migrations # But",
"exception block.clean(value) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'}) def",
"= PhoneBlock() assert phone.to_python('') == '' def test_images_block_get_context(): block = ImagesBlock() assert block.get_context({'images':",
"2}) == datetime.date(2017, 12, 13) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday': 6}) == datetime.date(2017,",
"patch.object(openingtime, 'single_date', return_value=True): out = OpeningTimesBlock.time_keyfunc(value) assert out is value def test_openingtimes_block_time_keyfunc_non_specific(): value",
"test_link_block_clean_for_not_required(): block = LinkBlock(required=False) value = block.to_python({ 'text': '<NAME>', 'link': [] # Can",
"out is value def test_openingtimes_block_time_keyfunc_non_specific(): value = OpeningTimeBlock().to_python({'closed': False, 'start': '5:00', 'end': '10:00'})",
"# Can be empty if the field is not required }) # This",
"= LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link': [{'type': 'url', 'value': '/hello/'}]",
"an exception block.clean(value) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'})",
"label = 'Easter sunday' value = openingtime.to_python({'weekday': '7', 'label': label}) assert value['label'] ==",
"7}) is None def test_openingtimes_block_time_keyfunc_specific(): openingtime = OpeningTimeBlock() value = openingtime.to_python({}) with patch.object(openingtime,",
"test_phone_block_to_python(): phone = PhoneBlock() number = phone.to_python('+447528712345') assert number == PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty():",
"}) assert value.link_url == '/hello/' assert value.link_text == '/hello/' def test_link_block_with_missing_streamblock(): block =",
"== '' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page(page): block = LinkBlock() value",
"== mocked_today.return_value def test_phone_block_get_prep_value(): phone = PhoneBlock() number = PhoneNumber.from_string('+447528712345') number_str = phone.get_prep_value(number)",
"def test_department_block_clean_valid_with_both(): department = DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>', 'phones': ['+447528712345']}) def test_department_block_to_python_empty(): department =",
"17) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday': 7}) is None def test_openingtimes_block_time_keyfunc_specific(): openingtime =",
"= OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'}) def test_openingtime_block_clean_end_before_start(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError):",
"django.core.exceptions import ValidationError from freezegun import freeze_time from phonenumber_field.phonenumber import PhoneNumber from wagtail.core.models",
"'', 'date': None, 'closed': False, 'start': None, 'end': None, 'weekday': ''}) # Pass",
"'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text ==",
"not be empty if the field is required }) with pytest.raises(ValidationError): block.clean(value) def",
"assert value.link_text == '/hello/' def test_link_block_with_missing_streamblock(): block = LinkBlock() value = block.to_python({ 'text':",
"}) assert value.link_url == '/hello/' assert value.link_text == '/hello/' def test_link_block_with_url_and_text(): block =",
"required }) # This should not raise an exception block.clean(value) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past():",
"'start': '5:00', 'end': '10:00'}) out = OpeningTimesBlock.time_keyfunc(value) assert out == (False, datetime.time(5), datetime.time(10))",
"@freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday': 7}) is None def test_openingtimes_block_time_keyfunc_specific(): openingtime = OpeningTimeBlock()",
"12, 17)) is None @freeze_time('2017-06-28') def test_openingtimes_block_opening_today(): openingtimes = OpeningTimesBlock with patch.object(openingtimes, 'get_time_for_date')",
"out = OpeningTimesBlock.group_times(value) assert out == [[1, 4, 5], [7, 10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc)",
"page.url assert value.link_text == page.title @pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page): \"\"\" If a page referenced",
"= OpeningTimeBlock() openingtime.to_python({'label': '', 'date': None, 'closed': False, 'start': None, 'end': None, 'weekday':",
"'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text == 'Hello World' def",
"[] }) assert value.link_url == '' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page(page):",
"by a PageChooserBlock has been deleted, the block value will be None. \"\"\"",
"OpeningTimeBlock.next_date({'weekday': 6}) == datetime.date(2017, 12, 17) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday': 7}) is",
"def test_link_block_with_page(page): block = LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value': page.pk}]",
"PhoneNumber.from_string('+447528712345') number_str = phone.get_prep_value(number) assert number_str == '+447528712345' def test_phone_block_to_python(): phone = PhoneBlock()",
"create our own child page for testing with. homepage = Page.objects.get(url_path='/home/') page =",
"'date': None, 'closed': False, 'start': None, 'end': None, 'weekday': ''}) # Pass without",
"# This must not be empty if the field is required }) with",
"'08:00', 'end': '20:00', 'date': '2017-01-01'}) def test_openingtime_block_to_python_empty(): openingtime = OpeningTimeBlock() openingtime.to_python({'label': '', 'date':",
"def test_openingtimes_block_time_keyfunc_non_specific(): value = OpeningTimeBlock().to_python({'closed': False, 'start': '5:00', 'end': '10:00'}) out = OpeningTimesBlock.time_keyfunc(value)",
"def test_openingtimes_block_get_context(): openingtimes = OpeningTimesBlock() value = {'times': [1, 5, 10]} with patch.object(openingtimes,",
"[7, 10])] out = OpeningTimesBlock.group_times(value) assert out == [[1, 4, 5], [7, 10]]",
"match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 10)) == match def test_openingtimes_block_get_time_for_date_times_weekday(): match",
"@pytest.mark.django_db @pytest.fixture def page(): # Homepage is created by Wagtail's initial migrations #",
"number = PhoneNumber.from_string('+447528712345') number_str = phone.get_prep_value(number) assert number_str == '+447528712345' def test_phone_block_to_python(): phone",
"from freezegun import freeze_time from phonenumber_field.phonenumber import PhoneNumber from wagtail.core.models import Page from",
"value = block.to_python({ 'text': 'Hello World', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert",
"value = block.to_python({ 'text': 'Hello World', 'link': [] # This must not be",
"assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page(page): block = LinkBlock() value = block.to_python({",
"'end': '08:00', 'weekday': '1'}) def test_openingtime_block_clean_no_weekday_or_date(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00',",
"test_openingtime_block_to_python_public_label(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '7'}) assert value['label'] == OpeningTimeBlock.PUBLIC_LABEL def",
"value = OpeningTimeBlock().to_python({'closed': False, 'start': '5:00', 'end': '10:00'}) out = OpeningTimesBlock.time_keyfunc(value) assert out",
"= block.to_python({ 'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url == page.url assert",
"= {} mocked_groupby.return_value = [('first', [1, 4, 5]), ('second', [7, 10])] out =",
"patch.object(openingtimes, 'get_time_for_date') as mocked_get: value = 'test' out = openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017, 6,",
"assert ctx['today'] == mocked_today.return_value def test_phone_block_get_prep_value(): phone = PhoneBlock() number = PhoneNumber.from_string('+447528712345') number_str",
"assert value['label'] == OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label(): openingtime = OpeningTimeBlock() label = 'Easter sunday'",
"return page def test_department_block_clean_invalid(): department = DepartmentBlock() with pytest.raises(ValidationError): department.clean({}) def test_department_block_clean_valid_with_both(): department",
"test_department_block_clean_invalid(): department = DepartmentBlock() with pytest.raises(ValidationError): department.clean({}) def test_department_block_clean_valid_with_both(): department = DepartmentBlock() department.clean({'name':'Test',",
"assert number == PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty(): phone = PhoneBlock() assert phone.to_python('') == ''",
"required }) with pytest.raises(ValidationError): block.clean(value) def test_link_block_clean_for_not_required(): block = LinkBlock(required=False) value = block.to_python({",
"not required }) # This should not raise an exception block.clean(value) @freeze_time(\"2017-01-01\") def",
"= phone.to_python('+447528712345') assert number == PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty(): phone = PhoneBlock() assert phone.to_python('')",
"'page', 'value': None}] }) assert value.link_url == '' assert value.link_text == '' @pytest.mark.django_db",
"= OpeningTimeBlock() value = openingtime.to_python({'weekday': '7'}) assert value['label'] == OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label(): openingtime",
"OpeningTimeBlock() value = openingtime.to_python({'weekday': '5'}) assert value['weekday'] == 5 def test_openingtime_block_to_python_public_label(): openingtime =",
"test_openingtimes_block_get_time_for_date_times_no_match(): value = { 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, {'weekday':",
"test_link_block_with_page_and_text(page): block = LinkBlock() value = block.to_python({ 'text': '<NAME>', 'link': [{'type': 'page', 'value':",
"LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link': [] # This must not",
"empty if the field is required }) with pytest.raises(ValidationError): block.clean(value) def test_link_block_clean_for_not_required(): block",
"assert value['weekday'] == 5 def test_openingtime_block_to_python_public_label(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '7'})",
"datetime import pytest from unittest.mock import patch from django.core.exceptions import ValidationError from freezegun",
"== '/hello/' assert value.link_text == '/hello/' def test_link_block_with_url_and_text(): block = LinkBlock() value =",
"mocked_group.assert_called_once_with([1, 5, 10]) mocked_today.assert_called_once_with(value) assert ctx['times'] == mocked_group.return_value assert ctx['today'] == mocked_today.return_value def",
"= PhoneBlock() number = PhoneNumber.from_string('+447528712345') number_str = phone.get_prep_value(number) assert number_str == '+447528712345' def",
"value.link_text == '' @pytest.mark.django_db def test_link_block_with_page(page): block = LinkBlock() value = block.to_python({ 'link':",
"def test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({}) == False def test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date': 'some date'}) ==",
"value = openingtime.to_python({'weekday': '7', 'label': label}) assert value['label'] == label def test_openingtime_block_single_date_empty(): assert",
"== datetime.date(2017, 12, 17) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday': 7}) is None def",
"12, 10)} value = { 'times': [ {'weekday': 4}, match, ], } assert",
"'/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text == '/hello/' def test_link_block_with_missing_streamblock(): block",
"value.link_text == 'Hello World' def test_link_block_clean_for_required(): block = LinkBlock() value = block.to_python({ 'text':",
"value will be None. \"\"\" block = LinkBlock() value = block.to_python({ 'link': [{'type':",
"page.pk}] }) assert value.link_url == page.url assert value.link_text == 'Hello World' def test_link_block_clean_for_required():",
"test_phone_block_to_python_empty(): phone = PhoneBlock() assert phone.to_python('') == '' def test_images_block_get_context(): block = ImagesBlock()",
"'end': None, 'weekday': ''}) # Pass without error def test_openingtime_block_to_python_cast_weekday(): openingtime = OpeningTimeBlock()",
"= openingtime.to_python({}) with patch.object(openingtime, 'single_date', return_value=True): out = OpeningTimesBlock.time_keyfunc(value) assert out is value",
"[{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text == '/hello/'",
"datetime.date(2017, 12, 17)) is None @freeze_time('2017-06-28') def test_openingtimes_block_opening_today(): openingtimes = OpeningTimesBlock with patch.object(openingtimes,",
"value = block.to_python({ 'text': '', 'link': [] }) assert value.link_url == '' assert",
"def test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date': 'some date'}) == True def test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday': 7})",
"block = LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value': None}] }) assert",
"PhoneBlock ) @pytest.mark.django_db @pytest.fixture def page(): # Homepage is created by Wagtail's initial",
"== [[1, 4, 5], [7, 10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None, None)",
"= LinkBlock(required=False) value = block.to_python({ 'text': '<NAME>', 'link': [] # Can be empty",
"assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12, 10)) is None def test_openingtimes_block_get_time_for_date_times_date(): match = {'date': datetime.date(2017,",
"block = LinkBlock() value = block.to_python({ 'text': '', 'link': [] }) assert value.link_url",
"= ImagesBlock() assert block.get_context({'images': ['an image', 'another image', 'yet another image']})['column_width'] == 4",
"None}] }) assert value.link_url == '' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page_and_text(page):",
"(False, datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby): value = {} mocked_groupby.return_value = [('first', [1,",
"with patch.object(openingtimes, 'group_times') as mocked_group,\\ patch.object(openingtimes, 'opening_today') as mocked_today: ctx = openingtimes.get_context(value) mocked_group.assert_called_once_with([1,",
"'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url == page.url assert value.link_text ==",
"OpeningTimesBlock.group_times(value) assert out == [[1, 4, 5], [7, 10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty():",
"5], [7, 10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None, None) is None def",
"def test_openingtimes_block_group_times(mocked_groupby): value = {} mocked_groupby.return_value = [('first', [1, 4, 5]), ('second', [7,",
"image', 'yet another image']})['column_width'] == 4 def test_images_block_get_context_empty_list(): block = ImagesBlock() assert block.get_context({})['column_width']",
"test_link_block_clean_for_required(): block = LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link': [] #",
"import freeze_time from phonenumber_field.phonenumber import PhoneNumber from wagtail.core.models import Page from wagtail_extensions.blocks import",
"phone = PhoneBlock() number = PhoneNumber.from_string('+447528712345') number_str = phone.get_prep_value(number) assert number_str == '+447528712345'",
"OpeningTimesBlock.time_keyfunc(value) assert out is value def test_openingtimes_block_time_keyfunc_non_specific(): value = OpeningTimeBlock().to_python({'closed': False, 'start': '5:00',",
"PhoneBlock() assert phone.to_python('') == '' def test_images_block_get_context(): block = ImagesBlock() assert block.get_context({'images': ['an",
"from django.core.exceptions import ValidationError from freezegun import freeze_time from phonenumber_field.phonenumber import PhoneNumber from",
"Wagtail's initial migrations # But let's create our own child page for testing",
"ctx['times'] == mocked_group.return_value assert ctx['today'] == mocked_today.return_value def test_phone_block_get_prep_value(): phone = PhoneBlock() number",
"another image']})['column_width'] == 4 def test_images_block_get_context_empty_list(): block = ImagesBlock() assert block.get_context({})['column_width'] == 12",
"from wagtail_extensions.blocks import ( DepartmentBlock, ImagesBlock, LinkBlock, OpeningTimeBlock, OpeningTimesBlock, PhoneBlock ) @pytest.mark.django_db @pytest.fixture",
"is None @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday': 2}) == datetime.date(2017, 12, 13) @freeze_time(\"2017-12-13\")",
"block = LinkBlock() value = block.to_python({ 'link': [{'type': 'url', 'value': '/hello/'}] }) assert",
"{'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12,",
"'date': '2017-01-01'}) def test_openingtime_block_to_python_empty(): openingtime = OpeningTimeBlock() openingtime.to_python({'label': '', 'date': None, 'closed': False,",
"assert value.link_url == '' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page(page): block =",
"'closed': False, 'start': None, 'end': None, 'weekday': ''}) # Pass without error def",
"= OpeningTimeBlock().to_python({'closed': False, 'start': '5:00', 'end': '10:00'}) out = OpeningTimesBlock.time_keyfunc(value) assert out ==",
"out = OpeningTimesBlock.time_keyfunc(value) assert out == (False, datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby): value",
"out == mocked_get.return_value def test_openingtimes_block_get_context(): openingtimes = OpeningTimesBlock() value = {'times': [1, 5,",
"== label def test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({}) == False def test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date': 'some",
"wagtail.core.models import Page from wagtail_extensions.blocks import ( DepartmentBlock, ImagesBlock, LinkBlock, OpeningTimeBlock, OpeningTimesBlock, PhoneBlock",
"False, 'start': '5:00', 'end': '10:00'}) out = OpeningTimesBlock.time_keyfunc(value) assert out == (False, datetime.time(5),",
"value = { 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, match, ],",
"assert block.get_context({'images': ['an image', 'another image', 'yet another image']})['column_width'] == 4 def test_images_block_get_context_empty_list():",
"homepage.add_child(instance=page) return page def test_department_block_clean_invalid(): department = DepartmentBlock() with pytest.raises(ValidationError): department.clean({}) def test_department_block_clean_valid_with_both():",
"openingtime = OpeningTimeBlock() label = 'Easter sunday' value = openingtime.to_python({'weekday': '7', 'label': label})",
"is None def test_openingtimes_block_get_time_for_date_times_date(): match = {'date': datetime.date(2017, 12, 10)} value = {",
"assert OpeningTimeBlock.single_date({}) == False def test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date': 'some date'}) == True def",
"'/hello/' assert value.link_text == '/hello/' def test_link_block_with_missing_streamblock(): block = LinkBlock() value = block.to_python({",
"phone.get_prep_value(number) assert number_str == '+447528712345' def test_phone_block_to_python(): phone = PhoneBlock() number = phone.to_python('+447528712345')",
"openingtime.clean({'start': '20:00', 'end': '08:00', 'weekday': '1'}) def test_openingtime_block_clean_no_weekday_or_date(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError):",
"'end': '20:00', 'date': '2017-01-01'}) def test_openingtime_block_to_python_empty(): openingtime = OpeningTimeBlock() openingtime.to_python({'label': '', 'date': None,",
"openingtime = OpeningTimeBlock() openingtime.to_python({'label': '', 'date': None, 'closed': False, 'start': None, 'end': None,",
"test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday': 6}) == datetime.date(2017, 12, 17) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday':",
"unittest.mock import patch from django.core.exceptions import ValidationError from freezegun import freeze_time from phonenumber_field.phonenumber",
"openingtime.to_python({'weekday': '5'}) assert value['weekday'] == 5 def test_openingtime_block_to_python_public_label(): openingtime = OpeningTimeBlock() value =",
"'some date'}) == True def test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday': 7}) == True def test_openingtime_block_next_date_empty():",
"[] # This must not be empty if the field is required })",
"'get_time_for_date') as mocked_get: value = 'test' out = openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017, 6, 28))",
"== '+447528712345' def test_phone_block_to_python(): phone = PhoneBlock() number = phone.to_python('+447528712345') assert number ==",
"6} value = { 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, match,",
"openingtime = OpeningTimeBlock() value = openingtime.to_python({}) with patch.object(openingtime, 'single_date', return_value=True): out = OpeningTimesBlock.time_keyfunc(value)",
"Page from wagtail_extensions.blocks import ( DepartmentBlock, ImagesBlock, LinkBlock, OpeningTimeBlock, OpeningTimesBlock, PhoneBlock ) @pytest.mark.django_db",
"12, 10)) == match def test_openingtimes_block_get_time_for_date_times_weekday(): match = {'weekday': 6} value = {",
"LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value': None}] }) assert value.link_url ==",
"be empty if the field is required }) with pytest.raises(ValidationError): block.clean(value) def test_link_block_clean_for_not_required():",
"assert OpeningTimeBlock.single_date({'weekday': 7}) == True def test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({}) is None @freeze_time(\"2017-12-13\") def",
"10])] out = OpeningTimesBlock.group_times(value) assert out == [[1, 4, 5], [7, 10]] mocked_groupby.assert_called_once_with(value,",
"value.link_text == '/hello/' def test_link_block_with_missing_streamblock(): block = LinkBlock() value = block.to_python({ 'text': '',",
"'']}) assert value['phones'] == ['+447528712345'] def test_link_block_with_url(): block = LinkBlock() value = block.to_python({",
"let's create our own child page for testing with. homepage = Page.objects.get(url_path='/home/') page",
"value.link_text == 'Hello World' def test_link_block_with_empty_string_text(): block = LinkBlock() value = block.to_python({ 'text':",
"'2017-01-01'}) def test_openingtime_block_to_python_empty(): openingtime = OpeningTimeBlock() openingtime.to_python({'label': '', 'date': None, 'closed': False, 'start':",
"datetime.date(2017, 12, 10)} value = { 'times': [ {'weekday': 4}, match, ], }",
"17)) is None @freeze_time('2017-06-28') def test_openingtimes_block_opening_today(): openingtimes = OpeningTimesBlock with patch.object(openingtimes, 'get_time_for_date') as",
"mocked_get.return_value def test_openingtimes_block_get_context(): openingtimes = OpeningTimesBlock() value = {'times': [1, 5, 10]} with",
"def test_openingtime_block_to_python_public_with_label(): openingtime = OpeningTimeBlock() label = 'Easter sunday' value = openingtime.to_python({'weekday': '7',",
"PageChooserBlock has been deleted, the block value will be None. \"\"\" block =",
"block.clean(value) def test_link_block_clean_for_not_required(): block = LinkBlock(required=False) value = block.to_python({ 'text': '<NAME>', 'link': []",
"12, 13) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday': 6}) == datetime.date(2017, 12, 17) @freeze_time(\"2017-12-13\")",
"datetime.date(2017, 12, 10)) == match def test_openingtimes_block_get_time_for_date_times_weekday(): match = {'weekday': 6} value =",
"def test_phone_block_get_prep_value(): phone = PhoneBlock() number = PhoneNumber.from_string('+447528712345') number_str = phone.get_prep_value(number) assert number_str",
"'5:00', 'end': '10:00'}) out = OpeningTimesBlock.time_keyfunc(value) assert out == (False, datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby')",
"with patch.object(openingtimes, 'get_time_for_date') as mocked_get: value = 'test' out = openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017,",
"{'date': datetime.date(2017, 12, 10)} value = { 'times': [ {'weekday': 4}, match, ],",
"None def test_openingtimes_block_time_keyfunc_specific(): openingtime = OpeningTimeBlock() value = openingtime.to_python({}) with patch.object(openingtime, 'single_date', return_value=True):",
"['an image', 'another image', 'yet another image']})['column_width'] == 4 def test_images_block_get_context_empty_list(): block =",
"department.clean({'name':'Test', 'email':'<EMAIL>', 'phones': ['+447528712345']}) def test_department_block_to_python_empty(): department = DepartmentBlock() department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers(): department",
"assert value.link_url == '/hello/' assert value.link_text == '/hello/' def test_link_block_with_url_and_text(): block = LinkBlock()",
"LinkBlock() value = block.to_python({ 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url ==",
"page referenced by a PageChooserBlock has been deleted, the block value will be",
"test_department_block_clean_valid_with_both(): department = DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>', 'phones': ['+447528712345']}) def test_department_block_to_python_empty(): department = DepartmentBlock()",
"= {'times': [1, 5, 10]} with patch.object(openingtimes, 'group_times') as mocked_group,\\ patch.object(openingtimes, 'opening_today') as",
"department.clean({}) def test_department_block_clean_valid_with_both(): department = DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>', 'phones': ['+447528712345']}) def test_department_block_to_python_empty(): department",
"import datetime import pytest from unittest.mock import patch from django.core.exceptions import ValidationError from",
"'Hello World' def test_link_block_clean_for_required(): block = LinkBlock() value = block.to_python({ 'text': 'Hello World',",
"DepartmentBlock, ImagesBlock, LinkBlock, OpeningTimeBlock, OpeningTimesBlock, PhoneBlock ) @pytest.mark.django_db @pytest.fixture def page(): # Homepage",
"the field is not required }) # This should not raise an exception",
"test_link_block_with_page(page): block = LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value': page.pk}] })",
"from wagtail.core.models import Page from wagtail_extensions.blocks import ( DepartmentBlock, ImagesBlock, LinkBlock, OpeningTimeBlock, OpeningTimesBlock,",
"} assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) is None @freeze_time('2017-06-28') def test_openingtimes_block_opening_today(): openingtimes =",
"assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) == match def test_openingtimes_block_get_time_for_date_times_no_match(): value = { 'times':",
"import pytest from unittest.mock import patch from django.core.exceptions import ValidationError from freezegun import",
"@patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby): value = {} mocked_groupby.return_value = [('first', [1, 4, 5]), ('second',",
"test_openingtime_block_to_python_cast_weekday(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '5'}) assert value['weekday'] == 5 def",
"def test_link_block_clean_for_required(): block = LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link': []",
"with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00'}) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid(): openingtime = OpeningTimeBlock() openingtime.clean({'start':",
"== True def test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({}) is None @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday':",
"}) # This should not raise an exception block.clean(value) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past(): openingtime",
"None. \"\"\" block = LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value': None}]",
"out = openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017, 6, 28)) assert out == mocked_get.return_value def test_openingtimes_block_get_context():",
"test_openingtime_block_clean_end_before_start(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00', 'weekday': '1'}) def",
"== '/hello/' assert value.link_text == '/hello/' def test_link_block_with_missing_streamblock(): block = LinkBlock() value =",
"openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '5'}) assert value['weekday'] == 5 def test_openingtime_block_to_python_public_label():",
"10)}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) == match def test_openingtimes_block_get_time_for_date_times_no_match():",
"mocked_today.assert_called_once_with(value) assert ctx['times'] == mocked_group.return_value assert ctx['today'] == mocked_today.return_value def test_phone_block_get_prep_value(): phone =",
"value.link_url == '' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page_and_text(page): block = LinkBlock()",
"def test_openingtime_block_to_python_public_label(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '7'}) assert value['label'] == OpeningTimeBlock.PUBLIC_LABEL",
"assert value.link_text == '/hello/' def test_link_block_with_url_and_text(): block = LinkBlock() value = block.to_python({ 'text':",
"'20:00', 'end': '08:00'}) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid(): openingtime = OpeningTimeBlock() openingtime.clean({'start': '08:00', 'end': '20:00',",
"= DepartmentBlock() with pytest.raises(ValidationError): department.clean({}) def test_department_block_clean_valid_with_both(): department = DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>', 'phones':",
"= OpeningTimeBlock() value = openingtime.to_python({}) with patch.object(openingtime, 'single_date', return_value=True): out = OpeningTimesBlock.time_keyfunc(value) assert",
"test page', slug=\"test\") homepage.add_child(instance=page) return page def test_department_block_clean_invalid(): department = DepartmentBlock() with pytest.raises(ValidationError):",
"= DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>', 'phones': ['+447528712345']}) def test_department_block_to_python_empty(): department = DepartmentBlock() department.to_python({}) def",
"assert OpeningTimeBlock.single_date({'date': 'some date'}) == True def test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday': 7}) == True",
"assert phone.to_python('') == '' def test_images_block_get_context(): block = ImagesBlock() assert block.get_context({'images': ['an image',",
"assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 10)) == match def test_openingtimes_block_get_time_for_date_times_weekday(): match = {'weekday': 6}",
"== match def test_openingtimes_block_get_time_for_date_times_no_match(): value = { 'times': [ {'weekday': 4}, {'date': datetime.date(2017,",
"'group_times') as mocked_group,\\ patch.object(openingtimes, 'opening_today') as mocked_today: ctx = openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5, 10])",
"block.to_python({ 'text': '<NAME>', 'link': [] # Can be empty if the field is",
"def test_link_block_with_empty_string_text(): block = LinkBlock() value = block.to_python({ 'text': '', 'link': [{'type': 'url',",
"@pytest.mark.django_db def test_link_block_with_page_and_text(page): block = LinkBlock() value = block.to_python({ 'text': '<NAME>', 'link': [{'type':",
"test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({}) == False def test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date': 'some date'}) == True",
"assert out == (False, datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby): value = {} mocked_groupby.return_value",
"13) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday': 6}) == datetime.date(2017, 12, 17) @freeze_time(\"2017-12-13\") def",
"OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12, 10)) is None def test_openingtimes_block_get_time_for_date_times_date(): match = {'date': datetime.date(2017, 12,",
"12, 10)}, {'weekday': 2}, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) is None",
"return_value=True): out = OpeningTimesBlock.time_keyfunc(value) assert out is value def test_openingtimes_block_time_keyfunc_non_specific(): value = OpeningTimeBlock().to_python({'closed':",
"out = OpeningTimesBlock.time_keyfunc(value) assert out is value def test_openingtimes_block_time_keyfunc_non_specific(): value = OpeningTimeBlock().to_python({'closed': False,",
"ImagesBlock, LinkBlock, OpeningTimeBlock, OpeningTimesBlock, PhoneBlock ) @pytest.mark.django_db @pytest.fixture def page(): # Homepage is",
"test_openingtime_block_to_python_public_with_label(): openingtime = OpeningTimeBlock() label = 'Easter sunday' value = openingtime.to_python({'weekday': '7', 'label':",
"'text': '<NAME>', 'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url == page.url assert",
"assert value.link_text == 'Hello World' def test_link_block_clean_for_required(): block = LinkBlock() value = block.to_python({",
"'/hello/' def test_link_block_with_url_and_text(): block = LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link':",
"def test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday': 2}) == datetime.date(2017, 12, 13) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday(): assert",
"None, 'weekday': ''}) # Pass without error def test_openingtime_block_to_python_cast_weekday(): openingtime = OpeningTimeBlock() value",
"assert out == mocked_get.return_value def test_openingtimes_block_get_context(): openingtimes = OpeningTimesBlock() value = {'times': [1,",
"( DepartmentBlock, ImagesBlock, LinkBlock, OpeningTimeBlock, OpeningTimesBlock, PhoneBlock ) @pytest.mark.django_db @pytest.fixture def page(): #",
"department = DepartmentBlock() with pytest.raises(ValidationError): department.clean({}) def test_department_block_clean_valid_with_both(): department = DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>',",
"'opening_today') as mocked_today: ctx = openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5, 10]) mocked_today.assert_called_once_with(value) assert ctx['times'] ==",
"page.pk}] }) assert value.link_url == page.url assert value.link_text == page.title @pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page):",
"if the field is required }) with pytest.raises(ValidationError): block.clean(value) def test_link_block_clean_for_not_required(): block =",
"openingtime.to_python({'weekday': '7', 'label': label}) assert value['label'] == label def test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({}) ==",
"PhoneNumber from wagtail.core.models import Page from wagtail_extensions.blocks import ( DepartmentBlock, ImagesBlock, LinkBlock, OpeningTimeBlock,",
"assert ctx['times'] == mocked_group.return_value assert ctx['today'] == mocked_today.return_value def test_phone_block_get_prep_value(): phone = PhoneBlock()",
"def test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12, 10)) is None def test_openingtimes_block_get_time_for_date_times_date(): match =",
"}) assert value.link_url == '' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page(page): block",
"'text': 'Hello World', 'link': [] # This must not be empty if the",
"match = {'date': datetime.date(2017, 12, 10)} value = { 'times': [ {'weekday': 4},",
"'times': [ {'weekday': 4}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 10)) ==",
"OpeningTimesBlock with patch.object(openingtimes, 'get_time_for_date') as mocked_get: value = 'test' out = openingtimes.opening_today(value) mocked_get.assert_called_once_with(value,",
"'text': '<NAME>', 'link': [] # Can be empty if the field is not",
"mocked_group,\\ patch.object(openingtimes, 'opening_today') as mocked_today: ctx = openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5, 10]) mocked_today.assert_called_once_with(value) assert",
"OpeningTimeBlock.single_date({}) == False def test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date': 'some date'}) == True def test_openingtime_block_single_date_public():",
"'' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page_and_text(page): block = LinkBlock() value =",
"date'}) == True def test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday': 7}) == True def test_openingtime_block_next_date_empty(): assert",
"match def test_openingtimes_block_get_time_for_date_times_weekday(): match = {'weekday': 6} value = { 'times': [ {'weekday':",
"datetime.date(2017, 12, 10)}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) == match",
"5, 10]) mocked_today.assert_called_once_with(value) assert ctx['times'] == mocked_group.return_value assert ctx['today'] == mocked_today.return_value def test_phone_block_get_prep_value():",
"page', slug=\"test\") homepage.add_child(instance=page) return page def test_department_block_clean_invalid(): department = DepartmentBlock() with pytest.raises(ValidationError): department.clean({})",
"= LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url",
"ValidationError from freezegun import freeze_time from phonenumber_field.phonenumber import PhoneNumber from wagtail.core.models import Page",
"'text': 'Hello World', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/'",
"test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None, None) is None def test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12, 10))",
"= OpeningTimesBlock with patch.object(openingtimes, 'get_time_for_date') as mocked_get: value = 'test' out = openingtimes.opening_today(value)",
"is required }) with pytest.raises(ValidationError): block.clean(value) def test_link_block_clean_for_not_required(): block = LinkBlock(required=False) value =",
"= block.to_python({ 'text': '', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url ==",
"'weekday': '1'}) def test_openingtime_block_clean_no_weekday_or_date(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00'})",
"6, 28)) assert out == mocked_get.return_value def test_openingtimes_block_get_context(): openingtimes = OpeningTimesBlock() value =",
"'label': label}) assert value['label'] == label def test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({}) == False def",
"'Hello World', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert",
"value = { 'times': [ {'weekday': 4}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017,",
"10)} value = { 'times': [ {'weekday': 4}, match, ], } assert OpeningTimesBlock.get_time_for_date(value,",
"'email':'<EMAIL>', 'phones': ['+447528712345']}) def test_department_block_to_python_empty(): department = DepartmentBlock() department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers(): department =",
"None @freeze_time('2017-06-28') def test_openingtimes_block_opening_today(): openingtimes = OpeningTimesBlock with patch.object(openingtimes, 'get_time_for_date') as mocked_get: value",
"None) is None def test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12, 10)) is None def",
"OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) == match def test_openingtimes_block_get_time_for_date_times_no_match(): value = { 'times': [",
"value = block.to_python({ 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/'",
"= block.to_python({ 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert",
"has been deleted, the block value will be None. \"\"\" block = LinkBlock()",
"None, 'end': None, 'weekday': ''}) # Pass without error def test_openingtime_block_to_python_cast_weekday(): openingtime =",
"@freeze_time('2017-06-28') def test_openingtimes_block_opening_today(): openingtimes = OpeningTimesBlock with patch.object(openingtimes, 'get_time_for_date') as mocked_get: value =",
"}) assert value.link_url == page.url assert value.link_text == 'Hello World' def test_link_block_clean_for_required(): block",
"by Wagtail's initial migrations # But let's create our own child page for",
"phone.to_python('+447528712345') assert number == PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty(): phone = PhoneBlock() assert phone.to_python('') ==",
"= openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017, 6, 28)) assert out == mocked_get.return_value def test_openingtimes_block_get_context(): openingtimes",
"def test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday': 6}) == datetime.date(2017, 12, 17) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public(): assert",
"match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) == match def test_openingtimes_block_get_time_for_date_times_no_match(): value",
"[[1, 4, 5], [7, 10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None, None) is",
"2}, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) is None @freeze_time('2017-06-28') def test_openingtimes_block_opening_today():",
"== '' def test_images_block_get_context(): block = ImagesBlock() assert block.get_context({'images': ['an image', 'another image',",
"test_department_block_to_python_strip_empty_phonenumbers(): department = DepartmentBlock() value = department.get_prep_value({'phones': ['', '+447528712345', '']}) assert value['phones'] ==",
"def test_department_block_to_python_strip_empty_phonenumbers(): department = DepartmentBlock() value = department.get_prep_value({'phones': ['', '+447528712345', '']}) assert value['phones']",
"= {'weekday': 6} value = { 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12,",
"with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00', 'weekday': '1'}) def test_openingtime_block_clean_no_weekday_or_date(): openingtime = OpeningTimeBlock()",
"== match def test_openingtimes_block_get_time_for_date_times_weekday(): match = {'weekday': 6} value = { 'times': [",
"is None def test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12, 10)) is None def test_openingtimes_block_get_time_for_date_times_date():",
"openingtime.clean({'date': '2016-01-01'}) def test_openingtime_block_clean_end_before_start(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00',",
"Pass without error def test_openingtime_block_to_python_cast_weekday(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '5'}) assert",
"from phonenumber_field.phonenumber import PhoneNumber from wagtail.core.models import Page from wagtail_extensions.blocks import ( DepartmentBlock,",
"block = LinkBlock() value = block.to_python({ 'text': '<NAME>', 'link': [{'type': 'page', 'value': page.pk}]",
"mocked_groupby.return_value = [('first', [1, 4, 5]), ('second', [7, 10])] out = OpeningTimesBlock.group_times(value) assert",
"phonenumber_field.phonenumber import PhoneNumber from wagtail.core.models import Page from wagtail_extensions.blocks import ( DepartmentBlock, ImagesBlock,",
"[ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, match, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017,",
"value = block.to_python({ 'text': '', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url",
"= LinkBlock() value = block.to_python({ 'link': [{'type': 'page', 'value': None}] }) assert value.link_url",
"'test' out = openingtimes.opening_today(value) mocked_get.assert_called_once_with(value, datetime.date(2017, 6, 28)) assert out == mocked_get.return_value def",
"def test_openingtime_block_to_python_cast_weekday(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '5'}) assert value['weekday'] == 5",
"@freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday': 2}) == datetime.date(2017, 12, 13) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday():",
"['+447528712345']}) def test_department_block_to_python_empty(): department = DepartmentBlock() department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers(): department = DepartmentBlock() value",
"pytest.raises(ValidationError): block.clean(value) def test_link_block_clean_for_not_required(): block = LinkBlock(required=False) value = block.to_python({ 'text': '<NAME>', 'link':",
"openingtime.to_python({'label': '', 'date': None, 'closed': False, 'start': None, 'end': None, 'weekday': ''}) #",
"import patch from django.core.exceptions import ValidationError from freezegun import freeze_time from phonenumber_field.phonenumber import",
"'+447528712345', '']}) assert value['phones'] == ['+447528712345'] def test_link_block_with_url(): block = LinkBlock() value =",
"PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty(): phone = PhoneBlock() assert phone.to_python('') == '' def test_images_block_get_context(): block",
"as mocked_group,\\ patch.object(openingtimes, 'opening_today') as mocked_today: ctx = openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5, 10]) mocked_today.assert_called_once_with(value)",
"== '' assert value.link_text == '' @pytest.mark.django_db def test_link_block_with_page_and_text(page): block = LinkBlock() value",
"sunday' value = openingtime.to_python({'weekday': '7', 'label': label}) assert value['label'] == label def test_openingtime_block_single_date_empty():",
"OpeningTimeBlock.single_date({'date': 'some date'}) == True def test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday': 7}) == True def",
"'link': [] # Can be empty if the field is not required })",
"= LinkBlock() value = block.to_python({ 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url",
"@pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page): \"\"\" If a page referenced by a PageChooserBlock has been",
"'value': page.pk}] }) assert value.link_url == page.url assert value.link_text == 'Hello World' def",
"# Pass without error def test_openingtime_block_to_python_cast_weekday(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '5'})",
"= block.to_python({ 'text': '<NAME>', 'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url ==",
"page def test_department_block_clean_invalid(): department = DepartmentBlock() with pytest.raises(ValidationError): department.clean({}) def test_department_block_clean_valid_with_both(): department =",
"'2016-01-01'}) def test_openingtime_block_clean_end_before_start(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00', 'weekday':",
"match def test_openingtimes_block_get_time_for_date_times_no_match(): value = { 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12,",
"freeze_time from phonenumber_field.phonenumber import PhoneNumber from wagtail.core.models import Page from wagtail_extensions.blocks import (",
"def test_link_block_with_missing_streamblock(): block = LinkBlock() value = block.to_python({ 'text': '', 'link': [] })",
"test_openingtimes_block_time_keyfunc_non_specific(): value = OpeningTimeBlock().to_python({'closed': False, 'start': '5:00', 'end': '10:00'}) out = OpeningTimesBlock.time_keyfunc(value) assert",
"{ 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, {'weekday': 2}, ], }",
"[{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text == 'Hello",
"DepartmentBlock() with pytest.raises(ValidationError): department.clean({}) def test_department_block_clean_valid_with_both(): department = DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>', 'phones': ['+447528712345']})",
"datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby): value = {} mocked_groupby.return_value = [('first', [1, 4,",
"block.to_python({ 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text",
"}) assert value.link_url == '/hello/' assert value.link_text == 'Hello World' def test_link_block_with_empty_string_text(): block",
"12, 17) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday': 7}) is None def test_openingtimes_block_time_keyfunc_specific(): openingtime",
"== '/hello/' def test_link_block_with_url_and_text(): block = LinkBlock() value = block.to_python({ 'text': 'Hello World',",
"as mocked_today: ctx = openingtimes.get_context(value) mocked_group.assert_called_once_with([1, 5, 10]) mocked_today.assert_called_once_with(value) assert ctx['times'] == mocked_group.return_value",
"block = LinkBlock() value = block.to_python({ 'text': '', 'link': [{'type': 'url', 'value': '/hello/'}]",
"block.to_python({ 'text': '<NAME>', 'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url == page.url",
"datetime.date(2017, 12, 17)) == match def test_openingtimes_block_get_time_for_date_times_no_match(): value = { 'times': [ {'weekday':",
"value['phones'] == ['+447528712345'] def test_link_block_with_url(): block = LinkBlock() value = block.to_python({ 'link': [{'type':",
"PhoneBlock() number = PhoneNumber.from_string('+447528712345') number_str = phone.get_prep_value(number) assert number_str == '+447528712345' def test_phone_block_to_python():",
"raise an exception block.clean(value) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'date':",
"= OpeningTimesBlock.group_times(value) assert out == [[1, 4, 5], [7, 10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def",
"test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({}) is None @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday': 2}) == datetime.date(2017,",
"= [('first', [1, 4, 5]), ('second', [7, 10])] out = OpeningTimesBlock.group_times(value) assert out",
"assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) is None @freeze_time('2017-06-28') def test_openingtimes_block_opening_today(): openingtimes = OpeningTimesBlock",
"[('first', [1, 4, 5]), ('second', [7, 10])] out = OpeningTimesBlock.group_times(value) assert out ==",
"out == (False, datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby): value = {} mocked_groupby.return_value =",
"12, 10)) is None def test_openingtimes_block_get_time_for_date_times_date(): match = {'date': datetime.date(2017, 12, 10)} value",
"'link': [] }) assert value.link_url == '' assert value.link_text == '' @pytest.mark.django_db def",
"test_openingtime_block_single_date_public(): assert OpeningTimeBlock.single_date({'weekday': 7}) == True def test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({}) is None @freeze_time(\"2017-12-13\")",
"OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 10)) == match def test_openingtimes_block_get_time_for_date_times_weekday(): match = {'weekday': 6} value",
"test_openingtime_block_next_date_public(): assert OpeningTimeBlock.next_date({'weekday': 7}) is None def test_openingtimes_block_time_keyfunc_specific(): openingtime = OpeningTimeBlock() value =",
"assert value.link_url == '/hello/' assert value.link_text == '/hello/' def test_link_block_with_missing_streamblock(): block = LinkBlock()",
"[{'type': 'page', 'value': page.pk}] }) assert value.link_url == page.url assert value.link_text == 'Hello",
"a page referenced by a PageChooserBlock has been deleted, the block value will",
"number == PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty(): phone = PhoneBlock() assert phone.to_python('') == '' def",
"def test_openingtimes_block_get_time_for_date_empty(): assert OpeningTimesBlock.get_time_for_date(None, None) is None def test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12,",
"= openingtime.to_python({'weekday': '7'}) assert value['label'] == OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label(): openingtime = OpeningTimeBlock() label",
"'page', 'value': page.pk}] }) assert value.link_url == page.url assert value.link_text == page.title @pytest.mark.django_db",
"False, 'start': None, 'end': None, 'weekday': ''}) # Pass without error def test_openingtime_block_to_python_cast_weekday():",
"not raise an exception block.clean(value) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError):",
"page = Page(title='A test page', slug=\"test\") homepage.add_child(instance=page) return page def test_department_block_clean_invalid(): department =",
"test_link_block_with_url_and_text(): block = LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link': [{'type': 'url',",
"== page.title @pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page): \"\"\" If a page referenced by a PageChooserBlock",
"= PhoneBlock() number = phone.to_python('+447528712345') assert number == PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty(): phone =",
"number_str == '+447528712345' def test_phone_block_to_python(): phone = PhoneBlock() number = phone.to_python('+447528712345') assert number",
"def test_openingtime_block_clean_valid(): openingtime = OpeningTimeBlock() openingtime.clean({'start': '08:00', 'end': '20:00', 'date': '2017-01-01'}) def test_openingtime_block_to_python_empty():",
"openingtime.clean({'start': '20:00', 'end': '08:00'}) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid(): openingtime = OpeningTimeBlock() openingtime.clean({'start': '08:00', 'end':",
"a PageChooserBlock has been deleted, the block value will be None. \"\"\" block",
"label}) assert value['label'] == label def test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({}) == False def test_openingtime_block_single_date_with_date():",
"mocked_today.return_value def test_phone_block_get_prep_value(): phone = PhoneBlock() number = PhoneNumber.from_string('+447528712345') number_str = phone.get_prep_value(number) assert",
"value = openingtime.to_python({}) with patch.object(openingtime, 'single_date', return_value=True): out = OpeningTimesBlock.time_keyfunc(value) assert out is",
"OpeningTimesBlock() value = {'times': [1, 5, 10]} with patch.object(openingtimes, 'group_times') as mocked_group,\\ patch.object(openingtimes,",
"[1, 4, 5]), ('second', [7, 10])] out = OpeningTimesBlock.group_times(value) assert out == [[1,",
"block.to_python({ 'text': '', 'link': [] }) assert value.link_url == '' assert value.link_text ==",
"value.link_url == '/hello/' assert value.link_text == '/hello/' def test_link_block_with_missing_streamblock(): block = LinkBlock() value",
"} assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 10)) == match def test_openingtimes_block_get_time_for_date_times_weekday(): match = {'weekday':",
"''}) # Pass without error def test_openingtime_block_to_python_cast_weekday(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday':",
"OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'}) def test_openingtime_block_clean_end_before_start(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start':",
"without error def test_openingtime_block_to_python_cast_weekday(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '5'}) assert value['weekday']",
"], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) is None @freeze_time('2017-06-28') def test_openingtimes_block_opening_today(): openingtimes",
"block.to_python({ 'link': [{'type': 'page', 'value': None}] }) assert value.link_url == '' assert value.link_text",
"== 'Hello World' def test_link_block_clean_for_required(): block = LinkBlock() value = block.to_python({ 'text': 'Hello",
"datetime.date(2017, 12, 10)}, {'weekday': 2}, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) is",
"with pytest.raises(ValidationError): block.clean(value) def test_link_block_clean_for_not_required(): block = LinkBlock(required=False) value = block.to_python({ 'text': '<NAME>',",
"openingtime.to_python({}) with patch.object(openingtime, 'single_date', return_value=True): out = OpeningTimesBlock.time_keyfunc(value) assert out is value def",
"assert value.link_url == page.url assert value.link_text == 'Hello World' def test_link_block_clean_for_required(): block =",
"with pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'}) def test_openingtime_block_clean_end_before_start(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00',",
"assert out == [[1, 4, 5], [7, 10]] mocked_groupby.assert_called_once_with(value, OpeningTimesBlock.time_keyfunc) def test_openingtimes_block_get_time_for_date_empty(): assert",
"[ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, {'weekday': 2}, ], } assert OpeningTimesBlock.get_time_for_date(value,",
"7}) == True def test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({}) is None @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today(): assert",
"[1, 5, 10]} with patch.object(openingtimes, 'group_times') as mocked_group,\\ patch.object(openingtimes, 'opening_today') as mocked_today: ctx",
"def test_phone_block_to_python_empty(): phone = PhoneBlock() assert phone.to_python('') == '' def test_images_block_get_context(): block =",
"def test_department_block_to_python_empty(): department = DepartmentBlock() department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers(): department = DepartmentBlock() value =",
"must not be empty if the field is required }) with pytest.raises(ValidationError): block.clean(value)",
"== '/hello/' assert value.link_text == 'Hello World' def test_link_block_with_empty_string_text(): block = LinkBlock() value",
"assert value['label'] == label def test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({}) == False def test_openingtime_block_single_date_with_date(): assert",
"def test_phone_block_to_python(): phone = PhoneBlock() number = phone.to_python('+447528712345') assert number == PhoneNumber.from_string('+447528712345') def",
"= { 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, {'weekday': 2}, ],",
"value = block.to_python({ 'text': '<NAME>', 'link': [{'type': 'page', 'value': page.pk}] }) assert value.link_url",
"def test_images_block_get_context(): block = ImagesBlock() assert block.get_context({'images': ['an image', 'another image', 'yet another",
"will be None. \"\"\" block = LinkBlock() value = block.to_python({ 'link': [{'type': 'page',",
"value.link_text == page.title @pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page): \"\"\" If a page referenced by a",
"LinkBlock() value = block.to_python({ 'text': '', 'link': [] }) assert value.link_url == ''",
"'7', 'label': label}) assert value['label'] == label def test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({}) == False",
"'5'}) assert value['weekday'] == 5 def test_openingtime_block_to_python_public_label(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday':",
"= Page.objects.get(url_path='/home/') page = Page(title='A test page', slug=\"test\") homepage.add_child(instance=page) return page def test_department_block_clean_invalid():",
"page.url assert value.link_text == 'Hello World' def test_link_block_clean_for_required(): block = LinkBlock() value =",
"department.get_prep_value({'phones': ['', '+447528712345', '']}) assert value['phones'] == ['+447528712345'] def test_link_block_with_url(): block = LinkBlock()",
"assert OpeningTimeBlock.next_date({'weekday': 2}) == datetime.date(2017, 12, 13) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday': 6})",
"OpeningTimeBlock() value = openingtime.to_python({}) with patch.object(openingtime, 'single_date', return_value=True): out = OpeningTimesBlock.time_keyfunc(value) assert out",
"def test_openingtime_block_next_date_empty(): assert OpeningTimeBlock.next_date({}) is None @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday': 2}) ==",
"pytest.raises(ValidationError): department.clean({}) def test_department_block_clean_valid_with_both(): department = DepartmentBlock() department.clean({'name':'Test', 'email':'<EMAIL>', 'phones': ['+447528712345']}) def test_department_block_to_python_empty():",
"OpeningTimesBlock.get_time_for_date(None, None) is None def test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12, 10)) is None",
"field is not required }) # This should not raise an exception block.clean(value)",
"assert number_str == '+447528712345' def test_phone_block_to_python(): phone = PhoneBlock() number = phone.to_python('+447528712345') assert",
"= openingtime.to_python({'weekday': '7', 'label': label}) assert value['label'] == label def test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({})",
"LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link': [{'type': 'url', 'value': '/hello/'}] })",
"== mocked_get.return_value def test_openingtimes_block_get_context(): openingtimes = OpeningTimesBlock() value = {'times': [1, 5, 10]}",
"'' @pytest.mark.django_db def test_link_block_with_page(page): block = LinkBlock() value = block.to_python({ 'link': [{'type': 'page',",
"10)}, {'weekday': 2}, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) is None @freeze_time('2017-06-28')",
"], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 10)) == match def test_openingtimes_block_get_time_for_date_times_weekday(): match =",
"But let's create our own child page for testing with. homepage = Page.objects.get(url_path='/home/')",
"{'date': datetime.date(2017, 12, 10)}, {'weekday': 2}, ], } assert OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17))",
"'' @pytest.mark.django_db def test_link_block_with_page_and_text(page): block = LinkBlock() value = block.to_python({ 'text': '<NAME>', 'link':",
"homepage = Page.objects.get(url_path='/home/') page = Page(title='A test page', slug=\"test\") homepage.add_child(instance=page) return page def",
"OpeningTimesBlock.time_keyfunc(value) assert out == (False, datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby): value = {}",
"'/hello/'}] }) assert value.link_url == '/hello/' assert value.link_text == 'Hello World' def test_link_block_with_empty_string_text():",
"should not raise an exception block.clean(value) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_date_in_past(): openingtime = OpeningTimeBlock() with",
"test_openingtimes_block_get_time_for_date_times_date(): match = {'date': datetime.date(2017, 12, 10)} value = { 'times': [ {'weekday':",
"'<NAME>', 'link': [] # Can be empty if the field is not required",
"def test_openingtime_block_clean_no_weekday_or_date(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00'}) @freeze_time(\"2017-01-01\") def",
"test_openingtimes_block_get_context(): openingtimes = OpeningTimesBlock() value = {'times': [1, 5, 10]} with patch.object(openingtimes, 'group_times')",
") @pytest.mark.django_db @pytest.fixture def page(): # Homepage is created by Wagtail's initial migrations",
"def test_openingtime_block_clean_date_in_past(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'}) def test_openingtime_block_clean_end_before_start(): openingtime =",
"= OpeningTimeBlock() value = openingtime.to_python({'weekday': '5'}) assert value['weekday'] == 5 def test_openingtime_block_to_python_public_label(): openingtime",
"'08:00'}) @freeze_time(\"2017-01-01\") def test_openingtime_block_clean_valid(): openingtime = OpeningTimeBlock() openingtime.clean({'start': '08:00', 'end': '20:00', 'date': '2017-01-01'})",
"block = LinkBlock() value = block.to_python({ 'text': 'Hello World', 'link': [] # This",
"PhoneBlock() number = phone.to_python('+447528712345') assert number == PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty(): phone = PhoneBlock()",
"test_department_block_to_python_empty(): department = DepartmentBlock() department.to_python({}) def test_department_block_to_python_strip_empty_phonenumbers(): department = DepartmentBlock() value = department.get_prep_value({'phones':",
"}) with pytest.raises(ValidationError): block.clean(value) def test_link_block_clean_for_not_required(): block = LinkBlock(required=False) value = block.to_python({ 'text':",
"openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start': '20:00', 'end': '08:00', 'weekday': '1'}) def test_openingtime_block_clean_no_weekday_or_date():",
"= block.to_python({ 'text': '', 'link': [] }) assert value.link_url == '' assert value.link_text",
"department = DepartmentBlock() value = department.get_prep_value({'phones': ['', '+447528712345', '']}) assert value['phones'] == ['+447528712345']",
"= OpeningTimesBlock.time_keyfunc(value) assert out is value def test_openingtimes_block_time_keyfunc_non_specific(): value = OpeningTimeBlock().to_python({'closed': False, 'start':",
"match = {'weekday': 6} value = { 'times': [ {'weekday': 4}, {'date': datetime.date(2017,",
"== PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty(): phone = PhoneBlock() assert phone.to_python('') == '' def test_images_block_get_context():",
"== datetime.date(2017, 12, 13) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday': 6}) == datetime.date(2017, 12,",
"test_openingtime_block_next_date_today(): assert OpeningTimeBlock.next_date({'weekday': 2}) == datetime.date(2017, 12, 13) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday':",
"10)) == match def test_openingtimes_block_get_time_for_date_times_weekday(): match = {'weekday': 6} value = { 'times':",
"'10:00'}) out = OpeningTimesBlock.time_keyfunc(value) assert out == (False, datetime.time(5), datetime.time(10)) @patch('wagtail_extensions.blocks.groupby') def test_openingtimes_block_group_times(mocked_groupby):",
"World', 'link': [] # This must not be empty if the field is",
"openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'date': '2016-01-01'}) def test_openingtime_block_clean_end_before_start(): openingtime = OpeningTimeBlock() with",
"Can be empty if the field is not required }) # This should",
"'7'}) assert value['label'] == OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label(): openingtime = OpeningTimeBlock() label = 'Easter",
"datetime.date(2017, 6, 28)) assert out == mocked_get.return_value def test_openingtimes_block_get_context(): openingtimes = OpeningTimesBlock() value",
"block = ImagesBlock() assert block.get_context({'images': ['an image', 'another image', 'yet another image']})['column_width'] ==",
"== 5 def test_openingtime_block_to_python_public_label(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '7'}) assert value['label']",
"def test_openingtimes_block_get_time_for_date_times_date(): match = {'date': datetime.date(2017, 12, 10)} value = { 'times': [",
"LinkBlock(required=False) value = block.to_python({ 'text': '<NAME>', 'link': [] # Can be empty if",
"17)) == match def test_openingtimes_block_get_time_for_date_times_no_match(): value = { 'times': [ {'weekday': 4}, {'date':",
"assert OpeningTimesBlock.get_time_for_date(None, None) is None def test_openingtimes_block_get_time_for_date_no_times(): assert OpeningTimesBlock.get_time_for_date({}, datetime.date(2017, 12, 10)) is",
"'link': [] # This must not be empty if the field is required",
"OpeningTimesBlock.get_time_for_date(value, datetime.date(2017, 12, 17)) is None @freeze_time('2017-06-28') def test_openingtimes_block_opening_today(): openingtimes = OpeningTimesBlock with",
"== False def test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date': 'some date'}) == True def test_openingtime_block_single_date_public(): assert",
"with patch.object(openingtime, 'single_date', return_value=True): out = OpeningTimesBlock.time_keyfunc(value) assert out is value def test_openingtimes_block_time_keyfunc_non_specific():",
"== 'Hello World' def test_link_block_with_empty_string_text(): block = LinkBlock() value = block.to_python({ 'text': '',",
"error def test_openingtime_block_to_python_cast_weekday(): openingtime = OpeningTimeBlock() value = openingtime.to_python({'weekday': '5'}) assert value['weekday'] ==",
"= 'Easter sunday' value = openingtime.to_python({'weekday': '7', 'label': label}) assert value['label'] == label",
"phone = PhoneBlock() number = phone.to_python('+447528712345') assert number == PhoneNumber.from_string('+447528712345') def test_phone_block_to_python_empty(): phone",
"= { 'times': [ {'weekday': 4}, {'date': datetime.date(2017, 12, 10)}, match, ], }",
"== mocked_group.return_value assert ctx['today'] == mocked_today.return_value def test_phone_block_get_prep_value(): phone = PhoneBlock() number =",
"phone = PhoneBlock() assert phone.to_python('') == '' def test_images_block_get_context(): block = ImagesBlock() assert",
"'text': '', 'link': [{'type': 'url', 'value': '/hello/'}] }) assert value.link_url == '/hello/' assert",
"migrations # But let's create our own child page for testing with. homepage",
"value.link_url == '/hello/' assert value.link_text == 'Hello World' def test_link_block_with_empty_string_text(): block = LinkBlock()",
"'20:00', 'end': '08:00', 'weekday': '1'}) def test_openingtime_block_clean_no_weekday_or_date(): openingtime = OpeningTimeBlock() with pytest.raises(ValidationError): openingtime.clean({'start':",
"= DepartmentBlock() value = department.get_prep_value({'phones': ['', '+447528712345', '']}) assert value['phones'] == ['+447528712345'] def",
"assert value.link_text == 'Hello World' def test_link_block_with_empty_string_text(): block = LinkBlock() value = block.to_python({",
"@freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_sunday(): assert OpeningTimeBlock.next_date({'weekday': 6}) == datetime.date(2017, 12, 17) @freeze_time(\"2017-12-13\") def test_openingtime_block_next_date_public():",
"value['label'] == label def test_openingtime_block_single_date_empty(): assert OpeningTimeBlock.single_date({}) == False def test_openingtime_block_single_date_with_date(): assert OpeningTimeBlock.single_date({'date':",
"test_openingtimes_block_opening_today(): openingtimes = OpeningTimesBlock with patch.object(openingtimes, 'get_time_for_date') as mocked_get: value = 'test' out",
"[{'type': 'page', 'value': page.pk}] }) assert value.link_url == page.url assert value.link_text == page.title",
"value = {} mocked_groupby.return_value = [('first', [1, 4, 5]), ('second', [7, 10])] out",
"page(): # Homepage is created by Wagtail's initial migrations # But let's create",
"openingtimes = OpeningTimesBlock() value = {'times': [1, 5, 10]} with patch.object(openingtimes, 'group_times') as",
"freezegun import freeze_time from phonenumber_field.phonenumber import PhoneNumber from wagtail.core.models import Page from wagtail_extensions.blocks",
"= LinkBlock() value = block.to_python({ 'text': '', 'link': [{'type': 'url', 'value': '/hello/'}] })",
"the field is required }) with pytest.raises(ValidationError): block.clean(value) def test_link_block_clean_for_not_required(): block = LinkBlock(required=False)",
"value.link_url == page.url assert value.link_text == page.title @pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page): \"\"\" If a",
"# But let's create our own child page for testing with. homepage =",
"value = openingtime.to_python({'weekday': '7'}) assert value['label'] == OpeningTimeBlock.PUBLIC_LABEL def test_openingtime_block_to_python_public_with_label(): openingtime = OpeningTimeBlock()",
"== page.url assert value.link_text == page.title @pytest.mark.django_db def test_link_block_with_page_that_no_longer_exists(page): \"\"\" If a page",
"12, 17)) == match def test_openingtimes_block_get_time_for_date_times_no_match(): value = { 'times': [ {'weekday': 4},",
"initial migrations # But let's create our own child page for testing with.",
"test_openingtime_block_to_python_empty(): openingtime = OpeningTimeBlock() openingtime.to_python({'label': '', 'date': None, 'closed': False, 'start': None, 'end':",
"the block value will be None. \"\"\" block = LinkBlock() value = block.to_python({",
"ctx['today'] == mocked_today.return_value def test_phone_block_get_prep_value(): phone = PhoneBlock() number = PhoneNumber.from_string('+447528712345') number_str =",
"'Easter sunday' value = openingtime.to_python({'weekday': '7', 'label': label}) assert value['label'] == label def"
] |
[
"get_response_schema as date_range_question_schema from .free_form_question import get_response_schema as free_form_question_schema from .multiple_choice_question import (",
"get_response_schema as free_form_question_schema from .multiple_choice_question import ( get_response_schema as multiple_choice_question_schema, ) from .numeric_range_question",
"free_form_question_schema from .multiple_choice_question import ( get_response_schema as multiple_choice_question_schema, ) from .numeric_range_question import get_response_schema",
") from .numeric_range_question import get_response_schema as numeric_range_question_schema from .single_choice_question import get_response_schema as single_choice_question_schema",
"from .numeric_range_question import get_response_schema as numeric_range_question_schema from .single_choice_question import get_response_schema as single_choice_question_schema from",
".multiple_choice_question import ( get_response_schema as multiple_choice_question_schema, ) from .numeric_range_question import get_response_schema as numeric_range_question_schema",
"from .free_form_question import get_response_schema as free_form_question_schema from .multiple_choice_question import ( get_response_schema as multiple_choice_question_schema,",
"import get_response_schema as free_form_question_schema from .multiple_choice_question import ( get_response_schema as multiple_choice_question_schema, ) from",
"get_response_schema as numeric_range_question_schema from .single_choice_question import get_response_schema as single_choice_question_schema from .true_false_question import get_response_schema",
"as multiple_choice_question_schema, ) from .numeric_range_question import get_response_schema as numeric_range_question_schema from .single_choice_question import get_response_schema",
"imports.\"\"\" from .date_range_question import get_response_schema as date_range_question_schema from .free_form_question import get_response_schema as free_form_question_schema",
"as numeric_range_question_schema from .single_choice_question import get_response_schema as single_choice_question_schema from .true_false_question import get_response_schema as",
"as date_range_question_schema from .free_form_question import get_response_schema as free_form_question_schema from .multiple_choice_question import ( get_response_schema",
".numeric_range_question import get_response_schema as numeric_range_question_schema from .single_choice_question import get_response_schema as single_choice_question_schema from .true_false_question",
"get_response_schema as multiple_choice_question_schema, ) from .numeric_range_question import get_response_schema as numeric_range_question_schema from .single_choice_question import",
"import ( get_response_schema as multiple_choice_question_schema, ) from .numeric_range_question import get_response_schema as numeric_range_question_schema from",
"import get_response_schema as numeric_range_question_schema from .single_choice_question import get_response_schema as single_choice_question_schema from .true_false_question import",
"from .date_range_question import get_response_schema as date_range_question_schema from .free_form_question import get_response_schema as free_form_question_schema from",
"import get_response_schema as date_range_question_schema from .free_form_question import get_response_schema as free_form_question_schema from .multiple_choice_question import",
"from .multiple_choice_question import ( get_response_schema as multiple_choice_question_schema, ) from .numeric_range_question import get_response_schema as",
"multiple_choice_question_schema, ) from .numeric_range_question import get_response_schema as numeric_range_question_schema from .single_choice_question import get_response_schema as",
"date_range_question_schema from .free_form_question import get_response_schema as free_form_question_schema from .multiple_choice_question import ( get_response_schema as",
"numeric_range_question_schema from .single_choice_question import get_response_schema as single_choice_question_schema from .true_false_question import get_response_schema as true_false_question_schema",
".free_form_question import get_response_schema as free_form_question_schema from .multiple_choice_question import ( get_response_schema as multiple_choice_question_schema, )",
".date_range_question import get_response_schema as date_range_question_schema from .free_form_question import get_response_schema as free_form_question_schema from .multiple_choice_question",
"\"\"\"Convenience imports.\"\"\" from .date_range_question import get_response_schema as date_range_question_schema from .free_form_question import get_response_schema as",
"( get_response_schema as multiple_choice_question_schema, ) from .numeric_range_question import get_response_schema as numeric_range_question_schema from .single_choice_question",
"as free_form_question_schema from .multiple_choice_question import ( get_response_schema as multiple_choice_question_schema, ) from .numeric_range_question import"
] |
[
"open start message file start_file = open('ressources/start.txt', 'r', encoding='utf-8') message = start_file.read() start_file.close()",
"<filename>utils/start.py # coding:utf-8 # open start message file start_file = open('ressources/start.txt', 'r', encoding='utf-8')",
"# open start message file start_file = open('ressources/start.txt', 'r', encoding='utf-8') message = start_file.read()",
"coding:utf-8 # open start message file start_file = open('ressources/start.txt', 'r', encoding='utf-8') message =",
"# coding:utf-8 # open start message file start_file = open('ressources/start.txt', 'r', encoding='utf-8') message"
] |
[
"@property def simulation(self) -> BlueSkySimulatorControls: return self._sim_controls @property def sim_version(self) -> VersionInfo: return",
"to re-add the tests for string parsing/units from the old API tests import",
"construct before sending it \"\"\" # Probably a cleaner way of doing this...",
"List from semver import VersionInfo from .bluesky_aircraft_controls import BlueSkyAircraftControls from .bluesky_simulator_controls import BlueSkySimulatorControls",
"Timer _BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\") if not _BS_MIN_VERSION: raise ValueError(\"The BS_MIN_VERSION environment variable must",
"return self._client.host_version def __init__(self, **kwargs): self._client = BlueSkyClient() self._aircraft_controls = BlueSkyAircraftControls(self._client) self._sim_controls =",
"raise ValueError(\"The BS_MIN_VERSION environment variable must be set\") MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION) # TODO",
"SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation for BlueSky\"\"\" @property def aircraft(self) -> BlueSkyAircraftControls: return self._aircraft_controls @property",
"tests for string parsing/units from the old API tests import os from typing",
"import BlueSkyAircraftControls from .bluesky_simulator_controls import BlueSkySimulatorControls from bluebird.settings import Settings from bluebird.sim_client.bluesky.bluesky_client import",
"parsing/units from the old API tests import os from typing import List from",
"import Timer _BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\") if not _BS_MIN_VERSION: raise ValueError(\"The BS_MIN_VERSION environment variable",
"import os from typing import List from semver import VersionInfo from .bluesky_aircraft_controls import",
"self._client.host_version def __init__(self, **kwargs): self._client = BlueSkyClient() self._aircraft_controls = BlueSkyAircraftControls(self._client) self._sim_controls = BlueSkySimulatorControls(self._client)",
"from the old API tests import os from typing import List from semver",
"to check the arguments for each command string we construct before sending it",
"import AbstractSimClient from bluebird.utils.timer import Timer _BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\") if not _BS_MIN_VERSION: raise",
"simulation client class \"\"\" # TODO: Need to re-add the tests for string",
"self._sim_controls @property def sim_version(self) -> VersionInfo: return self._client.host_version def __init__(self, **kwargs): self._client =",
"import List from semver import VersionInfo from .bluesky_aircraft_controls import BlueSkyAircraftControls from .bluesky_simulator_controls import",
"before sending it \"\"\" # Probably a cleaner way of doing this... assert",
"from .bluesky_simulator_controls import BlueSkySimulatorControls from bluebird.settings import Settings from bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient from",
".bluesky_simulator_controls import BlueSkySimulatorControls from bluebird.settings import Settings from bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient from bluebird.utils.abstract_sim_client",
"BlueSkySimulatorControls: return self._sim_controls @property def sim_version(self) -> VersionInfo: return self._client.host_version def __init__(self, **kwargs):",
"= VersionInfo.parse(_BS_MIN_VERSION) # TODO Check cases where we need this def _assert_valid_args(args: list):",
"BlueSky\"\"\" @property def aircraft(self) -> BlueSkyAircraftControls: return self._aircraft_controls @property def simulation(self) -> BlueSkySimulatorControls:",
"cleaner way of doing this... assert all( x and not x.isspace() and x",
"old API tests import os from typing import List from semver import VersionInfo",
"self._sim_controls = BlueSkySimulatorControls(self._client) def start_timers(self) -> List[Timer]: return self._client.start_timers() def connect(self, timeout=1) ->",
"-> List[Timer]: return self._client.start_timers() def connect(self, timeout=1) -> None: self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT,",
"ValueError(\"The BS_MIN_VERSION environment variable must be set\") MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION) # TODO Check",
"commands in the form of (variable-length) strings, we need to check the arguments",
"not x.isspace() and x != \"None\" for x in map(str, args) ), f\"Invalid",
"need this def _assert_valid_args(args: list): \"\"\" Since BlueSky only accepts commands in the",
"!= \"None\" for x in map(str, args) ), f\"Invalid argument in : {args}\"",
"args) ), f\"Invalid argument in : {args}\" class SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation for BlueSky\"\"\"",
"BlueSkyAircraftControls: return self._aircraft_controls @property def simulation(self) -> BlueSkySimulatorControls: return self._sim_controls @property def sim_version(self)",
".bluesky_aircraft_controls import BlueSkyAircraftControls from .bluesky_simulator_controls import BlueSkySimulatorControls from bluebird.settings import Settings from bluebird.sim_client.bluesky.bluesky_client",
"only accepts commands in the form of (variable-length) strings, we need to check",
"of (variable-length) strings, we need to check the arguments for each command string",
": {args}\" class SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation for BlueSky\"\"\" @property def aircraft(self) -> BlueSkyAircraftControls:",
"def connect(self, timeout=1) -> None: self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout, ) def shutdown(self,",
"BlueSkySimulatorControls from bluebird.settings import Settings from bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient from bluebird.utils.abstract_sim_client import AbstractSimClient",
"event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout, ) def shutdown(self, shutdown_sim: bool = False) -> bool: self._client.stop()",
"simulation(self) -> BlueSkySimulatorControls: return self._sim_controls @property def sim_version(self) -> VersionInfo: return self._client.host_version def",
"the old API tests import os from typing import List from semver import",
"def aircraft(self) -> BlueSkyAircraftControls: return self._aircraft_controls @property def simulation(self) -> BlueSkySimulatorControls: return self._sim_controls",
"environment variable must be set\") MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION) # TODO Check cases where",
"timeout=1) -> None: self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout, ) def shutdown(self, shutdown_sim: bool",
"**kwargs): self._client = BlueSkyClient() self._aircraft_controls = BlueSkyAircraftControls(self._client) self._sim_controls = BlueSkySimulatorControls(self._client) def start_timers(self) ->",
"strings, we need to check the arguments for each command string we construct",
"os from typing import List from semver import VersionInfo from .bluesky_aircraft_controls import BlueSkyAircraftControls",
"we need this def _assert_valid_args(args: list): \"\"\" Since BlueSky only accepts commands in",
"(variable-length) strings, we need to check the arguments for each command string we",
"not _BS_MIN_VERSION: raise ValueError(\"The BS_MIN_VERSION environment variable must be set\") MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION)",
"way of doing this... assert all( x and not x.isspace() and x !=",
"for x in map(str, args) ), f\"Invalid argument in : {args}\" class SimClient(AbstractSimClient):",
"\"\"\" # TODO: Need to re-add the tests for string parsing/units from the",
"# TODO Check cases where we need this def _assert_valid_args(args: list): \"\"\" Since",
"be set\") MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION) # TODO Check cases where we need this",
"x != \"None\" for x in map(str, args) ), f\"Invalid argument in :",
"self._client = BlueSkyClient() self._aircraft_controls = BlueSkyAircraftControls(self._client) self._sim_controls = BlueSkySimulatorControls(self._client) def start_timers(self) -> List[Timer]:",
"Check cases where we need this def _assert_valid_args(args: list): \"\"\" Since BlueSky only",
"MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION) # TODO Check cases where we need this def _assert_valid_args(args:",
"implementation for BlueSky\"\"\" @property def aircraft(self) -> BlueSkyAircraftControls: return self._aircraft_controls @property def simulation(self)",
"BlueSky simulation client class \"\"\" # TODO: Need to re-add the tests for",
"def __init__(self, **kwargs): self._client = BlueSkyClient() self._aircraft_controls = BlueSkyAircraftControls(self._client) self._sim_controls = BlueSkySimulatorControls(self._client) def",
"\"\"\" Since BlueSky only accepts commands in the form of (variable-length) strings, we",
"bluebird.settings import Settings from bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient from bluebird.utils.abstract_sim_client import AbstractSimClient from bluebird.utils.timer",
"cases where we need this def _assert_valid_args(args: list): \"\"\" Since BlueSky only accepts",
"in : {args}\" class SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation for BlueSky\"\"\" @property def aircraft(self) ->",
"x and not x.isspace() and x != \"None\" for x in map(str, args)",
"accepts commands in the form of (variable-length) strings, we need to check the",
"List[Timer]: return self._client.start_timers() def connect(self, timeout=1) -> None: self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout,",
"BlueSkyClient() self._aircraft_controls = BlueSkyAircraftControls(self._client) self._sim_controls = BlueSkySimulatorControls(self._client) def start_timers(self) -> List[Timer]: return self._client.start_timers()",
"each command string we construct before sending it \"\"\" # Probably a cleaner",
"semver import VersionInfo from .bluesky_aircraft_controls import BlueSkyAircraftControls from .bluesky_simulator_controls import BlueSkySimulatorControls from bluebird.settings",
"string parsing/units from the old API tests import os from typing import List",
"timeout=timeout, ) def shutdown(self, shutdown_sim: bool = False) -> bool: self._client.stop() return True",
"and x != \"None\" for x in map(str, args) ), f\"Invalid argument in",
"VersionInfo from .bluesky_aircraft_controls import BlueSkyAircraftControls from .bluesky_simulator_controls import BlueSkySimulatorControls from bluebird.settings import Settings",
"command string we construct before sending it \"\"\" # Probably a cleaner way",
"form of (variable-length) strings, we need to check the arguments for each command",
"TODO Check cases where we need this def _assert_valid_args(args: list): \"\"\" Since BlueSky",
"), f\"Invalid argument in : {args}\" class SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation for BlueSky\"\"\" @property",
"this... assert all( x and not x.isspace() and x != \"None\" for x",
"_BS_MIN_VERSION: raise ValueError(\"The BS_MIN_VERSION environment variable must be set\") MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION) #",
"\"None\" for x in map(str, args) ), f\"Invalid argument in : {args}\" class",
"@property def sim_version(self) -> VersionInfo: return self._client.host_version def __init__(self, **kwargs): self._client = BlueSkyClient()",
"= BlueSkyAircraftControls(self._client) self._sim_controls = BlueSkySimulatorControls(self._client) def start_timers(self) -> List[Timer]: return self._client.start_timers() def connect(self,",
"tests import os from typing import List from semver import VersionInfo from .bluesky_aircraft_controls",
"list): \"\"\" Since BlueSky only accepts commands in the form of (variable-length) strings,",
"all( x and not x.isspace() and x != \"None\" for x in map(str,",
"sim_version(self) -> VersionInfo: return self._client.host_version def __init__(self, **kwargs): self._client = BlueSkyClient() self._aircraft_controls =",
"\"\"\" BlueSky simulation client class \"\"\" # TODO: Need to re-add the tests",
"Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout, ) def shutdown(self, shutdown_sim: bool = False) -> bool:",
"from typing import List from semver import VersionInfo from .bluesky_aircraft_controls import BlueSkyAircraftControls from",
"and not x.isspace() and x != \"None\" for x in map(str, args) ),",
"BlueSky only accepts commands in the form of (variable-length) strings, we need to",
"from .bluesky_aircraft_controls import BlueSkyAircraftControls from .bluesky_simulator_controls import BlueSkySimulatorControls from bluebird.settings import Settings from",
"map(str, args) ), f\"Invalid argument in : {args}\" class SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation for",
"API tests import os from typing import List from semver import VersionInfo from",
"-> VersionInfo: return self._client.host_version def __init__(self, **kwargs): self._client = BlueSkyClient() self._aircraft_controls = BlueSkyAircraftControls(self._client)",
"Since BlueSky only accepts commands in the form of (variable-length) strings, we need",
"return self._aircraft_controls @property def simulation(self) -> BlueSkySimulatorControls: return self._sim_controls @property def sim_version(self) ->",
"a cleaner way of doing this... assert all( x and not x.isspace() and",
"start_timers(self) -> List[Timer]: return self._client.start_timers() def connect(self, timeout=1) -> None: self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT,",
"import VersionInfo from .bluesky_aircraft_controls import BlueSkyAircraftControls from .bluesky_simulator_controls import BlueSkySimulatorControls from bluebird.settings import",
"variable must be set\") MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION) # TODO Check cases where we",
"self._aircraft_controls @property def simulation(self) -> BlueSkySimulatorControls: return self._sim_controls @property def sim_version(self) -> VersionInfo:",
"must be set\") MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION) # TODO Check cases where we need",
"typing import List from semver import VersionInfo from .bluesky_aircraft_controls import BlueSkyAircraftControls from .bluesky_simulator_controls",
"import BlueSkySimulatorControls from bluebird.settings import Settings from bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient from bluebird.utils.abstract_sim_client import",
"def simulation(self) -> BlueSkySimulatorControls: return self._sim_controls @property def sim_version(self) -> VersionInfo: return self._client.host_version",
"# TODO: Need to re-add the tests for string parsing/units from the old",
"TODO: Need to re-add the tests for string parsing/units from the old API",
"AbstractSimClient from bluebird.utils.timer import Timer _BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\") if not _BS_MIN_VERSION: raise ValueError(\"The",
"\"\"\" # Probably a cleaner way of doing this... assert all( x and",
"-> BlueSkyAircraftControls: return self._aircraft_controls @property def simulation(self) -> BlueSkySimulatorControls: return self._sim_controls @property def",
"the arguments for each command string we construct before sending it \"\"\" #",
"x in map(str, args) ), f\"Invalid argument in : {args}\" class SimClient(AbstractSimClient): \"\"\"AbstractSimClient",
"def start_timers(self) -> List[Timer]: return self._client.start_timers() def connect(self, timeout=1) -> None: self._client.connect( Settings.SIM_HOST,",
"self._client.start_timers() def connect(self, timeout=1) -> None: self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout, ) def",
"class \"\"\" # TODO: Need to re-add the tests for string parsing/units from",
"bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient from bluebird.utils.abstract_sim_client import AbstractSimClient from bluebird.utils.timer import Timer _BS_MIN_VERSION =",
"# Probably a cleaner way of doing this... assert all( x and not",
"bluebird.utils.abstract_sim_client import AbstractSimClient from bluebird.utils.timer import Timer _BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\") if not _BS_MIN_VERSION:",
"os.getenv(\"BS_MIN_VERSION\") if not _BS_MIN_VERSION: raise ValueError(\"The BS_MIN_VERSION environment variable must be set\") MIN_SIM_VERSION",
"BlueSkyAircraftControls from .bluesky_simulator_controls import BlueSkySimulatorControls from bluebird.settings import Settings from bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient",
"BlueSkyAircraftControls(self._client) self._sim_controls = BlueSkySimulatorControls(self._client) def start_timers(self) -> List[Timer]: return self._client.start_timers() def connect(self, timeout=1)",
"from bluebird.utils.abstract_sim_client import AbstractSimClient from bluebird.utils.timer import Timer _BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\") if not",
"set\") MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION) # TODO Check cases where we need this def",
"this def _assert_valid_args(args: list): \"\"\" Since BlueSky only accepts commands in the form",
"re-add the tests for string parsing/units from the old API tests import os",
"= BlueSkySimulatorControls(self._client) def start_timers(self) -> List[Timer]: return self._client.start_timers() def connect(self, timeout=1) -> None:",
"stream_port=Settings.BS_STREAM_PORT, timeout=timeout, ) def shutdown(self, shutdown_sim: bool = False) -> bool: self._client.stop() return",
"def _assert_valid_args(args: list): \"\"\" Since BlueSky only accepts commands in the form of",
"for each command string we construct before sending it \"\"\" # Probably a",
"BlueSkySimulatorControls(self._client) def start_timers(self) -> List[Timer]: return self._client.start_timers() def connect(self, timeout=1) -> None: self._client.connect(",
"aircraft(self) -> BlueSkyAircraftControls: return self._aircraft_controls @property def simulation(self) -> BlueSkySimulatorControls: return self._sim_controls @property",
"class SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation for BlueSky\"\"\" @property def aircraft(self) -> BlueSkyAircraftControls: return self._aircraft_controls",
"for BlueSky\"\"\" @property def aircraft(self) -> BlueSkyAircraftControls: return self._aircraft_controls @property def simulation(self) ->",
"connect(self, timeout=1) -> None: self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout, ) def shutdown(self, shutdown_sim:",
"client class \"\"\" # TODO: Need to re-add the tests for string parsing/units",
"the tests for string parsing/units from the old API tests import os from",
"of doing this... assert all( x and not x.isspace() and x != \"None\"",
"from bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient from bluebird.utils.abstract_sim_client import AbstractSimClient from bluebird.utils.timer import Timer _BS_MIN_VERSION",
"BS_MIN_VERSION environment variable must be set\") MIN_SIM_VERSION = VersionInfo.parse(_BS_MIN_VERSION) # TODO Check cases",
"from bluebird.utils.timer import Timer _BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\") if not _BS_MIN_VERSION: raise ValueError(\"The BS_MIN_VERSION",
"in the form of (variable-length) strings, we need to check the arguments for",
"assert all( x and not x.isspace() and x != \"None\" for x in",
"return self._client.start_timers() def connect(self, timeout=1) -> None: self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout, )",
"doing this... assert all( x and not x.isspace() and x != \"None\" for",
"it \"\"\" # Probably a cleaner way of doing this... assert all( x",
"self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout, ) def shutdown(self, shutdown_sim: bool = False) ->",
"x.isspace() and x != \"None\" for x in map(str, args) ), f\"Invalid argument",
"def sim_version(self) -> VersionInfo: return self._client.host_version def __init__(self, **kwargs): self._client = BlueSkyClient() self._aircraft_controls",
"None: self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout, ) def shutdown(self, shutdown_sim: bool = False)",
"for string parsing/units from the old API tests import os from typing import",
"from semver import VersionInfo from .bluesky_aircraft_controls import BlueSkyAircraftControls from .bluesky_simulator_controls import BlueSkySimulatorControls from",
"import Settings from bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient from bluebird.utils.abstract_sim_client import AbstractSimClient from bluebird.utils.timer import",
"{args}\" class SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation for BlueSky\"\"\" @property def aircraft(self) -> BlueSkyAircraftControls: return",
"VersionInfo: return self._client.host_version def __init__(self, **kwargs): self._client = BlueSkyClient() self._aircraft_controls = BlueSkyAircraftControls(self._client) self._sim_controls",
"bluebird.utils.timer import Timer _BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\") if not _BS_MIN_VERSION: raise ValueError(\"The BS_MIN_VERSION environment",
"_BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\") if not _BS_MIN_VERSION: raise ValueError(\"The BS_MIN_VERSION environment variable must be",
"arguments for each command string we construct before sending it \"\"\" # Probably",
"\"\"\"AbstractSimClient implementation for BlueSky\"\"\" @property def aircraft(self) -> BlueSkyAircraftControls: return self._aircraft_controls @property def",
"the form of (variable-length) strings, we need to check the arguments for each",
"VersionInfo.parse(_BS_MIN_VERSION) # TODO Check cases where we need this def _assert_valid_args(args: list): \"\"\"",
"self._aircraft_controls = BlueSkyAircraftControls(self._client) self._sim_controls = BlueSkySimulatorControls(self._client) def start_timers(self) -> List[Timer]: return self._client.start_timers() def",
"from bluebird.settings import Settings from bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient from bluebird.utils.abstract_sim_client import AbstractSimClient from",
"argument in : {args}\" class SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation for BlueSky\"\"\" @property def aircraft(self)",
"@property def aircraft(self) -> BlueSkyAircraftControls: return self._aircraft_controls @property def simulation(self) -> BlueSkySimulatorControls: return",
"if not _BS_MIN_VERSION: raise ValueError(\"The BS_MIN_VERSION environment variable must be set\") MIN_SIM_VERSION =",
"need to check the arguments for each command string we construct before sending",
"check the arguments for each command string we construct before sending it \"\"\"",
"string we construct before sending it \"\"\" # Probably a cleaner way of",
"__init__(self, **kwargs): self._client = BlueSkyClient() self._aircraft_controls = BlueSkyAircraftControls(self._client) self._sim_controls = BlueSkySimulatorControls(self._client) def start_timers(self)",
"-> None: self._client.connect( Settings.SIM_HOST, event_port=Settings.BS_EVENT_PORT, stream_port=Settings.BS_STREAM_PORT, timeout=timeout, ) def shutdown(self, shutdown_sim: bool =",
"Need to re-add the tests for string parsing/units from the old API tests",
"Settings from bluebird.sim_client.bluesky.bluesky_client import BlueSkyClient from bluebird.utils.abstract_sim_client import AbstractSimClient from bluebird.utils.timer import Timer",
"return self._sim_controls @property def sim_version(self) -> VersionInfo: return self._client.host_version def __init__(self, **kwargs): self._client",
"= BlueSkyClient() self._aircraft_controls = BlueSkyAircraftControls(self._client) self._sim_controls = BlueSkySimulatorControls(self._client) def start_timers(self) -> List[Timer]: return",
"BlueSkyClient from bluebird.utils.abstract_sim_client import AbstractSimClient from bluebird.utils.timer import Timer _BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\") if",
"_assert_valid_args(args: list): \"\"\" Since BlueSky only accepts commands in the form of (variable-length)",
"we need to check the arguments for each command string we construct before",
"Probably a cleaner way of doing this... assert all( x and not x.isspace()",
"-> BlueSkySimulatorControls: return self._sim_controls @property def sim_version(self) -> VersionInfo: return self._client.host_version def __init__(self,",
"import BlueSkyClient from bluebird.utils.abstract_sim_client import AbstractSimClient from bluebird.utils.timer import Timer _BS_MIN_VERSION = os.getenv(\"BS_MIN_VERSION\")",
"= os.getenv(\"BS_MIN_VERSION\") if not _BS_MIN_VERSION: raise ValueError(\"The BS_MIN_VERSION environment variable must be set\")",
"sending it \"\"\" # Probably a cleaner way of doing this... assert all(",
"we construct before sending it \"\"\" # Probably a cleaner way of doing",
"where we need this def _assert_valid_args(args: list): \"\"\" Since BlueSky only accepts commands",
"f\"Invalid argument in : {args}\" class SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation for BlueSky\"\"\" @property def",
"in map(str, args) ), f\"Invalid argument in : {args}\" class SimClient(AbstractSimClient): \"\"\"AbstractSimClient implementation"
] |
[
"if lns_pp == np.inf: print (\"***\\n***\\n2nd derivative of log of z/z0 is infinite.\\nWe",
"start xi from dxi rather than 0 to avoid singularity xi = np.copy(dxi)",
"this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_pp == np.inf: print (\"***\\n***\\n2nd derivative",
"[] ypp_arr = [] rho_arr = [] rhop_arr = [] P_arr = []",
"== 0: ## Newton method in the first loop lns += lns_p*dxi lns_p",
"= np.array(P_arr) M_arr = np.array(M_arr) v02_vr2_arr = np.array(v02_vr2_arr) temphi_arr = np.array(temphi_arr) ## return",
"lns_pp*dxi ############ ## adapt dxi ############ ## tolerance toler = 0.003 ## at",
"temphi_arr = np.array(temphi_arr) ## return the containers return lns_arr, lnsp_arr, lnspp_arr,\\ y_arr, yp_arr,",
"v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ## stop the loop when density is 1/1000 of the initial",
"initial value while gal.n(lns,y) > 1.e-3*gal.n0: ## second derivative of y and s",
"= gal.xi(co.parsec*0.01) ## the largest dxi elif dxi_suggest > gal.xi(co.parsec): dxi = gal.xi(co.parsec)",
"setup y = ins.y(xi) y_p = ins.y_p(xi) ## fugacity setup lns = 0.",
"dM M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break the loop",
"lns == np.inf: print (\"***\\n***\\nlog of z/z0 is infinite.\\nThis is full degeneracy limit.",
"= abs(n1-n2)/(n0*dxi) ## suggested dxi dxi_suggest = toler/error*dxi ## the smallest dxi if",
"lns_pp*dxi**2 lns_p = lnsp_arr[-2] + 2.*lns_pp*dxi ## for unrealistic temperature profiles temperature can",
"in the while loop N = 0 ## mass of galaxy M =",
"if lns == np.inf: print (\"***\\n***\\nlog of z/z0 is infinite.\\nThis is full degeneracy",
"temperature can turn negative ## break the loop and inform the user if",
"lns_p += lns_pp*dxi ############ ## adapt dxi ############ ## tolerance toler = 0.003",
"value while gal.n(lns,y) > 1.e-3*gal.n0: ## second derivative of y and s y_pp",
"r_arr = [] lns_arr = [] lnsp_arr = [] lnspp_arr = [] y_arr",
"galaxy(DM mass,n0,T0) gal = profile(ins.m,ins.n0,ins.T0) def SolveStability(): ## increments of xi dxi =",
"lnsp_arr = [] lnspp_arr = [] y_arr = [] yp_arr = [] ypp_arr",
"...\\n***\\n***\") break if lns_pp == np.inf: print (\"***\\n***\\n2nd derivative of log of z/z0",
"(\"***\\n***\\n2nd derivative of log of z/z0 is infinite.\\nWe can't handle this at this",
"yp_arr = np.array(yp_arr) ypp_arr = np.array(ypp_arr) lns_arr = np.array(lns_arr) lnsp_arr = np.array(lnsp_arr) r_arr",
"-lns_arr[-2] + 2.*lns + lns_pp*dxi**2 lns_p = lnsp_arr[-2] + 2.*lns_pp*dxi ## for unrealistic",
"## for unrealistic temperature profiles temperature can turn negative ## break the loop",
"ins.y(xi) y_p = ins.y_p(xi) ## determine s and y if N == 0:",
"= np.array(v02_vr2_arr) temphi_arr = np.array(temphi_arr) ## return the containers return lns_arr, lnsp_arr, lnspp_arr,\\",
"## tolerance toler = 0.003 ## at dxi/2. forward lns_12 = lns_arr[-1] +",
"user if derivative of density is infinite if gal.n_p(lns_p,lns,y_p,y) == np.inf: print (\"***\\n***\\nderivative",
"rather than 0 to avoid singularity xi = np.copy(dxi) ## temperature setup y",
"print (\"--\") except: ## this is just a print. no action needed pass",
"dxi = gal.xi(co.parsec) ## if in the range, accept the suggested dxi else:",
"############ ## tolerance toler = 0.003 ## at dxi/2. forward lns_12 = lns_arr[-1]",
"the Gravitational Potential energy temphi = 0. ## containers to store the outputs",
"gal.n(lns_,y) n0 = gal.n(lns_arr[-1],y_arr[-1]) error = abs(n1-n2)/(n0*dxi) ## suggested dxi dxi_suggest = toler/error*dxi",
"= np.array(lnsp_arr) r_arr = np.array(r_arr) rho_arr = np.array(rho_arr) P_arr = np.array(P_arr) M_arr =",
"lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try: if N%1000",
"= np.array(temphi_arr) ## return the containers return lns_arr, lnsp_arr, lnspp_arr,\\ y_arr, yp_arr, ypp_arr,\\",
"fugacity setup lns = 0. ## s0=1 =>lns0 = 0 lns_p = 0.",
"adapt ############ else: ## Verlet method lns = -lns_arr[-2] + 2.*lns + lns_pp*dxi**2",
"lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set the temperature and its derivative y = ins.y(xi)",
"= [] M_arr = [] v02_vr2_arr = [] temphi_arr = [] ## append",
"rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ## stop the loop when density is 1/1000",
"ypp_arr = np.array(ypp_arr) lns_arr = np.array(lns_arr) lnsp_arr = np.array(lnsp_arr) r_arr = np.array(r_arr) rho_arr",
"speed v02_vr2 = 0. ## To calculate the Gravitational Potential energy temphi =",
"print (\"M: %1.1e (sun)\"%(M/co.MSun)) print (\"--\") except: ## this is just a print.",
"dxi dxi_suggest = toler/error*dxi ## the smallest dxi if dxi_suggest < gal.xi(co.parsec*0.01): dxi",
"dxi/2. forward lns_12 = lns_arr[-1] + lns_p*(dxi/2.) lns_p_12 = lnsp_arr[-1] + lns_pp*(dxi/2.) ##",
"= np.array(M_arr) v02_vr2_arr = np.array(v02_vr2_arr) temphi_arr = np.array(temphi_arr) ## return the containers return",
"## adapt dxi ############ ## tolerance toler = 0.003 ## at dxi/2. forward",
"Galaxies import profile import Constants as co import Inputs as ins import warnings",
"the temperature and its derivative y = ins.y(xi) y_p = ins.y_p(xi) ## determine",
"infinite if gal.n_p(lns_p,lns,y_p,y) == np.inf: print (\"***\\n***\\nderivative of number density is infinite.\\nnumber density",
"## suggested dxi dxi_suggest = toler/error*dxi ## the smallest dxi if dxi_suggest <",
"np.copy(dxi) ## temperature setup y = ins.y(xi) y_p = ins.y_p(xi) ## fugacity setup",
"+ lns_p_12*(dxi/2.) lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ = lns_p_12 + lns_pp_12*(dxi/2.) ## compare densities",
"point.\\nBreaking the loop ...\\n***\\n***\") break if lns_p == np.inf: print (\"***\\n***\\n1st derivative of",
"np.array(M_arr) v02_vr2_arr = np.array(v02_vr2_arr) temphi_arr = np.array(temphi_arr) ## return the containers return lns_arr,",
"=>lns0 = 0 lns_p = 0. ## number of loops in the while",
"## return the containers return lns_arr, lnsp_arr, lnspp_arr,\\ y_arr, yp_arr, ypp_arr,\\ r_arr, rho_arr,",
"fugacity or its derivatives are infinite if lns == np.inf: print (\"***\\n***\\nlog of",
"M = M + dM M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi)",
"is infinite.\\nThis is full degeneracy limit. We can't handle this at this point.\\nBreaking",
"when density is 1/1000 of the initial value while gal.n(lns,y) > 1.e-3*gal.n0: ##",
"temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break the loop and inform the user if derivative",
"M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try: if N%1000 == 0 and N>0: print (\"r: %1.1e",
"2.*lns + lns_pp*dxi**2 lns_p = lnsp_arr[-2] + 2.*lns_pp*dxi ## for unrealistic temperature profiles",
"0 lns_p = 0. ## number of loops in the while loop N",
"M + dM M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break",
"lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T: %1.1e (Kelvin) y: %1.1e yp: %1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print",
"N+=1 ################################### ## convert the lists to numpy array y_arr = np.array(y_arr) yp_arr",
"gal.n(lns_arr[-1],y_arr[-1]) error = abs(n1-n2)/(n0*dxi) ## suggested dxi dxi_suggest = toler/error*dxi ## the smallest",
"numpy as np from Galaxies import profile import Constants as co import Inputs",
"import Constants as co import Inputs as ins import warnings ## a galaxy(DM",
"dxi if dxi_suggest < gal.xi(co.parsec*0.01): dxi = gal.xi(co.parsec*0.01) ## the largest dxi elif",
"temperature profiles temperature can turn negative ## break the loop and inform the",
"and inform the user if y < 0.: print (\"***\\n***\\nNegative temperature. Breaking ...\\n***\\n***\")",
"if dxi_suggest < gal.xi(co.parsec*0.01): dxi = gal.xi(co.parsec*0.01) ## the largest dxi elif dxi_suggest",
"temperature and its derivative y = ins.y(xi) y_p = ins.y_p(xi) ## determine s",
"+ lns_pp*(dxi/2.) ## at dxi lns_ = lns_12 + lns_p_12*(dxi/2.) lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.)",
"in SI units using M = M + dM M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2",
"= lns_12 + lns_p_12*(dxi/2.) lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ = lns_p_12 + lns_pp_12*(dxi/2.) ##",
"= [] rhop_arr = [] P_arr = [] M_arr = [] v02_vr2_arr =",
"avoid singularity xi = np.copy(dxi) ## temperature setup y = ins.y(xi) y_p =",
"handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break ## add the calculated",
"fall to zero.\\nthis is usually the edge of the system.\\nBreaking the while loop",
"co import Inputs as ins import warnings ## a galaxy(DM mass,n0,T0) gal =",
"lns_p == np.inf: print (\"***\\n***\\n1st derivative of log of z/z0 is infinite.\\nWe can't",
"gal.n(lns,y) n2 = gal.n(lns_,y) n0 = gal.n(lns_arr[-1],y_arr[-1]) error = abs(n1-n2)/(n0*dxi) ## suggested dxi",
"raise(Exception(\"Negative temperature. Unacceptable solution\")) break ## determine xi xi += dxi ## mass",
"determine xi xi += dxi ## mass at radius r in SI units",
"this at this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_pp == np.inf: print",
"< 0.: print (\"***\\n***\\nNegative temperature. Breaking ...\\n***\\n***\") raise(Exception(\"Negative temperature. Unacceptable solution\")) break ##",
"xi = np.copy(dxi) ## temperature setup y = ins.y(xi) y_p = ins.y_p(xi) ##",
"of the initial value while gal.n(lns,y) > 1.e-3*gal.n0: ## second derivative of y",
"gal.xi(co.parsec): dxi = gal.xi(co.parsec) ## if in the range, accept the suggested dxi",
"= ins.y(xi) y_p = ins.y_p(xi) ## determine s and y if N ==",
"this point.\\nBreaking the loop ...\\n***\\n***\") break ## add the calculated quantities into the",
"+ lns_pp*dxi**2 lns_p = lnsp_arr[-2] + 2.*lns_pp*dxi ## for unrealistic temperature profiles temperature",
"y = ins.y(xi) y_p = ins.y_p(xi) ## fugacity setup lns = 0. ##",
"+ dM M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break the",
"the loop and inform the user if y < 0.: print (\"***\\n***\\nNegative temperature.",
"+= dxi ## mass at radius r in SI units using M =",
"containers to store the outputs xi_arr = [] r_arr = [] lns_arr =",
"(\"T: %1.1e (Kelvin) y: %1.1e yp: %1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n: %1.1e (1/m^3)",
"the first loop lns += lns_p*dxi lns_p += lns_pp*dxi ############ ## adapt dxi",
"can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_p ==",
"pass ## change the counter N+=1 ################################### ## convert the lists to numpy",
"its derivatives are infinite if lns == np.inf: print (\"***\\n***\\nlog of z/z0 is",
"the loop and inform the user if derivative of density is infinite if",
"print (\"***\\n***\\n2nd derivative of log of z/z0 is infinite.\\nWe can't handle this at",
"energy temphi = 0. ## containers to store the outputs xi_arr = []",
"= profile(ins.m,ins.n0,ins.T0) def SolveStability(): ## increments of xi dxi = gal.xi(co.parsec*0.1) ## start",
"at this point.\\nBreaking the loop ...\\n***\\n***\") break ## add the calculated quantities into",
"= 0. ## s0=1 =>lns0 = 0 lns_p = 0. ## number of",
"xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2)",
"derivative of log of z/z0 is infinite.\\nWe can't handle this at this point.\\nBreaking",
"v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try: if N%1000 == 0 and N>0: print (\"r: %1.1e (kpc)",
"M = 0. ## for free falling speed v02_vr2 = 0. ## To",
"<NAME>, PhD email : <EMAIL> affiliation: Baylor University \"\"\" import numpy as np",
"the lists to numpy array y_arr = np.array(y_arr) yp_arr = np.array(yp_arr) ypp_arr =",
"gal = profile(ins.m,ins.n0,ins.T0) def SolveStability(): ## increments of xi dxi = gal.xi(co.parsec*0.1) ##",
"np.inf: print (\"***\\n***\\n1st derivative of log of z/z0 is infinite.\\nWe can't handle this",
"ypp_arr = [] rho_arr = [] rhop_arr = [] P_arr = [] M_arr",
"ins import warnings ## a galaxy(DM mass,n0,T0) gal = profile(ins.m,ins.n0,ins.T0) def SolveStability(): ##",
"the user if y < 0.: print (\"***\\n***\\nNegative temperature. Breaking ...\\n***\\n***\") raise(Exception(\"Negative temperature.",
"the largest dxi elif dxi_suggest > gal.xi(co.parsec): dxi = gal.xi(co.parsec) ## if in",
"into the containers xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y))",
"smallest dxi if dxi_suggest < gal.xi(co.parsec*0.01): dxi = gal.xi(co.parsec*0.01) ## the largest dxi",
"dxi = gal.xi(co.parsec*0.1) ## start xi from dxi rather than 0 to avoid",
"0. ## To calculate the Gravitational Potential energy temphi = 0. ## containers",
"lnsp: %1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T: %1.1e (Kelvin) y: %1.1e yp: %1.1e ypp:",
"gal.n_p(lns_p,lns,y_p,y) == np.inf: print (\"***\\n***\\nderivative of number density is infinite.\\nnumber density will sharply",
"dxi ## mass at radius r in SI units using M = M",
"mass of galaxy M = 0. ## for free falling speed v02_vr2 =",
"y_p = ins.y_p(xi) ## determine s and y if N == 0: ##",
"lnsp_arr[-1] + lns_pp*(dxi/2.) ## at dxi lns_ = lns_12 + lns_p_12*(dxi/2.) lns_pp_12 =",
"is infinite.\\nnumber density will sharply fall to zero.\\nthis is usually the edge of",
"lns += lns_p*dxi lns_p += lns_pp*dxi ############ ## adapt dxi ############ ## tolerance",
"< gal.xi(co.parsec*0.01): dxi = gal.xi(co.parsec*0.01) ## the largest dxi elif dxi_suggest > gal.xi(co.parsec):",
"to numpy array y_arr = np.array(y_arr) yp_arr = np.array(yp_arr) ypp_arr = np.array(ypp_arr) lns_arr",
"M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break the loop and",
"## the largest dxi elif dxi_suggest > gal.xi(co.parsec): dxi = gal.xi(co.parsec) ## if",
"M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ## stop the loop when density is 1/1000 of the",
"is 1/1000 of the initial value while gal.n(lns,y) > 1.e-3*gal.n0: ## second derivative",
"= [] y_arr = [] yp_arr = [] ypp_arr = [] rho_arr =",
"= gal.n(lns,y) n2 = gal.n(lns_,y) n0 = gal.n(lns_arr[-1],y_arr[-1]) error = abs(n1-n2)/(n0*dxi) ## suggested",
"density is 1/1000 of the initial value while gal.n(lns,y) > 1.e-3*gal.n0: ## second",
"## fugacity setup lns = 0. ## s0=1 =>lns0 = 0 lns_p =",
"temphi_arr.append(temphi) try: if N%1000 == 0 and N>0: print (\"r: %1.1e (kpc) xi:",
"0. ## containers to store the outputs xi_arr = [] r_arr = []",
"np.array(v02_vr2_arr) temphi_arr = np.array(temphi_arr) ## return the containers return lns_arr, lnsp_arr, lnspp_arr,\\ y_arr,",
"P_arr = np.array(P_arr) M_arr = np.array(M_arr) v02_vr2_arr = np.array(v02_vr2_arr) temphi_arr = np.array(temphi_arr) ##",
"Inputs as ins import warnings ## a galaxy(DM mass,n0,T0) gal = profile(ins.m,ins.n0,ins.T0) def",
"xi xi += dxi ## mass at radius r in SI units using",
"while loop ...\\n***\\n***\") break ## break the loop and inform the user if",
"We can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_p",
"a galaxy(DM mass,n0,T0) gal = profile(ins.m,ins.n0,ins.T0) def SolveStability(): ## increments of xi dxi",
"gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ = lns_p_12 + lns_pp_12*(dxi/2.) ## compare densities n1 = gal.n(lns,y) n2",
"z/z0 is infinite.\\nWe can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break",
"degeneracy limit. We can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break",
"handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_pp == np.inf:",
"dxi: %g (pc)\"%(dxi/gal.xi(co.parsec))) ############ ## end adapt ############ else: ## Verlet method lns",
"break if lns_p == np.inf: print (\"***\\n***\\n1st derivative of log of z/z0 is",
"affiliation: Baylor University \"\"\" import numpy as np from Galaxies import profile import",
"profile import Constants as co import Inputs as ins import warnings ## a",
"= 0. ## To calculate the Gravitational Potential energy temphi = 0. ##",
"+ lns_pp_12*(dxi/2.) ## compare densities n1 = gal.n(lns,y) n2 = gal.n(lns_,y) n0 =",
"= [] rho_arr = [] rhop_arr = [] P_arr = [] M_arr =",
"## at dxi lns_ = lns_12 + lns_p_12*(dxi/2.) lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ =",
"np.array(lns_arr) lnsp_arr = np.array(lnsp_arr) r_arr = np.array(r_arr) rho_arr = np.array(rho_arr) P_arr = np.array(P_arr)",
"(kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M: %1.1e (sun)\"%(M/co.MSun)) print (\"--\") except: ## this is just a",
"numpy array y_arr = np.array(y_arr) yp_arr = np.array(yp_arr) ypp_arr = np.array(ypp_arr) lns_arr =",
"break the loop and inform the user if fugacity or its derivatives are",
"\"\"\" Created on May 19 2019 author : <NAME>, PhD email : <EMAIL>",
"P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try: if N%1000 == 0 and N>0: print (\"r:",
"warnings ## a galaxy(DM mass,n0,T0) gal = profile(ins.m,ins.n0,ins.T0) def SolveStability(): ## increments of",
"= np.array(lns_arr) lnsp_arr = np.array(lnsp_arr) r_arr = np.array(r_arr) rho_arr = np.array(rho_arr) P_arr =",
"= [] lnsp_arr = [] lnspp_arr = [] y_arr = [] yp_arr =",
"np.array(P_arr) M_arr = np.array(M_arr) v02_vr2_arr = np.array(v02_vr2_arr) temphi_arr = np.array(temphi_arr) ## return the",
"dxi ############ ## tolerance toler = 0.003 ## at dxi/2. forward lns_12 =",
"radius r in SI units using M = M + dM M +=",
"## set the temperature and its derivative y = ins.y(xi) y_p = ins.y_p(xi)",
"%1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz: %1.1e lns: %1.1e lnsp: %1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T:",
"user if fugacity or its derivatives are infinite if lns == np.inf: print",
"tolerance toler = 0.003 ## at dxi/2. forward lns_12 = lns_arr[-1] + lns_p*(dxi/2.)",
"adapt dxi ############ ## tolerance toler = 0.003 ## at dxi/2. forward lns_12",
"is infinite.\\nWe can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break ##",
"array y_arr = np.array(y_arr) yp_arr = np.array(yp_arr) ypp_arr = np.array(ypp_arr) lns_arr = np.array(lns_arr)",
"ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try: if N%1000 == 0 and",
"lists to numpy array y_arr = np.array(y_arr) yp_arr = np.array(yp_arr) ypp_arr = np.array(ypp_arr)",
"on May 19 2019 author : <NAME>, PhD email : <EMAIL> affiliation: Baylor",
"error = abs(n1-n2)/(n0*dxi) ## suggested dxi dxi_suggest = toler/error*dxi ## the smallest dxi",
"## add the calculated quantities into the containers xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp)",
"print (\"r: %1.1e (kpc) xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz: %1.1e lns: %1.1e lnsp:",
"return lns_arr, lnsp_arr, lnspp_arr,\\ y_arr, yp_arr, ypp_arr,\\ r_arr, rho_arr, P_arr,\\ M_arr, v02_vr2_arr, temphi_arr",
"append the initial values xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y))",
"infinite if lns == np.inf: print (\"***\\n***\\nlog of z/z0 is infinite.\\nThis is full",
"%g (pc)\"%(dxi/gal.xi(co.parsec))) ############ ## end adapt ############ else: ## Verlet method lns =",
"y_pp = ins.y_pp(xi) lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set the temperature and its derivative",
"suggested dxi dxi_suggest = toler/error*dxi ## the smallest dxi if dxi_suggest < gal.xi(co.parsec*0.01):",
"loop and inform the user if y < 0.: print (\"***\\n***\\nNegative temperature. Breaking",
"0 and N>0: print (\"r: %1.1e (kpc) xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz: %1.1e",
"falling speed v02_vr2 = 0. ## To calculate the Gravitational Potential energy temphi",
"(\"***\\n***\\nderivative of number density is infinite.\\nnumber density will sharply fall to zero.\\nthis is",
"number of loops in the while loop N = 0 ## mass of",
"email : <EMAIL> affiliation: Baylor University \"\"\" import numpy as np from Galaxies",
"%1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n: %1.1e (1/m^3) rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M: %1.1e (sun)\"%(M/co.MSun)) print",
"author : <NAME>, PhD email : <EMAIL> affiliation: Baylor University \"\"\" import numpy",
"xi_arr = [] r_arr = [] lns_arr = [] lnsp_arr = [] lnspp_arr",
"[] r_arr = [] lns_arr = [] lnsp_arr = [] lnspp_arr = []",
"the user if derivative of density is infinite if gal.n_p(lns_p,lns,y_p,y) == np.inf: print",
"gal.xi(co.parsec*0.01): dxi = gal.xi(co.parsec*0.01) ## the largest dxi elif dxi_suggest > gal.xi(co.parsec): dxi",
"= [] yp_arr = [] ypp_arr = [] rho_arr = [] rhop_arr =",
"= 0 lns_p = 0. ## number of loops in the while loop",
"can turn negative ## break the loop and inform the user if y",
"lns_p = lnsp_arr[-2] + 2.*lns_pp*dxi ## for unrealistic temperature profiles temperature can turn",
"densities n1 = gal.n(lns,y) n2 = gal.n(lns_,y) n0 = gal.n(lns_arr[-1],y_arr[-1]) error = abs(n1-n2)/(n0*dxi)",
"4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break the loop and inform the",
"lns_pp_12*(dxi/2.) ## compare densities n1 = gal.n(lns,y) n2 = gal.n(lns_,y) n0 = gal.n(lns_arr[-1],y_arr[-1])",
"rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try: if N%1000 == 0 and N>0:",
"(kpc) xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz: %1.1e lns: %1.1e lnsp: %1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp))",
"Potential energy temphi = 0. ## containers to store the outputs xi_arr =",
"system.\\nBreaking the while loop ...\\n***\\n***\") break ## break the loop and inform the",
"lns_p_12 = lnsp_arr[-1] + lns_pp*(dxi/2.) ## at dxi lns_ = lns_12 + lns_p_12*(dxi/2.)",
"zero.\\nthis is usually the edge of the system.\\nBreaking the while loop ...\\n***\\n***\") break",
"solution\")) break ## determine xi xi += dxi ## mass at radius r",
"= ins.y(xi) y_p = ins.y_p(xi) ## fugacity setup lns = 0. ## s0=1",
"the smallest dxi if dxi_suggest < gal.xi(co.parsec*0.01): dxi = gal.xi(co.parsec*0.01) ## the largest",
"z/z0 is infinite.\\nThis is full degeneracy limit. We can't handle this at this",
"of galaxy M = 0. ## for free falling speed v02_vr2 = 0.",
"the user if fugacity or its derivatives are infinite if lns == np.inf:",
"## number of loops in the while loop N = 0 ## mass",
"## break the loop and inform the user if y < 0.: print",
"+= lns_pp*dxi ############ ## adapt dxi ############ ## tolerance toler = 0.003 ##",
"## change the counter N+=1 ################################### ## convert the lists to numpy array",
"the calculated quantities into the containers xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p)",
"loop and inform the user if derivative of density is infinite if gal.n_p(lns_p,lns,y_p,y)",
"## at dxi/2. forward lns_12 = lns_arr[-1] + lns_p*(dxi/2.) lns_p_12 = lnsp_arr[-1] +",
"break ## break the loop and inform the user if fugacity or its",
"rho_arr = [] rhop_arr = [] P_arr = [] M_arr = [] v02_vr2_arr",
"toler/error*dxi ## the smallest dxi if dxi_suggest < gal.xi(co.parsec*0.01): dxi = gal.xi(co.parsec*0.01) ##",
"lns_arr = [] lnsp_arr = [] lnspp_arr = [] y_arr = [] yp_arr",
"for unrealistic temperature profiles temperature can turn negative ## break the loop and",
"## break the loop and inform the user if fugacity or its derivatives",
"lnsp_arr[-2] + 2.*lns_pp*dxi ## for unrealistic temperature profiles temperature can turn negative ##",
"turn negative ## break the loop and inform the user if y <",
"## end adapt ############ else: ## Verlet method lns = -lns_arr[-2] + 2.*lns",
"temperature. Breaking ...\\n***\\n***\") raise(Exception(\"Negative temperature. Unacceptable solution\")) break ## determine xi xi +=",
"+ 2.*lns_pp*dxi ## for unrealistic temperature profiles temperature can turn negative ## break",
"############ else: ## Verlet method lns = -lns_arr[-2] + 2.*lns + lns_pp*dxi**2 lns_p",
"inform the user if fugacity or its derivatives are infinite if lns ==",
"loop ...\\n***\\n***\") break ## add the calculated quantities into the containers xi_arr.append(xi) r_arr.append(gal.r(xi))",
"ins.y_p(xi) ## determine s and y if N == 0: ## Newton method",
"while gal.n(lns,y) > 1.e-3*gal.n0: ## second derivative of y and s y_pp =",
"= gal.xi(co.parsec) ## if in the range, accept the suggested dxi else: dxi",
"of y and s y_pp = ins.y_pp(xi) lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set the",
"and s y_pp = ins.y_pp(xi) lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set the temperature and",
"Newton method in the first loop lns += lns_p*dxi lns_p += lns_pp*dxi ############",
"\"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz: %1.1e lns: %1.1e lnsp: %1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T: %1.1e",
"if lns_p == np.inf: print (\"***\\n***\\n1st derivative of log of z/z0 is infinite.\\nWe",
"the loop ...\\n***\\n***\") break ## add the calculated quantities into the containers xi_arr.append(xi)",
"dxi else: dxi = dxi_suggest print(\"new dxi: %g (pc)\"%(dxi/gal.xi(co.parsec))) ############ ## end adapt",
": <EMAIL> affiliation: Baylor University \"\"\" import numpy as np from Galaxies import",
"+= 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break the loop and inform",
"the loop ...\\n***\\n***\") break if lns_pp == np.inf: print (\"***\\n***\\n2nd derivative of log",
"np.inf: print (\"***\\n***\\nlog of z/z0 is infinite.\\nThis is full degeneracy limit. We can't",
"unrealistic temperature profiles temperature can turn negative ## break the loop and inform",
"units using M = M + dM M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi",
"%1.1e yp: %1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n: %1.1e (1/m^3) rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print",
"at dxi lns_ = lns_12 + lns_p_12*(dxi/2.) lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ = lns_p_12",
"(\"n: %1.1e (1/m^3) rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M: %1.1e (sun)\"%(M/co.MSun)) print (\"--\") except:",
"elif dxi_suggest > gal.xi(co.parsec): dxi = gal.xi(co.parsec) ## if in the range, accept",
"lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try:",
"and inform the user if derivative of density is infinite if gal.n_p(lns_p,lns,y_p,y) ==",
"dxi_suggest = toler/error*dxi ## the smallest dxi if dxi_suggest < gal.xi(co.parsec*0.01): dxi =",
"= gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ = lns_p_12 + lns_pp_12*(dxi/2.) ## compare densities n1 = gal.n(lns,y)",
"lns = 0. ## s0=1 =>lns0 = 0 lns_p = 0. ## number",
"np.inf: print (\"***\\n***\\n2nd derivative of log of z/z0 is infinite.\\nWe can't handle this",
"lns_p = 0. ## number of loops in the while loop N =",
"calculate the Gravitational Potential energy temphi = 0. ## containers to store the",
"store the outputs xi_arr = [] r_arr = [] lns_arr = [] lnsp_arr",
"lnspp_arr = [] y_arr = [] yp_arr = [] ypp_arr = [] rho_arr",
"## append the initial values xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.)",
"temperature. Unacceptable solution\")) break ## determine xi xi += dxi ## mass at",
"infinite.\\nWe can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break ## add",
"%1.1e (1/m^3) rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M: %1.1e (sun)\"%(M/co.MSun)) print (\"--\") except: ##",
"## increments of xi dxi = gal.xi(co.parsec*0.1) ## start xi from dxi rather",
"y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ## stop the loop",
"[] lnspp_arr = [] y_arr = [] yp_arr = [] ypp_arr = []",
"rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M: %1.1e (sun)\"%(M/co.MSun)) print (\"--\") except: ## this is",
"as co import Inputs as ins import warnings ## a galaxy(DM mass,n0,T0) gal",
"## containers to store the outputs xi_arr = [] r_arr = [] lns_arr",
"set the temperature and its derivative y = ins.y(xi) y_p = ins.y_p(xi) ##",
"and y if N == 0: ## Newton method in the first loop",
"y = ins.y(xi) y_p = ins.y_p(xi) ## determine s and y if N",
"calculated quantities into the containers xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp)",
"ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n: %1.1e (1/m^3) rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M: %1.1e (sun)\"%(M/co.MSun))",
"r_arr = np.array(r_arr) rho_arr = np.array(rho_arr) P_arr = np.array(P_arr) M_arr = np.array(M_arr) v02_vr2_arr",
"## this is just a print. no action needed pass ## change the",
"derivative of y and s y_pp = ins.y_pp(xi) lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set",
"density is infinite if gal.n_p(lns_p,lns,y_p,y) == np.inf: print (\"***\\n***\\nderivative of number density is",
"inform the user if derivative of density is infinite if gal.n_p(lns_p,lns,y_p,y) == np.inf:",
"xi dxi = gal.xi(co.parsec*0.1) ## start xi from dxi rather than 0 to",
"np.array(r_arr) rho_arr = np.array(rho_arr) P_arr = np.array(P_arr) M_arr = np.array(M_arr) v02_vr2_arr = np.array(v02_vr2_arr)",
"n1 = gal.n(lns,y) n2 = gal.n(lns_,y) n0 = gal.n(lns_arr[-1],y_arr[-1]) error = abs(n1-n2)/(n0*dxi) ##",
"n2 = gal.n(lns_,y) n0 = gal.n(lns_arr[-1],y_arr[-1]) error = abs(n1-n2)/(n0*dxi) ## suggested dxi dxi_suggest",
"usually the edge of the system.\\nBreaking the while loop ...\\n***\\n***\") break ## break",
"(\"***\\n***\\nNegative temperature. Breaking ...\\n***\\n***\") raise(Exception(\"Negative temperature. Unacceptable solution\")) break ## determine xi xi",
"ins.y_p(xi) ## fugacity setup lns = 0. ## s0=1 =>lns0 = 0 lns_p",
"np.array(ypp_arr) lns_arr = np.array(lns_arr) lnsp_arr = np.array(lnsp_arr) r_arr = np.array(r_arr) rho_arr = np.array(rho_arr)",
"the initial value while gal.n(lns,y) > 1.e-3*gal.n0: ## second derivative of y and",
"0.003 ## at dxi/2. forward lns_12 = lns_arr[-1] + lns_p*(dxi/2.) lns_p_12 = lnsp_arr[-1]",
"compare densities n1 = gal.n(lns,y) n2 = gal.n(lns_,y) n0 = gal.n(lns_arr[-1],y_arr[-1]) error =",
"if y < 0.: print (\"***\\n***\\nNegative temperature. Breaking ...\\n***\\n***\") raise(Exception(\"Negative temperature. Unacceptable solution\"))",
"quantities into the containers xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y))",
"## break the loop and inform the user if derivative of density is",
"gal.n(lns,y) > 1.e-3*gal.n0: ## second derivative of y and s y_pp = ins.y_pp(xi)",
"## for free falling speed v02_vr2 = 0. ## To calculate the Gravitational",
"containers xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M)",
"largest dxi elif dxi_suggest > gal.xi(co.parsec): dxi = gal.xi(co.parsec) ## if in the",
"in the first loop lns += lns_p*dxi lns_p += lns_pp*dxi ############ ## adapt",
"else: dxi = dxi_suggest print(\"new dxi: %g (pc)\"%(dxi/gal.xi(co.parsec))) ############ ## end adapt ############",
"%1.1e (sun)\"%(M/co.MSun)) print (\"--\") except: ## this is just a print. no action",
"(Kelvin) y: %1.1e yp: %1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n: %1.1e (1/m^3) rho: %1.1e",
"0 to avoid singularity xi = np.copy(dxi) ## temperature setup y = ins.y(xi)",
"temphi_arr = [] ## append the initial values xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.)",
"np from Galaxies import profile import Constants as co import Inputs as ins",
"y_p = ins.y_p(xi) ## fugacity setup lns = 0. ## s0=1 =>lns0 =",
"the while loop N = 0 ## mass of galaxy M = 0.",
"## mass of galaxy M = 0. ## for free falling speed v02_vr2",
"[] P_arr = [] M_arr = [] v02_vr2_arr = [] temphi_arr = []",
"import Inputs as ins import warnings ## a galaxy(DM mass,n0,T0) gal = profile(ins.m,ins.n0,ins.T0)",
"at this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_pp == np.inf: print (\"***\\n***\\n2nd",
"## Verlet method lns = -lns_arr[-2] + 2.*lns + lns_pp*dxi**2 lns_p = lnsp_arr[-2]",
"PhD email : <EMAIL> affiliation: Baylor University \"\"\" import numpy as np from",
"= [] P_arr = [] M_arr = [] v02_vr2_arr = [] temphi_arr =",
"loop ...\\n***\\n***\") break ## break the loop and inform the user if fugacity",
"(\"r: %1.1e (kpc) xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz: %1.1e lns: %1.1e lnsp: %1.1e",
"of log of z/z0 is infinite.\\nWe can't handle this at this point.\\nBreaking the",
"## temperature setup y = ins.y(xi) y_p = ins.y_p(xi) ## fugacity setup lns",
"its derivative y = ins.y(xi) y_p = ins.y_p(xi) ## determine s and y",
"v02_vr2_arr = np.array(v02_vr2_arr) temphi_arr = np.array(temphi_arr) ## return the containers return lns_arr, lnsp_arr,",
"print(\"new dxi: %g (pc)\"%(dxi/gal.xi(co.parsec))) ############ ## end adapt ############ else: ## Verlet method",
"= ins.y_pp(xi) lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set the temperature and its derivative y",
"SI units using M = M + dM M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2",
"as ins import warnings ## a galaxy(DM mass,n0,T0) gal = profile(ins.m,ins.n0,ins.T0) def SolveStability():",
"np.array(temphi_arr) ## return the containers return lns_arr, lnsp_arr, lnspp_arr,\\ y_arr, yp_arr, ypp_arr,\\ r_arr,",
"method in the first loop lns += lns_p*dxi lns_p += lns_pp*dxi ############ ##",
"this is just a print. no action needed pass ## change the counter",
"dxi = gal.xi(co.parsec*0.01) ## the largest dxi elif dxi_suggest > gal.xi(co.parsec): dxi =",
"xi from dxi rather than 0 to avoid singularity xi = np.copy(dxi) ##",
"lns_p_12*(dxi/2.) lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ = lns_p_12 + lns_pp_12*(dxi/2.) ## compare densities n1",
"## if in the range, accept the suggested dxi else: dxi = dxi_suggest",
"try: if N%1000 == 0 and N>0: print (\"r: %1.1e (kpc) xi: %1.1e",
"[] rhop_arr = [] P_arr = [] M_arr = [] v02_vr2_arr = []",
"Created on May 19 2019 author : <NAME>, PhD email : <EMAIL> affiliation:",
"negative ## break the loop and inform the user if y < 0.:",
"+ 2.*lns + lns_pp*dxi**2 lns_p = lnsp_arr[-2] + 2.*lns_pp*dxi ## for unrealistic temperature",
"return the containers return lns_arr, lnsp_arr, lnspp_arr,\\ y_arr, yp_arr, ypp_arr,\\ r_arr, rho_arr, P_arr,\\",
"infinite.\\nnumber density will sharply fall to zero.\\nthis is usually the edge of the",
"To calculate the Gravitational Potential energy temphi = 0. ## containers to store",
"############ ## end adapt ############ else: ## Verlet method lns = -lns_arr[-2] +",
"= np.array(r_arr) rho_arr = np.array(rho_arr) P_arr = np.array(P_arr) M_arr = np.array(M_arr) v02_vr2_arr =",
"break ## determine xi xi += dxi ## mass at radius r in",
"N == 0: ## Newton method in the first loop lns += lns_p*dxi",
"= lnsp_arr[-1] + lns_pp*(dxi/2.) ## at dxi lns_ = lns_12 + lns_p_12*(dxi/2.) lns_pp_12",
"action needed pass ## change the counter N+=1 ################################### ## convert the lists",
"galaxy M = 0. ## for free falling speed v02_vr2 = 0. ##",
"of z/z0 is infinite.\\nThis is full degeneracy limit. We can't handle this at",
"lns: %1.1e lnsp: %1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T: %1.1e (Kelvin) y: %1.1e yp:",
"(1/m^3) rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M: %1.1e (sun)\"%(M/co.MSun)) print (\"--\") except: ## this",
"== np.inf: print (\"***\\n***\\n2nd derivative of log of z/z0 is infinite.\\nWe can't handle",
"= ins.y_p(xi) ## determine s and y if N == 0: ## Newton",
"and inform the user if fugacity or its derivatives are infinite if lns",
"n0 = gal.n(lns_arr[-1],y_arr[-1]) error = abs(n1-n2)/(n0*dxi) ## suggested dxi dxi_suggest = toler/error*dxi ##",
"this at this point.\\nBreaking the loop ...\\n***\\n***\") break ## add the calculated quantities",
"[] temphi_arr = [] ## append the initial values xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p)",
"lns_12 = lns_arr[-1] + lns_p*(dxi/2.) lns_p_12 = lnsp_arr[-1] + lns_pp*(dxi/2.) ## at dxi",
"= gal.xi(co.parsec*0.1) ## start xi from dxi rather than 0 to avoid singularity",
"mass,n0,T0) gal = profile(ins.m,ins.n0,ins.T0) def SolveStability(): ## increments of xi dxi = gal.xi(co.parsec*0.1)",
"2019 author : <NAME>, PhD email : <EMAIL> affiliation: Baylor University \"\"\" import",
"handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_p == np.inf:",
"= lns_arr[-1] + lns_p*(dxi/2.) lns_p_12 = lnsp_arr[-1] + lns_pp*(dxi/2.) ## at dxi lns_",
"while loop N = 0 ## mass of galaxy M = 0. ##",
"N = 0 ## mass of galaxy M = 0. ## for free",
"= [] lns_arr = [] lnsp_arr = [] lnspp_arr = [] y_arr =",
"this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_p == np.inf: print (\"***\\n***\\n1st derivative",
"def SolveStability(): ## increments of xi dxi = gal.xi(co.parsec*0.1) ## start xi from",
"gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break the loop and inform the user if derivative of density",
"temphi_arr.append(temphi) ## stop the loop when density is 1/1000 of the initial value",
"infinite.\\nThis is full degeneracy limit. We can't handle this at this point.\\nBreaking the",
"= np.array(y_arr) yp_arr = np.array(yp_arr) ypp_arr = np.array(ypp_arr) lns_arr = np.array(lns_arr) lnsp_arr =",
"first loop lns += lns_p*dxi lns_p += lns_pp*dxi ############ ## adapt dxi ############",
"the loop ...\\n***\\n***\") break if lns_p == np.inf: print (\"***\\n***\\n1st derivative of log",
"of loops in the while loop N = 0 ## mass of galaxy",
"dxi lns_ = lns_12 + lns_p_12*(dxi/2.) lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ = lns_p_12 +",
"gal.xi(co.parsec*0.01) ## the largest dxi elif dxi_suggest > gal.xi(co.parsec): dxi = gal.xi(co.parsec) ##",
"lns_pp*(dxi/2.) ## at dxi lns_ = lns_12 + lns_p_12*(dxi/2.) lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_",
"[] M_arr = [] v02_vr2_arr = [] temphi_arr = [] ## append the",
"[] yp_arr = [] ypp_arr = [] rho_arr = [] rhop_arr = []",
"y if N == 0: ## Newton method in the first loop lns",
"if gal.n_p(lns_p,lns,y_p,y) == np.inf: print (\"***\\n***\\nderivative of number density is infinite.\\nnumber density will",
"= dxi_suggest print(\"new dxi: %g (pc)\"%(dxi/gal.xi(co.parsec))) ############ ## end adapt ############ else: ##",
"...\\n***\\n***\") raise(Exception(\"Negative temperature. Unacceptable solution\")) break ## determine xi xi += dxi ##",
"(\"--\") except: ## this is just a print. no action needed pass ##",
"print (\"***\\n***\\nNegative temperature. Breaking ...\\n***\\n***\") raise(Exception(\"Negative temperature. Unacceptable solution\")) break ## determine xi",
"at dxi/2. forward lns_12 = lns_arr[-1] + lns_p*(dxi/2.) lns_p_12 = lnsp_arr[-1] + lns_pp*(dxi/2.)",
"of density is infinite if gal.n_p(lns_p,lns,y_p,y) == np.inf: print (\"***\\n***\\nderivative of number density",
"of xi dxi = gal.xi(co.parsec*0.1) ## start xi from dxi rather than 0",
"gal.xi(co.parsec) ## if in the range, accept the suggested dxi else: dxi =",
"lns_p_ = lns_p_12 + lns_pp_12*(dxi/2.) ## compare densities n1 = gal.n(lns,y) n2 =",
"if derivative of density is infinite if gal.n_p(lns_p,lns,y_p,y) == np.inf: print (\"***\\n***\\nderivative of",
"log of z/z0 is infinite.\\nWe can't handle this at this point.\\nBreaking the loop",
"[] ## append the initial values xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p)",
"...\\n***\\n***\") break ## add the calculated quantities into the containers xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns)",
"lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try: if",
"%1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n: %1.1e (1/m^3) rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M: %1.1e",
"temperature setup y = ins.y(xi) y_p = ins.y_p(xi) ## fugacity setup lns =",
"1/1000 of the initial value while gal.n(lns,y) > 1.e-3*gal.n0: ## second derivative of",
"y: %1.1e yp: %1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n: %1.1e (1/m^3) rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m))",
"M_arr = np.array(M_arr) v02_vr2_arr = np.array(v02_vr2_arr) temphi_arr = np.array(temphi_arr) ## return the containers",
"import profile import Constants as co import Inputs as ins import warnings ##",
"## stop the loop when density is 1/1000 of the initial value while",
"y_arr = [] yp_arr = [] ypp_arr = [] rho_arr = [] rhop_arr",
"lns_p_12 + lns_pp_12*(dxi/2.) ## compare densities n1 = gal.n(lns,y) n2 = gal.n(lns_,y) n0",
"loop lns += lns_p*dxi lns_p += lns_pp*dxi ############ ## adapt dxi ############ ##",
"(\"***\\n***\\nlog of z/z0 is infinite.\\nThis is full degeneracy limit. We can't handle this",
"dxi_suggest > gal.xi(co.parsec): dxi = gal.xi(co.parsec) ## if in the range, accept the",
"rhop_arr = [] P_arr = [] M_arr = [] v02_vr2_arr = [] temphi_arr",
"## To calculate the Gravitational Potential energy temphi = 0. ## containers to",
"[] v02_vr2_arr = [] temphi_arr = [] ## append the initial values xi_arr.append(xi)",
"y < 0.: print (\"***\\n***\\nNegative temperature. Breaking ...\\n***\\n***\") raise(Exception(\"Negative temperature. Unacceptable solution\")) break",
"can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_pp ==",
"singularity xi = np.copy(dxi) ## temperature setup y = ins.y(xi) y_p = ins.y_p(xi)",
"r in SI units using M = M + dM M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi)",
"no action needed pass ## change the counter N+=1 ################################### ## convert the",
"if fugacity or its derivatives are infinite if lns == np.inf: print (\"***\\n***\\nlog",
"will sharply fall to zero.\\nthis is usually the edge of the system.\\nBreaking the",
"of z/z0 is infinite.\\nWe can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\")",
"lnsp_arr = np.array(lnsp_arr) r_arr = np.array(r_arr) rho_arr = np.array(rho_arr) P_arr = np.array(P_arr) M_arr",
"for free falling speed v02_vr2 = 0. ## To calculate the Gravitational Potential",
"derivatives are infinite if lns == np.inf: print (\"***\\n***\\nlog of z/z0 is infinite.\\nThis",
"second derivative of y and s y_pp = ins.y_pp(xi) lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ##",
"dxi rather than 0 to avoid singularity xi = np.copy(dxi) ## temperature setup",
"(pc)\"%(dxi/gal.xi(co.parsec))) ############ ## end adapt ############ else: ## Verlet method lns = -lns_arr[-2]",
"counter N+=1 ################################### ## convert the lists to numpy array y_arr = np.array(y_arr)",
"dxi_suggest < gal.xi(co.parsec*0.01): dxi = gal.xi(co.parsec*0.01) ## the largest dxi elif dxi_suggest >",
"= 0 ## mass of galaxy M = 0. ## for free falling",
"import warnings ## a galaxy(DM mass,n0,T0) gal = profile(ins.m,ins.n0,ins.T0) def SolveStability(): ## increments",
"0: ## Newton method in the first loop lns += lns_p*dxi lns_p +=",
"%1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T: %1.1e (Kelvin) y: %1.1e yp: %1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp))",
"number density is infinite.\\nnumber density will sharply fall to zero.\\nthis is usually the",
"= np.copy(dxi) ## temperature setup y = ins.y(xi) y_p = ins.y_p(xi) ## fugacity",
"s0=1 =>lns0 = 0 lns_p = 0. ## number of loops in the",
"density will sharply fall to zero.\\nthis is usually the edge of the system.\\nBreaking",
"break ## add the calculated quantities into the containers xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p)",
"infinite.\\nWe can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_pp",
"= gal.n(lns_,y) n0 = gal.n(lns_arr[-1],y_arr[-1]) error = abs(n1-n2)/(n0*dxi) ## suggested dxi dxi_suggest =",
"...\\n***\\n***\") break if lns_p == np.inf: print (\"***\\n***\\n1st derivative of log of z/z0",
"################################### ## convert the lists to numpy array y_arr = np.array(y_arr) yp_arr =",
"%1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T: %1.1e (Kelvin) y: %1.1e yp: %1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n:",
"0.: print (\"***\\n***\\nNegative temperature. Breaking ...\\n***\\n***\") raise(Exception(\"Negative temperature. Unacceptable solution\")) break ## determine",
"Unacceptable solution\")) break ## determine xi xi += dxi ## mass at radius",
"a print. no action needed pass ## change the counter N+=1 ################################### ##",
"= -lns_arr[-2] + 2.*lns + lns_pp*dxi**2 lns_p = lnsp_arr[-2] + 2.*lns_pp*dxi ## for",
"v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break the loop and inform the user",
"rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try: if N%1000 == 0 and N>0: print",
"break the loop and inform the user if y < 0.: print (\"***\\n***\\nNegative",
"np.array(lnsp_arr) r_arr = np.array(r_arr) rho_arr = np.array(rho_arr) P_arr = np.array(P_arr) M_arr = np.array(M_arr)",
"= [] ## append the initial values xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y)",
"np.inf: print (\"***\\n***\\nderivative of number density is infinite.\\nnumber density will sharply fall to",
"yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ## stop the loop when",
"= np.array(yp_arr) ypp_arr = np.array(ypp_arr) lns_arr = np.array(lns_arr) lnsp_arr = np.array(lnsp_arr) r_arr =",
"at this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_p == np.inf: print (\"***\\n***\\n1st",
"user if y < 0.: print (\"***\\n***\\nNegative temperature. Breaking ...\\n***\\n***\") raise(Exception(\"Negative temperature. Unacceptable",
"if N == 0: ## Newton method in the first loop lns +=",
"if in the range, accept the suggested dxi else: dxi = dxi_suggest print(\"new",
"+=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break the loop and inform the user if",
"Verlet method lns = -lns_arr[-2] + 2.*lns + lns_pp*dxi**2 lns_p = lnsp_arr[-2] +",
"loop N = 0 ## mass of galaxy M = 0. ## for",
"is full degeneracy limit. We can't handle this at this point.\\nBreaking the loop",
"determine s and y if N == 0: ## Newton method in the",
"point.\\nBreaking the loop ...\\n***\\n***\") break ## add the calculated quantities into the containers",
"= ins.y_p(xi) ## fugacity setup lns = 0. ## s0=1 =>lns0 = 0",
"= 0. ## containers to store the outputs xi_arr = [] r_arr =",
"of the system.\\nBreaking the while loop ...\\n***\\n***\") break ## break the loop and",
"= 0. ## number of loops in the while loop N = 0",
"dxi = dxi_suggest print(\"new dxi: %g (pc)\"%(dxi/gal.xi(co.parsec))) ############ ## end adapt ############ else:",
"import numpy as np from Galaxies import profile import Constants as co import",
"the initial values xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y))",
"using M = M + dM M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi +=",
"the containers xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y))",
"gal.xi(co.parsec*0.1) ## start xi from dxi rather than 0 to avoid singularity xi",
"= lns_p_12 + lns_pp_12*(dxi/2.) ## compare densities n1 = gal.n(lns,y) n2 = gal.n(lns_,y)",
"change the counter N+=1 ################################### ## convert the lists to numpy array y_arr",
"r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi)",
"edge of the system.\\nBreaking the while loop ...\\n***\\n***\") break ## break the loop",
"print. no action needed pass ## change the counter N+=1 ################################### ## convert",
"lns_p*(dxi/2.) lns_p_12 = lnsp_arr[-1] + lns_pp*(dxi/2.) ## at dxi lns_ = lns_12 +",
"print (\"***\\n***\\n1st derivative of log of z/z0 is infinite.\\nWe can't handle this at",
"== 0 and N>0: print (\"r: %1.1e (kpc) xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz:",
"(\"***\\n***\\n1st derivative of log of z/z0 is infinite.\\nWe can't handle this at this",
"ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ## stop the loop when density",
"mass at radius r in SI units using M = M + dM",
"toler = 0.003 ## at dxi/2. forward lns_12 = lns_arr[-1] + lns_p*(dxi/2.) lns_p_12",
"= [] temphi_arr = [] ## append the initial values xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns)",
"outputs xi_arr = [] r_arr = [] lns_arr = [] lnsp_arr = []",
"to zero.\\nthis is usually the edge of the system.\\nBreaking the while loop ...\\n***\\n***\")",
"is infinite.\\nWe can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break if",
"range, accept the suggested dxi else: dxi = dxi_suggest print(\"new dxi: %g (pc)\"%(dxi/gal.xi(co.parsec)))",
"limit. We can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break if",
"+= gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ## break the loop and inform the user if derivative of",
"v02_vr2_arr = [] temphi_arr = [] ## append the initial values xi_arr.append(xi) r_arr.append(gal.r(xi))",
"...\\n***\\n***\") break ## break the loop and inform the user if fugacity or",
"(\"M: %1.1e (sun)\"%(M/co.MSun)) print (\"--\") except: ## this is just a print. no",
"v02_vr2 = 0. ## To calculate the Gravitational Potential energy temphi = 0.",
"0. ## s0=1 =>lns0 = 0 lns_p = 0. ## number of loops",
"np.array(yp_arr) ypp_arr = np.array(ypp_arr) lns_arr = np.array(lns_arr) lnsp_arr = np.array(lnsp_arr) r_arr = np.array(r_arr)",
"SolveStability(): ## increments of xi dxi = gal.xi(co.parsec*0.1) ## start xi from dxi",
"inform the user if y < 0.: print (\"***\\n***\\nNegative temperature. Breaking ...\\n***\\n***\") raise(Exception(\"Negative",
"(\"lnz: %1.1e lns: %1.1e lnsp: %1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T: %1.1e (Kelvin) y:",
"from Galaxies import profile import Constants as co import Inputs as ins import",
"r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi)",
"containers return lns_arr, lnsp_arr, lnspp_arr,\\ y_arr, yp_arr, ypp_arr,\\ r_arr, rho_arr, P_arr,\\ M_arr, v02_vr2_arr,",
"is usually the edge of the system.\\nBreaking the while loop ...\\n***\\n***\") break ##",
"loop ...\\n***\\n***\") break if lns_p == np.inf: print (\"***\\n***\\n1st derivative of log of",
"yp_arr = [] ypp_arr = [] rho_arr = [] rhop_arr = [] P_arr",
"yp: %1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n: %1.1e (1/m^3) rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M:",
"Breaking ...\\n***\\n***\") raise(Exception(\"Negative temperature. Unacceptable solution\")) break ## determine xi xi += dxi",
"convert the lists to numpy array y_arr = np.array(y_arr) yp_arr = np.array(yp_arr) ypp_arr",
"\"\"\" import numpy as np from Galaxies import profile import Constants as co",
"= [] lnspp_arr = [] y_arr = [] yp_arr = [] ypp_arr =",
"= toler/error*dxi ## the smallest dxi if dxi_suggest < gal.xi(co.parsec*0.01): dxi = gal.xi(co.parsec*0.01)",
"abs(n1-n2)/(n0*dxi) ## suggested dxi dxi_suggest = toler/error*dxi ## the smallest dxi if dxi_suggest",
"as np from Galaxies import profile import Constants as co import Inputs as",
"values xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M)",
"the outputs xi_arr = [] r_arr = [] lns_arr = [] lnsp_arr =",
"19 2019 author : <NAME>, PhD email : <EMAIL> affiliation: Baylor University \"\"\"",
"print (\"lnz: %1.1e lns: %1.1e lnsp: %1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T: %1.1e (Kelvin)",
"%1.1e (Kelvin) y: %1.1e yp: %1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n: %1.1e (1/m^3) rho:",
"dxi_suggest print(\"new dxi: %g (pc)\"%(dxi/gal.xi(co.parsec))) ############ ## end adapt ############ else: ## Verlet",
"lns = -lns_arr[-2] + 2.*lns + lns_pp*dxi**2 lns_p = lnsp_arr[-2] + 2.*lns_pp*dxi ##",
"initial values xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y))",
"<EMAIL> affiliation: Baylor University \"\"\" import numpy as np from Galaxies import profile",
"## mass at radius r in SI units using M = M +",
"## determine s and y if N == 0: ## Newton method in",
"the edge of the system.\\nBreaking the while loop ...\\n***\\n***\") break ## break the",
"full degeneracy limit. We can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\")",
"this at this point.\\nBreaking the loop ...\\n***\\n***\") break if lns_p == np.inf: print",
"yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try: if N%1000 == 0",
"rho_arr = np.array(rho_arr) P_arr = np.array(P_arr) M_arr = np.array(M_arr) v02_vr2_arr = np.array(v02_vr2_arr) temphi_arr",
"## s0=1 =>lns0 = 0 lns_p = 0. ## number of loops in",
"s y_pp = ins.y_pp(xi) lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set the temperature and its",
"print (\"***\\n***\\nlog of z/z0 is infinite.\\nThis is full degeneracy limit. We can't handle",
"profiles temperature can turn negative ## break the loop and inform the user",
"y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) try: if N%1000 ==",
"[] rho_arr = [] rhop_arr = [] P_arr = [] M_arr = []",
"to avoid singularity xi = np.copy(dxi) ## temperature setup y = ins.y(xi) y_p",
"xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz: %1.1e lns: %1.1e lnsp: %1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print",
"break the loop and inform the user if derivative of density is infinite",
"np.array(y_arr) yp_arr = np.array(yp_arr) ypp_arr = np.array(ypp_arr) lns_arr = np.array(lns_arr) lnsp_arr = np.array(lnsp_arr)",
"loop when density is 1/1000 of the initial value while gal.n(lns,y) > 1.e-3*gal.n0:",
"== np.inf: print (\"***\\n***\\nlog of z/z0 is infinite.\\nThis is full degeneracy limit. We",
"1.e-3*gal.n0: ## second derivative of y and s y_pp = ins.y_pp(xi) lns_pp =",
"else: ## Verlet method lns = -lns_arr[-2] + 2.*lns + lns_pp*dxi**2 lns_p =",
"point.\\nBreaking the loop ...\\n***\\n***\") break if lns_pp == np.inf: print (\"***\\n***\\n2nd derivative of",
"to store the outputs xi_arr = [] r_arr = [] lns_arr = []",
"the system.\\nBreaking the while loop ...\\n***\\n***\") break ## break the loop and inform",
"setup lns = 0. ## s0=1 =>lns0 = 0 lns_p = 0. ##",
"loops in the while loop N = 0 ## mass of galaxy M",
"## a galaxy(DM mass,n0,T0) gal = profile(ins.m,ins.n0,ins.T0) def SolveStability(): ## increments of xi",
"lns_12 + lns_p_12*(dxi/2.) lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ = lns_p_12 + lns_pp_12*(dxi/2.) ## compare",
"can't handle this at this point.\\nBreaking the loop ...\\n***\\n***\") break ## add the",
"P_arr = [] M_arr = [] v02_vr2_arr = [] temphi_arr = [] ##",
"ins.y_pp(xi) lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set the temperature and its derivative y =",
"the range, accept the suggested dxi else: dxi = dxi_suggest print(\"new dxi: %g",
"the containers return lns_arr, lnsp_arr, lnspp_arr,\\ y_arr, yp_arr, ypp_arr,\\ r_arr, rho_arr, P_arr,\\ M_arr,",
"## the smallest dxi if dxi_suggest < gal.xi(co.parsec*0.01): dxi = gal.xi(co.parsec*0.01) ## the",
"ins.y(xi) y_p = ins.y_p(xi) ## fugacity setup lns = 0. ## s0=1 =>lns0",
"[] y_arr = [] yp_arr = [] ypp_arr = [] rho_arr = []",
"## second derivative of y and s y_pp = ins.y_pp(xi) lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi)",
"stop the loop when density is 1/1000 of the initial value while gal.n(lns,y)",
"or its derivatives are infinite if lns == np.inf: print (\"***\\n***\\nlog of z/z0",
"## start xi from dxi rather than 0 to avoid singularity xi =",
"xi += dxi ## mass at radius r in SI units using M",
"lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ## stop",
"= [] ypp_arr = [] rho_arr = [] rhop_arr = [] P_arr =",
"accept the suggested dxi else: dxi = dxi_suggest print(\"new dxi: %g (pc)\"%(dxi/gal.xi(co.parsec))) ############",
"derivative of density is infinite if gal.n_p(lns_p,lns,y_p,y) == np.inf: print (\"***\\n***\\nderivative of number",
"%1.1e (kpc) xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz: %1.1e lns: %1.1e lnsp: %1.1e lnspp:",
"xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(y_pp) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2)",
"add the calculated quantities into the containers xi_arr.append(xi) r_arr.append(gal.r(xi)) lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(lns_pp) y_arr.append(y)",
"0 ## mass of galaxy M = 0. ## for free falling speed",
"print (\"***\\n***\\nderivative of number density is infinite.\\nnumber density will sharply fall to zero.\\nthis",
"= gal.n(lns_arr[-1],y_arr[-1]) error = abs(n1-n2)/(n0*dxi) ## suggested dxi dxi_suggest = toler/error*dxi ## the",
"= np.array(ypp_arr) lns_arr = np.array(lns_arr) lnsp_arr = np.array(lnsp_arr) r_arr = np.array(r_arr) rho_arr =",
"np.array(rho_arr) P_arr = np.array(P_arr) M_arr = np.array(M_arr) v02_vr2_arr = np.array(v02_vr2_arr) temphi_arr = np.array(temphi_arr)",
"+= lns_p*dxi lns_p += lns_pp*dxi ############ ## adapt dxi ############ ## tolerance toler",
"the counter N+=1 ################################### ## convert the lists to numpy array y_arr =",
"[] lnsp_arr = [] lnspp_arr = [] y_arr = [] yp_arr = []",
"0. ## number of loops in the while loop N = 0 ##",
"gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set the temperature and its derivative y = ins.y(xi) y_p =",
"of number density is infinite.\\nnumber density will sharply fall to zero.\\nthis is usually",
"lns_arr.append(lns) lnsp_arr.append(lns_p) lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ##",
"end adapt ############ else: ## Verlet method lns = -lns_arr[-2] + 2.*lns +",
"than 0 to avoid singularity xi = np.copy(dxi) ## temperature setup y =",
"+ lns_p*(dxi/2.) lns_p_12 = lnsp_arr[-1] + lns_pp*(dxi/2.) ## at dxi lns_ = lns_12",
"is infinite if gal.n_p(lns_p,lns,y_p,y) == np.inf: print (\"***\\n***\\nderivative of number density is infinite.\\nnumber",
"y and s y_pp = ins.y_pp(xi) lns_pp = gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set the temperature",
"except: ## this is just a print. no action needed pass ## change",
"## Newton method in the first loop lns += lns_p*dxi lns_p += lns_pp*dxi",
"free falling speed v02_vr2 = 0. ## To calculate the Gravitational Potential energy",
"> 1.e-3*gal.n0: ## second derivative of y and s y_pp = ins.y_pp(xi) lns_pp",
"= 0. ## for free falling speed v02_vr2 = 0. ## To calculate",
"the loop when density is 1/1000 of the initial value while gal.n(lns,y) >",
"if N%1000 == 0 and N>0: print (\"r: %1.1e (kpc) xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi))",
"N%1000 == 0 and N>0: print (\"r: %1.1e (kpc) xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print",
"and N>0: print (\"r: %1.1e (kpc) xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz: %1.1e lns:",
"= gal.lnspp(lns_p,lns,y_pp,y_p,y,xi) ## set the temperature and its derivative y = ins.y(xi) y_p",
"= lnsp_arr[-2] + 2.*lns_pp*dxi ## for unrealistic temperature profiles temperature can turn negative",
"%1.1e lnsp: %1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T: %1.1e (Kelvin) y: %1.1e yp: %1.1e",
"from dxi rather than 0 to avoid singularity xi = np.copy(dxi) ## temperature",
"forward lns_12 = lns_arr[-1] + lns_p*(dxi/2.) lns_p_12 = lnsp_arr[-1] + lns_pp*(dxi/2.) ## at",
"the suggested dxi else: dxi = dxi_suggest print(\"new dxi: %g (pc)\"%(dxi/gal.xi(co.parsec))) ############ ##",
"lns_arr = np.array(lns_arr) lnsp_arr = np.array(lnsp_arr) r_arr = np.array(r_arr) rho_arr = np.array(rho_arr) P_arr",
"method lns = -lns_arr[-2] + 2.*lns + lns_pp*dxi**2 lns_p = lnsp_arr[-2] + 2.*lns_pp*dxi",
"University \"\"\" import numpy as np from Galaxies import profile import Constants as",
"dxi elif dxi_suggest > gal.xi(co.parsec): dxi = gal.xi(co.parsec) ## if in the range,",
"and its derivative y = ins.y(xi) y_p = ins.y_p(xi) ## determine s and",
"M_arr = [] v02_vr2_arr = [] temphi_arr = [] ## append the initial",
"= [] v02_vr2_arr = [] temphi_arr = [] ## append the initial values",
"in the range, accept the suggested dxi else: dxi = dxi_suggest print(\"new dxi:",
"%1.1e lns: %1.1e lnsp: %1.1e lnspp: %1.1e\"%(gal.lnz0+lns,lns,lns_p,lns_pp)) print (\"T: %1.1e (Kelvin) y: %1.1e",
"print (\"n: %1.1e (1/m^3) rho: %1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M: %1.1e (sun)\"%(M/co.MSun)) print (\"--\")",
"is just a print. no action needed pass ## change the counter N+=1",
"= [] r_arr = [] lns_arr = [] lnsp_arr = [] lnspp_arr =",
"temphi = 0. ## containers to store the outputs xi_arr = [] r_arr",
"lns_pp == np.inf: print (\"***\\n***\\n2nd derivative of log of z/z0 is infinite.\\nWe can't",
"sharply fall to zero.\\nthis is usually the edge of the system.\\nBreaking the while",
": <NAME>, PhD email : <EMAIL> affiliation: Baylor University \"\"\" import numpy as",
"lns_p*dxi lns_p += lns_pp*dxi ############ ## adapt dxi ############ ## tolerance toler =",
"increments of xi dxi = gal.xi(co.parsec*0.1) ## start xi from dxi rather than",
"## determine xi xi += dxi ## mass at radius r in SI",
"N>0: print (\"r: %1.1e (kpc) xi: %1.1e \"%(gal.r(xi)/(co.parsec*1000.),xi)) print (\"lnz: %1.1e lns: %1.1e",
"profile(ins.m,ins.n0,ins.T0) def SolveStability(): ## increments of xi dxi = gal.xi(co.parsec*0.1) ## start xi",
"## compare densities n1 = gal.n(lns,y) n2 = gal.n(lns_,y) n0 = gal.n(lns_arr[-1],y_arr[-1]) error",
"= np.array(rho_arr) P_arr = np.array(P_arr) M_arr = np.array(M_arr) v02_vr2_arr = np.array(v02_vr2_arr) temphi_arr =",
"lns_arr[-1] + lns_p*(dxi/2.) lns_p_12 = lnsp_arr[-1] + lns_pp*(dxi/2.) ## at dxi lns_ =",
"y_arr = np.array(y_arr) yp_arr = np.array(yp_arr) ypp_arr = np.array(ypp_arr) lns_arr = np.array(lns_arr) lnsp_arr",
"== np.inf: print (\"***\\n***\\nderivative of number density is infinite.\\nnumber density will sharply fall",
"rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ## stop the loop when density is",
"P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ## stop the loop when density is 1/1000 of",
"[] lns_arr = [] lnsp_arr = [] lnspp_arr = [] y_arr = []",
"############ ## adapt dxi ############ ## tolerance toler = 0.003 ## at dxi/2.",
"## convert the lists to numpy array y_arr = np.array(y_arr) yp_arr = np.array(yp_arr)",
"May 19 2019 author : <NAME>, PhD email : <EMAIL> affiliation: Baylor University",
"the loop and inform the user if fugacity or its derivatives are infinite",
"= 0.003 ## at dxi/2. forward lns_12 = lns_arr[-1] + lns_p*(dxi/2.) lns_p_12 =",
"Baylor University \"\"\" import numpy as np from Galaxies import profile import Constants",
"<reponame>ahmadborzou/Study_DM_in_Galaxies-master<gh_stars>0 \"\"\" Created on May 19 2019 author : <NAME>, PhD email :",
"Constants as co import Inputs as ins import warnings ## a galaxy(DM mass,n0,T0)",
"needed pass ## change the counter N+=1 ################################### ## convert the lists to",
"loop and inform the user if fugacity or its derivatives are infinite if",
"> gal.xi(co.parsec): dxi = gal.xi(co.parsec) ## if in the range, accept the suggested",
"loop ...\\n***\\n***\") break if lns_pp == np.inf: print (\"***\\n***\\n2nd derivative of log of",
"(sun)\"%(M/co.MSun)) print (\"--\") except: ## this is just a print. no action needed",
"Gravitational Potential energy temphi = 0. ## containers to store the outputs xi_arr",
"lns_ = lns_12 + lns_p_12*(dxi/2.) lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ = lns_p_12 + lns_pp_12*(dxi/2.)",
"= M + dM M += 4.*np.pi*(gal.r(xi))**2*gal.m*gal.n(lns,y)*gal.r(dxi) v02_vr2 +=2.*co.G*M*gal.r(dxi)/(gal.r(xi))**2 temphi += gal.r(xi)*gal.m*gal.n(lns,y)*gal.r(dxi) ##",
"derivative y = ins.y(xi) y_p = ins.y_p(xi) ## determine s and y if",
"are infinite if lns == np.inf: print (\"***\\n***\\nlog of z/z0 is infinite.\\nThis is",
"0. ## for free falling speed v02_vr2 = 0. ## To calculate the",
"suggested dxi else: dxi = dxi_suggest print(\"new dxi: %g (pc)\"%(dxi/gal.xi(co.parsec))) ############ ## end",
"lnspp_arr.append(0.) y_arr.append(y) yp_arr.append(y_p) ypp_arr.append(0.) rho_arr.append(gal.m*gal.n(lns,y)) rhop_arr.append(gal.m*gal.n_p(lns_p,lns,y_p,y)) P_arr.append(gal.P(lns,y)) M_arr.append(M) v02_vr2_arr.append(v02_vr2) temphi_arr.append(temphi) ## stop the",
"density is infinite.\\nnumber density will sharply fall to zero.\\nthis is usually the edge",
"%1.1e (kg/m^3)\"%(gal.n(lns,y),gal.n(lns,y)*gal.m)) print (\"M: %1.1e (sun)\"%(M/co.MSun)) print (\"--\") except: ## this is just",
"lns_pp_12 = gal.lnspp(lns_p_12,lns_12,ins.y_pp(xi+dxi/2.),ins.y_p(xi+dxi/2.),ins.y(xi+dxi/2.),xi+dxi/2.) lns_p_ = lns_p_12 + lns_pp_12*(dxi/2.) ## compare densities n1 =",
"break if lns_pp == np.inf: print (\"***\\n***\\n2nd derivative of log of z/z0 is",
"s and y if N == 0: ## Newton method in the first",
"== np.inf: print (\"***\\n***\\n1st derivative of log of z/z0 is infinite.\\nWe can't handle",
"at radius r in SI units using M = M + dM M",
"2.*lns_pp*dxi ## for unrealistic temperature profiles temperature can turn negative ## break the",
"print (\"T: %1.1e (Kelvin) y: %1.1e yp: %1.1e ypp: %1.1e\"%(gal.T0*y,y,y_p,y_pp)) print (\"n: %1.1e",
"the while loop ...\\n***\\n***\") break ## break the loop and inform the user",
"just a print. no action needed pass ## change the counter N+=1 ###################################"
] |
[
"and len(texto[i].strip())<2: missImagem[i] = 1 else: missImagem[i] = 0 texto = texto +",
"0 texto = texto + ' ' + banco.DS_OBSERVACOES_GERAIS for i in range(len(texto)):",
"= texto + ' ' + banco.NV_USG_CALC_DESC texto = texto + ' '",
"texto,bancoNovo = gerarbanco() bancoNovo['texto'] = list(texto) # type class and save typeClass= pd.Series([np.nan]*len(bancoNovo))",
"texto = texto + ' ' + banco.NV_USG_VENTR texto = texto + '",
"pd import numpy as np def gerarbanco(): banco = pd.read_stata(\"Microcefalia MS analysis 20160609.dta\")",
"banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule classification sexo = banco.TP_SEXO classFinal = pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente']",
"import pandas as pd import numpy as np def gerarbanco(): banco = pd.read_stata(\"Microcefalia",
"= circ.boy_min[semanaGes[i]] else: ref1 = circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1: micro[i]=1 else: micro[i]=0 bancoNovo['micro'] =",
"= list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente']))",
"bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo texto,bancoNovo = gerarbanco() bancoNovo['texto'] = list(texto) # type class and",
"if sexo[i]=='Masculino': ref1 = circ.boy_min[semanaGes[i]] else: ref1 = circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1: micro[i]=1 else:",
"if semanaGes[i]<=42 and semanaGes[i]>=14: ref1 =0 if sexo[i]=='Masculino': ref1 = circ.boy_min[semanaGes[i]] else: ref1",
"' ' + banco.NV_TC_VENTR texto = texto + ' ' + banco.NV_RM_VENTR missImagem",
"texto[i] = texto[i].strip().replace('.',' ').replace(';',' ').replace(',',' ').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+',' ').replace('/',' ').replace('(',' ').replace(')',' ').replace('<','",
"bancoNovo = pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule classification sexo = banco.TP_SEXO classFinal =",
"+ ' ' + banco.NV_TC_VENTR texto = texto + ' ' + banco.NV_RM_VENTR",
"banco.NV_USG_CALC_DESC texto = texto + ' ' + banco.NV_RM_CALC texto = texto +",
"').lower() bancoNovo['missImagem'] = list(missImagem) bancoNovo['casegr'] = list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo texto,bancoNovo = gerarbanco()",
"+ ' ' + banco.NV_USG_CALC_DESC texto = texto + ' ' + banco.NV_RM_CALC",
"= banco.headcirc bancoNovo['sexo'] = list(sexo) bancoNovo['tamanhoCabe'] = list(tamanhoCabe) bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes =",
"= pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index = range(len(banco.index)) bancoNovo = pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule classification",
"= list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS) bancoNovo['NV_TOXO']",
"count_storch = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1: if",
"reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1",
"len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1",
"banco = pd.read_stata(\"Microcefalia MS analysis 20160609.dta\") circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index = range(len(banco.index)) bancoNovo",
"= list(sexo) bancoNovo['tamanhoCabe'] = list(tamanhoCabe) bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes = banco.SINASC_SEMAGESTAC missing =",
"').replace('\"',' ').lower() bancoNovo['missImagem'] = list(missImagem) bancoNovo['casegr'] = list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo texto,bancoNovo =",
"' + banco.NV_RM_OUTRO texto = texto + ' ' + banco.NV_USG_VENTR texto =",
"['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule classification sexo = banco.TP_SEXO classFinal = pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente'] =",
"= texto + ' ' + banco.NV_TC_OUTRO texto = texto + ' '",
"reagente'] = 'Discarded' classFinal[banco.NV_HCV=='Reagente'] = 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente'] = 'Discarded' classFinal[banco.NV_TOXO=='IgM reagente'] =",
"list(tamanhoCabe) bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes = banco.SINASC_SEMAGESTAC missing = pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1",
"' + banco.NV_USG_VENTR texto = texto + ' ' + banco.NV_TC_VENTR texto =",
"= texto + ' ' + banco.NV_USG_OUTRO texto = texto + ' '",
"' ' + banco.NV_USG_VENTR texto = texto + ' ' + banco.NV_TC_VENTR texto",
"#exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto = banco.NV_RM_CALC texto = texto",
"27 08:49:21 2020 @author: rafae \"\"\" import pandas as pd import numpy as",
"if len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else:",
"banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if",
"bancoNovo['tamanhoCabe'] = list(tamanhoCabe) bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes = banco.SINASC_SEMAGESTAC missing = pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1",
"+ ' ' + banco.NV_USG_OUTRO texto = texto + ' ' + banco.NV_TC_OUTRO",
"as pd import numpy as np def gerarbanco(): banco = pd.read_stata(\"Microcefalia MS analysis",
"#sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list(",
"count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 banco['count_storch'] = count_storch bancoNovo['count_storch'] = list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO)",
"if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1: if",
"' ' + banco.DS_OBSERVACOES_GERAIS for i in range(len(texto)): texto[i] = texto[i].strip().replace('.',' ').replace(';',' ').replace(',','",
"= texto + ' ' + banco.DS_OBSERVACOES_GERAIS for i in range(len(texto)): texto[i] =",
"reagente'] = 'Discarded' classFinal[banco.NV_TOXO=='IgM reagente'] = 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded'",
"gerarbanco(): banco = pd.read_stata(\"Microcefalia MS analysis 20160609.dta\") circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index = range(len(banco.index))",
"bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto = banco.NV_RM_CALC texto = texto + '",
"bancoNovo['texto'] = list(texto) # type class and save typeClass= pd.Series([np.nan]*len(bancoNovo)) typeClass[bancoNovo.classFinal.isnull()==False]='rule' typeClass[(typeClass.isnull()) &",
"rule classification sexo = banco.TP_SEXO classFinal = pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente'] = 'Discarded' classFinal[banco.NV_HCV=='Reagente']",
"= pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule classification sexo = banco.TP_SEXO classFinal = pd.Series([np.nan]*len(sexo))",
"missing[i]!=1: if semanaGes[i]<=42 and semanaGes[i]>=14: ref1 =0 if sexo[i]=='Masculino': ref1 = circ.boy_min[semanaGes[i]] else:",
"texto + ' ' + banco.NV_USG_VENTR texto = texto + ' ' +",
"pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2:",
"list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK)",
"').replace('\\n',' ').replace('\"',' ').lower() bancoNovo['missImagem'] = list(missImagem) bancoNovo['casegr'] = list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo texto,bancoNovo",
"bancoNovo['micro'] = list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS)",
"missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if missing[i]!=1:",
"i in range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2: missImagem[i] =",
"banco.NV_RM_CALC texto = texto + ' ' + banco.NV_TC_CALC texto = texto +",
"else: ref1 = circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1: micro[i]=1 else: micro[i]=0 bancoNovo['micro'] = list(micro) banco['micro']=micro",
"= 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite' # organize",
"and len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2: missImagem[i] = 1 else: missImagem[i] = 0",
"= list(missImagem) bancoNovo['casegr'] = list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo texto,bancoNovo = gerarbanco() bancoNovo['texto'] =",
"= texto + ' ' + banco.NV_TC_CALC texto = texto + ' '",
"').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+',' ').replace('/',' ').replace('(',' ').replace(')',' ').replace('<',' ').replace('>',' ').replace(':',' ').replace('&',' ').replace('¿',' ').replace('%','",
"coding: utf-8 -*- \"\"\" Created on Mon Jul 27 08:49:21 2020 @author: rafae",
"'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente'] = 'Discarded' classFinal[banco.NV_TOXO=='IgM reagente'] = 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal']",
"bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1:",
"len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2: missImagem[i] = 1 else: missImagem[i] = 0 texto = texto",
"' + banco.NV_TC_OUTRO texto = texto + ' ' + banco.NV_RM_OUTRO texto =",
"for i in range(len(texto)): texto[i] = texto[i].strip().replace('.',' ').replace(';',' ').replace(',',' ').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+','",
"count_storch bancoNovo['count_storch'] = list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto =",
"missImagem = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2",
"banco.NV_RM_OUTRO texto = texto + ' ' + banco.NV_USG_VENTR texto = texto +",
"= list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo texto,bancoNovo = gerarbanco() bancoNovo['texto'] = list(texto) # type",
"list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] =",
"= pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente'] = 'Discarded' classFinal[banco.NV_HCV=='Reagente'] = 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente'] = 'Discarded'",
"banco['count_storch'] = count_storch bancoNovo['count_storch'] = list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT)",
"= list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente']))",
"sexo[i]=='Masculino': ref1 = circ.boy_min[semanaGes[i]] else: ref1 = circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1: micro[i]=1 else: micro[i]=0",
"classFinal[banco.NV_TOXO=='IgM reagente'] = 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite'",
"').replace('/',' ').replace('(',' ').replace(')',' ').replace('<',' ').replace('>',' ').replace(':',' ').replace('&',' ').replace('¿',' ').replace('%',' ').replace('\\n',' ').replace('\"',' ').lower() bancoNovo['missImagem']",
"bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto = banco.NV_RM_CALC texto = texto + ' ' +",
"bancoNovo['missImagem'] = list(missImagem) bancoNovo['casegr'] = list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo texto,bancoNovo = gerarbanco() bancoNovo['texto']",
"= 'Discarded' classFinal[banco.NV_TOXO=='IgM reagente'] = 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_ZIKA=='Positivo']",
"= count_storch bancoNovo['count_storch'] = list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto",
"= 'Discarded' classFinal[banco.NV_HCV=='Reagente'] = 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente'] = 'Discarded' classFinal[banco.NV_TOXO=='IgM reagente'] = 'Discarded'",
"= texto + ' ' + banco.NV_RM_OUTRO texto = texto + ' '",
"texto + ' ' + banco.NV_USG_OUTRO texto = texto + ' ' +",
"' ' + banco.NV_USG_CALC_DESC texto = texto + ' ' + banco.NV_RM_CALC texto",
"semanaGes[i]>=14: ref1 =0 if sexo[i]=='Masculino': ref1 = circ.boy_min[semanaGes[i]] else: ref1 = circ.girl_min[semanaGes[i]] if",
"list(texto) # type class and save typeClass= pd.Series([np.nan]*len(bancoNovo)) typeClass[bancoNovo.classFinal.isnull()==False]='rule' typeClass[(typeClass.isnull()) & (bancoNovo.texto.str.strip()!='')]='group2' typeClass[typeClass.isnull()]='group1'",
"'Discarded' classFinal[banco.NV_HCV=='Reagente'] = 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente'] = 'Discarded' classFinal[banco.NV_TOXO=='IgM reagente'] = 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal']",
"').replace(';',' ').replace(',',' ').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+',' ').replace('/',' ').replace('(',' ').replace(')',' ').replace('<',' ').replace('>',' ').replace(':',' ').replace('&','",
"= texto + ' ' + banco.NV_TC_VENTR texto = texto + ' '",
"range(len(texto)): texto[i] = texto[i].strip().replace('.',' ').replace(';',' ').replace(',',' ').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+',' ').replace('/',' ').replace('(',' ').replace(')','",
"= pd.read_stata(\"Microcefalia MS analysis 20160609.dta\") circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index = range(len(banco.index)) bancoNovo =",
"sexo = banco.TP_SEXO classFinal = pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente'] = 'Discarded' classFinal[banco.NV_HCV=='Reagente'] = 'Discarded'",
"banco.SINASC_SEMAGESTAC missing = pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro = pd.Series([np.nan]*len(sexo)) for i",
"pd.read_stata(\"Microcefalia MS analysis 20160609.dta\") circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index = range(len(banco.index)) bancoNovo = pd.DataFrame()",
"=list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)):",
"tamanhoCabe = banco.headcirc bancoNovo['sexo'] = list(sexo) bancoNovo['tamanhoCabe'] = list(tamanhoCabe) bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes",
"' + banco.NV_RM_VENTR missImagem = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2 and",
"classFinal[banco.NV_HCV=='Reagente'] = 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente'] = 'Discarded' classFinal[banco.NV_TOXO=='IgM reagente'] = 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] =",
"reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch = pd.Series([np.nan]*len(sexo)) for i",
"= 'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite' # organize database tamanhoCabe = banco.headcirc bancoNovo['sexo'] =",
"= banco.TP_SEXO classFinal = pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente'] = 'Discarded' classFinal[banco.NV_HCV=='Reagente'] = 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM",
"+ banco.NV_RM_VENTR missImagem = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2",
"+ banco.DS_OBSERVACOES_GERAIS for i in range(len(texto)): texto[i] = texto[i].strip().replace('.',' ').replace(';',' ').replace(',',' ').replace('?',' ').replace(\"'\",'",
"if missing[i]!=1: if semanaGes[i]<=42 and semanaGes[i]>=14: ref1 =0 if sexo[i]=='Masculino': ref1 = circ.boy_min[semanaGes[i]]",
"banco.NV_RM_CALC texto = texto + ' ' + banco.NV_USG_CALC_DESC texto = texto +",
"+ banco.NV_RM_OUTRO texto = texto + ' ' + banco.NV_USG_VENTR texto = texto",
"= circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1: micro[i]=1 else: micro[i]=0 bancoNovo['micro'] = list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO'] =",
"' ' + banco.NV_RM_CALC texto = texto + ' ' + banco.NV_TC_CALC texto",
"= 'Definite' # organize database tamanhoCabe = banco.headcirc bancoNovo['sexo'] = list(sexo) bancoNovo['tamanhoCabe'] =",
"+ banco.NV_TC_OUTRO texto = texto + ' ' + banco.NV_RM_OUTRO texto = texto",
"# -*- coding: utf-8 -*- \"\"\" Created on Mon Jul 27 08:49:21 2020",
"').replace('(',' ').replace(')',' ').replace('<',' ').replace('>',' ').replace(':',' ').replace('&',' ').replace('¿',' ').replace('%',' ').replace('\\n',' ').replace('\"',' ').lower() bancoNovo['missImagem'] =",
"' ' + banco.NV_TC_CALC texto = texto + ' ' + banco.NV_USG_OUTRO texto",
"list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo texto,bancoNovo = gerarbanco() bancoNovo['texto'] = list(texto) # type class",
"2020 @author: rafae \"\"\" import pandas as pd import numpy as np def",
"@author: rafae \"\"\" import pandas as pd import numpy as np def gerarbanco():",
"+ banco.NV_TC_CALC texto = texto + ' ' + banco.NV_USG_OUTRO texto = texto",
"ref1 = circ.boy_min[semanaGes[i]] else: ref1 = circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1: micro[i]=1 else: micro[i]=0 bancoNovo['micro']",
"texto + ' ' + banco.DS_OBSERVACOES_GERAIS for i in range(len(texto)): texto[i] = texto[i].strip().replace('.','",
"=list(banco.lab_STORCH) bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG",
"').replace(')',' ').replace('<',' ').replace('>',' ').replace(':',' ').replace('&',' ').replace('¿',' ').replace('%',' ').replace('\\n',' ').replace('\"',' ').lower() bancoNovo['missImagem'] = list(missImagem)",
"= texto[i].strip().replace('.',' ').replace(';',' ').replace(',',' ').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+',' ').replace('/',' ').replace('(',' ').replace(')',' ').replace('<',' ').replace('>','",
"reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch = pd.Series([np.nan]*len(sexo)) for",
"texto + ' ' + banco.NV_TC_OUTRO texto = texto + ' ' +",
"texto[i].strip().replace('.',' ').replace(';',' ').replace(',',' ').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+',' ').replace('/',' ').replace('(',' ').replace(')',' ').replace('<',' ').replace('>',' ').replace(':','",
"' + banco.NV_TC_CALC texto = texto + ' ' + banco.NV_USG_OUTRO texto =",
"bancoNovo['NV_CMV'] =list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch = pd.Series([np.nan]*len(sexo)) for i in",
"list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto = banco.NV_RM_CALC texto =",
"'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite' # organize database",
"' ' + banco.NV_RM_OUTRO texto = texto + ' ' + banco.NV_USG_VENTR texto",
"if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 banco['count_storch'] = count_storch bancoNovo['count_storch'] = list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO)",
"+ ' ' + banco.DS_OBSERVACOES_GERAIS for i in range(len(texto)): texto[i] = texto[i].strip().replace('.',' ').replace(';','",
"texto = texto + ' ' + banco.DS_OBSERVACOES_GERAIS for i in range(len(texto)): texto[i]",
"+ ' ' + banco.NV_RM_VENTR missImagem = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if",
"' ' + banco.NV_RM_VENTR missImagem = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2",
"bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto = banco.NV_RM_CALC texto = texto + ' ' + banco.NV_USG_CALC_DESC",
"pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index = range(len(banco.index)) bancoNovo = pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule classification sexo",
"bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch",
"banco.DS_OBSERVACOES_GERAIS for i in range(len(texto)): texto[i] = texto[i].strip().replace('.',' ').replace(';',' ').replace(',',' ').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-','",
"if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 banco['count_storch']",
"in range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2: missImagem[i] = 1",
"' + banco.NV_USG_OUTRO texto = texto + ' ' + banco.NV_TC_OUTRO texto =",
"+ banco.NV_USG_CALC_DESC texto = texto + ' ' + banco.NV_RM_CALC texto = texto",
"classFinal = pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente'] = 'Discarded' classFinal[banco.NV_HCV=='Reagente'] = 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente'] =",
"and semanaGes[i]>=14: ref1 =0 if sexo[i]=='Masculino': ref1 = circ.boy_min[semanaGes[i]] else: ref1 = circ.girl_min[semanaGes[i]]",
"+ banco.NV_USG_OUTRO texto = texto + ' ' + banco.NV_TC_OUTRO texto = texto",
"+ banco.NV_USG_VENTR texto = texto + ' ' + banco.NV_TC_VENTR texto = texto",
"= range(len(banco.index)) bancoNovo = pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule classification sexo = banco.TP_SEXO",
"missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if missing[i]!=1: if",
"range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1:",
"# rule classification sexo = banco.TP_SEXO classFinal = pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente'] = 'Discarded'",
"+ ' ' + banco.NV_TC_OUTRO texto = texto + ' ' + banco.NV_RM_OUTRO",
"if len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 banco['count_storch'] = count_storch bancoNovo['count_storch'] = list(count_storch)",
"circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1: micro[i]=1 else: micro[i]=0 bancoNovo['micro'] = list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO)",
"classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite' # organize database tamanhoCabe = banco.headcirc bancoNovo['sexo']",
"').replace('+',' ').replace('/',' ').replace('(',' ').replace(')',' ').replace('<',' ').replace('>',' ').replace(':',' ').replace('&',' ').replace('¿',' ').replace('%',' ').replace('\\n',' ').replace('\"',' ').lower()",
"return texto,bancoNovo texto,bancoNovo = gerarbanco() bancoNovo['texto'] = list(texto) # type class and save",
"count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 banco['count_storch'] = count_storch bancoNovo['count_storch'] = list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO)",
"gerarbanco() bancoNovo['texto'] = list(texto) # type class and save typeClass= pd.Series([np.nan]*len(bancoNovo)) typeClass[bancoNovo.classFinal.isnull()==False]='rule' typeClass[(typeClass.isnull())",
"classification sexo = banco.TP_SEXO classFinal = pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente'] = 'Discarded' classFinal[banco.NV_HCV=='Reagente'] =",
"texto + ' ' + banco.NV_USG_CALC_DESC texto = texto + ' ' +",
"# organize database tamanhoCabe = banco.headcirc bancoNovo['sexo'] = list(sexo) bancoNovo['tamanhoCabe'] = list(tamanhoCabe) bancoNovo['classFeto']",
"= pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2 and",
"type class and save typeClass= pd.Series([np.nan]*len(bancoNovo)) typeClass[bancoNovo.classFinal.isnull()==False]='rule' typeClass[(typeClass.isnull()) & (bancoNovo.texto.str.strip()!='')]='group2' typeClass[typeClass.isnull()]='group1' bancoNovo['typeClass']=list(typeClass) bancoNovo.to_csv('banco_total.csv')",
"pandas as pd import numpy as np def gerarbanco(): banco = pd.read_stata(\"Microcefalia MS",
"for i in range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2: missImagem[i]",
"+ ' ' + banco.NV_USG_VENTR texto = texto + ' ' + banco.NV_TC_VENTR",
"bancoNovo['casegr'] = list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo texto,bancoNovo = gerarbanco() bancoNovo['texto'] = list(texto) #",
"list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV']",
"bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto = banco.NV_RM_CALC texto = texto + ' ' + banco.NV_USG_CALC_DESC texto",
"\"\"\" import pandas as pd import numpy as np def gerarbanco(): banco =",
"micro[i]=0 bancoNovo['micro'] = list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis'] =",
"= banco.NV_RM_CALC texto = texto + ' ' + banco.NV_USG_CALC_DESC texto = texto",
"tamanhoCabe[i]<ref1: micro[i]=1 else: micro[i]=0 bancoNovo['micro'] = list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch']",
"ref1 = circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1: micro[i]=1 else: micro[i]=0 bancoNovo['micro'] = list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO']",
"on Mon Jul 27 08:49:21 2020 @author: rafae \"\"\" import pandas as pd",
"'Discarded' classFinal[banco.NV_TOXO=='IgM reagente'] = 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] =",
"').replace(',',' ').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+',' ').replace('/',' ').replace('(',' ').replace(')',' ').replace('<',' ').replace('>',' ').replace(':',' ').replace('&',' ').replace('¿','",
"len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2: missImagem[i] = 1 else: missImagem[i] = 0 texto",
"= list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto = banco.NV_RM_CALC texto",
"in range(len(sexo)): if missing[i]!=1: if semanaGes[i]<=42 and semanaGes[i]>=14: ref1 =0 if sexo[i]=='Masculino': ref1",
"if len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2: missImagem[i] = 1 else: missImagem[i]",
"Mon Jul 27 08:49:21 2020 @author: rafae \"\"\" import pandas as pd import",
"= pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]:",
"count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1",
"banco['micro']=micro bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG",
"Jul 27 08:49:21 2020 @author: rafae \"\"\" import pandas as pd import numpy",
"rafae \"\"\" import pandas as pd import numpy as np def gerarbanco(): banco",
"range(len(sexo)): if missing[i]!=1: if semanaGes[i]<=42 and semanaGes[i]>=14: ref1 =0 if sexo[i]=='Masculino': ref1 =",
"len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]:",
"range(len(banco.index)) bancoNovo = pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule classification sexo = banco.TP_SEXO classFinal",
"pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule classification sexo = banco.TP_SEXO classFinal = pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM",
"MS analysis 20160609.dta\") circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index = range(len(banco.index)) bancoNovo = pd.DataFrame() banco.NV_USG_RESULT.replace(",
"list(missImagem) bancoNovo['casegr'] = list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo texto,bancoNovo = gerarbanco() bancoNovo['texto'] = list(texto)",
"range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2: missImagem[i] = 1 else:",
"').replace('>',' ').replace(':',' ').replace('&',' ').replace('¿',' ').replace('%',' ').replace('\\n',' ').replace('\"',' ').lower() bancoNovo['missImagem'] = list(missImagem) bancoNovo['casegr'] =",
"pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente'] = 'Discarded' classFinal[banco.NV_HCV=='Reagente'] = 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente'] = 'Discarded' classFinal[banco.NV_TOXO=='IgM",
"list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch = pd.Series([np.nan]*len(sexo))",
"database tamanhoCabe = banco.headcirc bancoNovo['sexo'] = list(sexo) bancoNovo['tamanhoCabe'] = list(tamanhoCabe) bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN)",
"texto = banco.NV_RM_CALC texto = texto + ' ' + banco.NV_USG_CALC_DESC texto =",
"micro = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if missing[i]!=1: if semanaGes[i]<=42 and semanaGes[i]>=14:",
"+ ' ' + banco.NV_RM_OUTRO texto = texto + ' ' + banco.NV_USG_VENTR",
"missImagem[i] = 1 else: missImagem[i] = 0 texto = texto + ' '",
"len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 banco['count_storch'] = count_storch bancoNovo['count_storch'] = list(count_storch) #exames",
"= pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if missing[i]!=1: if semanaGes[i]<=42 and semanaGes[i]>=14: ref1",
"-*- \"\"\" Created on Mon Jul 27 08:49:21 2020 @author: rafae \"\"\" import",
"= list(tamanhoCabe) bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes = banco.SINASC_SEMAGESTAC missing = pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1",
"i in range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1",
"= 0 texto = texto + ' ' + banco.DS_OBSERVACOES_GERAIS for i in",
"').replace('&',' ').replace('¿',' ').replace('%',' ').replace('\\n',' ').replace('\"',' ').lower() bancoNovo['missImagem'] = list(missImagem) bancoNovo['casegr'] = list(banco.casegr) bancoNovo['classFinal']=list(classFinal)",
"utf-8 -*- \"\"\" Created on Mon Jul 27 08:49:21 2020 @author: rafae \"\"\"",
"texto = texto + ' ' + banco.NV_TC_CALC texto = texto + '",
"'Definite' # organize database tamanhoCabe = banco.headcirc bancoNovo['sexo'] = list(sexo) bancoNovo['tamanhoCabe'] = list(tamanhoCabe)",
"missing = pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro = pd.Series([np.nan]*len(sexo)) for i in",
"= pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)):",
"20160609.dta\") circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index = range(len(banco.index)) bancoNovo = pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) #",
"classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite' # organize database tamanhoCabe",
"= banco.SINASC_SEMAGESTAC missing = pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro = pd.Series([np.nan]*len(sexo)) for",
"' + banco.NV_RM_CALC texto = texto + ' ' + banco.NV_TC_CALC texto =",
"count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 banco['count_storch'] = count_storch",
"list(sexo) bancoNovo['tamanhoCabe'] = list(tamanhoCabe) bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes = banco.SINASC_SEMAGESTAC missing = pd.Series([np.nan]*len(sexo))",
"len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2 and len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2: missImagem[i] = 1 else: missImagem[i] =",
"' + banco.DS_OBSERVACOES_GERAIS for i in range(len(texto)): texto[i] = texto[i].strip().replace('.',' ').replace(';',' ').replace(',',' ').replace('?','",
"else: count_storch[i]=count_storch[i]+1 banco['count_storch'] = count_storch bancoNovo['count_storch'] = list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT)",
"reagente'] = 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite' #",
"= 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite' # organize database tamanhoCabe =",
"= 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente'] = 'Discarded' classFinal[banco.NV_TOXO=='IgM reagente'] = 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded'",
"-*- coding: utf-8 -*- \"\"\" Created on Mon Jul 27 08:49:21 2020 @author:",
"= gerarbanco() bancoNovo['texto'] = list(texto) # type class and save typeClass= pd.Series([np.nan]*len(bancoNovo)) typeClass[bancoNovo.classFinal.isnull()==False]='rule'",
"Created on Mon Jul 27 08:49:21 2020 @author: rafae \"\"\" import pandas as",
"def gerarbanco(): banco = pd.read_stata(\"Microcefalia MS analysis 20160609.dta\") circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index =",
"= list(texto) # type class and save typeClass= pd.Series([np.nan]*len(bancoNovo)) typeClass[bancoNovo.classFinal.isnull()==False]='rule' typeClass[(typeClass.isnull()) & (bancoNovo.texto.str.strip()!='')]='group2'",
"# type class and save typeClass= pd.Series([np.nan]*len(bancoNovo)) typeClass[bancoNovo.classFinal.isnull()==False]='rule' typeClass[(typeClass.isnull()) & (bancoNovo.texto.str.strip()!='')]='group2' typeClass[typeClass.isnull()]='group1' bancoNovo['typeClass']=list(typeClass)",
"banco.NV_USG_OUTRO texto = texto + ' ' + banco.NV_TC_OUTRO texto = texto +",
"missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if missing[i]!=1: if semanaGes[i]<=42",
"numpy as np def gerarbanco(): banco = pd.read_stata(\"Microcefalia MS analysis 20160609.dta\") circ =",
"').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+',' ').replace('/',' ').replace('(',' ').replace(')',' ').replace('<',' ').replace('>',' ').replace(':',' ').replace('&',' ').replace('¿',' ').replace('%',' ').replace('\\n','",
"as np def gerarbanco(): banco = pd.read_stata(\"Microcefalia MS analysis 20160609.dta\") circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem')",
"+ ' ' + banco.NV_TC_CALC texto = texto + ' ' + banco.NV_USG_OUTRO",
"' + banco.NV_TC_VENTR texto = texto + ' ' + banco.NV_RM_VENTR missImagem =",
"texto = texto + ' ' + banco.NV_RM_CALC texto = texto + '",
"texto = texto + ' ' + banco.NV_RM_OUTRO texto = texto + '",
"' + banco.NV_USG_CALC_DESC texto = texto + ' ' + banco.NV_RM_CALC texto =",
"\"\"\" Created on Mon Jul 27 08:49:21 2020 @author: rafae \"\"\" import pandas",
"texto + ' ' + banco.NV_RM_CALC texto = texto + ' ' +",
"= texto + ' ' + banco.NV_USG_VENTR texto = texto + ' '",
"texto + ' ' + banco.NV_TC_VENTR texto = texto + ' ' +",
"banco.index = range(len(banco.index)) bancoNovo = pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule classification sexo =",
"bancoNovo['count_storch'] = list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto = banco.NV_RM_CALC",
"texto,bancoNovo texto,bancoNovo = gerarbanco() bancoNovo['texto'] = list(texto) # type class and save typeClass=",
"and len(banco.NV_RM_RESULT[i].strip())<2 and len(texto[i].strip())<2: missImagem[i] = 1 else: missImagem[i] = 0 texto =",
"for i in range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else:",
"texto + ' ' + banco.NV_TC_CALC texto = texto + ' ' +",
"semanaGes[i]<=42 and semanaGes[i]>=14: ref1 =0 if sexo[i]=='Masculino': ref1 = circ.boy_min[semanaGes[i]] else: ref1 =",
"in range(len(texto)): texto[i] = texto[i].strip().replace('.',' ').replace(';',' ').replace(',',' ').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+',' ').replace('/',' ').replace('(','",
"texto = texto + ' ' + banco.NV_USG_OUTRO texto = texto + '",
"pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1",
"count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 banco['count_storch'] = count_storch bancoNovo['count_storch'] =",
"+ banco.NV_TC_VENTR texto = texto + ' ' + banco.NV_RM_VENTR missImagem = pd.Series([np.nan]*len(sexo))",
"len(texto[i].strip())<2: missImagem[i] = 1 else: missImagem[i] = 0 texto = texto + '",
"banco.NV_TC_OUTRO texto = texto + ' ' + banco.NV_RM_OUTRO texto = texto +",
"= list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes = banco.SINASC_SEMAGESTAC missing = pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro",
"bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1:",
"ref1 =0 if sexo[i]=='Masculino': ref1 = circ.boy_min[semanaGes[i]] else: ref1 = circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1:",
"= 1 else: missImagem[i] = 0 texto = texto + ' ' +",
"circ.boy_min[semanaGes[i]] else: ref1 = circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1: micro[i]=1 else: micro[i]=0 bancoNovo['micro'] = list(micro)",
"micro[i]=1 else: micro[i]=0 bancoNovo['micro'] = list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH)",
"banco.NV_USG_VENTR texto = texto + ' ' + banco.NV_TC_VENTR texto = texto +",
"').replace(':',' ').replace('&',' ').replace('¿',' ').replace('%',' ').replace('\\n',' ').replace('\"',' ').lower() bancoNovo['missImagem'] = list(missImagem) bancoNovo['casegr'] = list(banco.casegr)",
"banco.TP_SEXO classFinal = pd.Series([np.nan]*len(sexo)) classFinal[banco.NV_CMV=='IgM reagente'] = 'Discarded' classFinal[banco.NV_HCV=='Reagente'] = 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente']",
"1 else: missImagem[i] = 0 texto = texto + ' ' + banco.DS_OBSERVACOES_GERAIS",
"bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM",
"list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes = banco.SINASC_SEMAGESTAC missing = pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro =",
"+ ' ' + banco.NV_RM_CALC texto = texto + ' ' + banco.NV_TC_CALC",
"banco.headcirc bancoNovo['sexo'] = list(sexo) bancoNovo['tamanhoCabe'] = list(tamanhoCabe) bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes = banco.SINASC_SEMAGESTAC",
"analysis 20160609.dta\") circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index = range(len(banco.index)) bancoNovo = pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True)",
"count_storch[i]=count_storch[i]+1 banco['count_storch'] = count_storch bancoNovo['count_storch'] = list(count_storch) #exames bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT)",
"circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index = range(len(banco.index)) bancoNovo = pd.DataFrame() banco.NV_USG_RESULT.replace( ['ALTERADO','NORMAL'],['Alterado','Normal'],inplace=True) # rule",
"semanaGes = banco.SINASC_SEMAGESTAC missing = pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro = pd.Series([np.nan]*len(sexo))",
"np def gerarbanco(): banco = pd.read_stata(\"Microcefalia MS analysis 20160609.dta\") circ = pd.read_csv(\"circumference.csv\",sep=\";\",index_col='sem') banco.index",
"texto = texto + ' ' + banco.NV_RM_VENTR missImagem = pd.Series([np.nan]*len(sexo)) for i",
"pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if missing[i]!=1: if semanaGes[i]<=42 and semanaGes[i]>=14: ref1 =0",
"= texto + ' ' + banco.NV_RM_CALC texto = texto + ' '",
"+ banco.NV_RM_CALC texto = texto + ' ' + banco.NV_TC_CALC texto = texto",
"classFinal[banco.NV_RUBEOLA=='IgM reagente'] = 'Discarded' classFinal[banco.NV_TOXO=='IgM reagente'] = 'Discarded' classFinal[banco.NV_RM_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] =",
"if tamanhoCabe[i]<ref1: micro[i]=1 else: micro[i]=0 bancoNovo['micro'] = list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO) #sorologia",
"bancoNovo['sexo'] = list(sexo) bancoNovo['tamanhoCabe'] = list(tamanhoCabe) bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes = banco.SINASC_SEMAGESTAC missing",
"=0 if sexo[i]=='Masculino': ref1 = circ.boy_min[semanaGes[i]] else: ref1 = circ.girl_min[semanaGes[i]] if tamanhoCabe[i]<ref1: micro[i]=1",
"texto = texto + ' ' + banco.NV_TC_OUTRO texto = texto + '",
"import numpy as np def gerarbanco(): banco = pd.read_stata(\"Microcefalia MS analysis 20160609.dta\") circ",
"'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite' # organize database tamanhoCabe = banco.headcirc bancoNovo['sexo'] = list(sexo)",
"i in range(len(sexo)): if missing[i]!=1: if semanaGes[i]<=42 and semanaGes[i]>=14: ref1 =0 if sexo[i]=='Masculino':",
"in range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if len(bancoNovo.NV_CMV[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 if",
"').replace('=','').replace('-',' ').replace('+',' ').replace('/',' ').replace('(',' ').replace(')',' ').replace('<',' ').replace('>',' ').replace(':',' ').replace('&',' ').replace('¿',' ').replace('%',' ').replace('\\n',' ').replace('\"','",
"' ' + banco.NV_TC_OUTRO texto = texto + ' ' + banco.NV_RM_OUTRO texto",
"bancoNovo['NV_USG_MICRO']=list(banco.NV_USG_MICRO) bancoNovo['NV_TC_MICRO']=list(banco.NV_TC_MICRO) bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto = banco.NV_RM_CALC texto = texto +",
"= list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list( banco.NV_CMV) bancoNovo['NV_DENGUE']=list(banco.NV_DENGUE.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch =",
"banco.NV_TC_CALC texto = texto + ' ' + banco.NV_USG_OUTRO texto = texto +",
"bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG reagente','IgM",
"classFinal[banco.NV_CMV=='IgM reagente'] = 'Discarded' classFinal[banco.NV_HCV=='Reagente'] = 'Discarded' classFinal[banco.NV_RUBEOLA=='IgM reagente'] = 'Discarded' classFinal[banco.NV_TOXO=='IgM reagente']",
"reagente'],['Reagente','Reagente'])) bancoNovo['NV_CHIK']=list(banco.NV_CHIK) count_storch = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(bancoNovo.NV_sifilis[i].strip())>1: count_storch[i]=1 if",
"').replace('<',' ').replace('>',' ').replace(':',' ').replace('&',' ').replace('¿',' ').replace('%',' ').replace('\\n',' ').replace('\"',' ').lower() bancoNovo['missImagem'] = list(missImagem) bancoNovo['casegr']",
"count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 banco['count_storch'] =",
"bancoNovo['NV_RM_MICRO']=list(banco.NV_RM_MICRO) bancoNovo['NV_USG_RESULT']=list(banco.NV_USG_RESULT) bancoNovo['NV_TC_RESULT']=list(banco.NV_TC_RESULT) bancoNovo['NV_RM_RESULT']=list(banco.NV_TC_RESULT) texto = banco.NV_RM_CALC texto = texto + ' '",
"texto = texto + ' ' + banco.NV_TC_VENTR texto = texto + '",
"for i in range(len(sexo)): if missing[i]!=1: if semanaGes[i]<=42 and semanaGes[i]>=14: ref1 =0 if",
"classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite' # organize database tamanhoCabe = banco.headcirc bancoNovo['sexo'] = list(sexo) bancoNovo['tamanhoCabe']",
"pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1 micro = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if",
"' ' + banco.NV_USG_OUTRO texto = texto + ' ' + banco.NV_TC_OUTRO texto",
"i in range(len(texto)): texto[i] = texto[i].strip().replace('.',' ').replace(';',' ').replace(',',' ').replace('?',' ').replace(\"'\",' ').replace('=','').replace('-',' ').replace('+',' ').replace('/','",
"bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis'] = list(banco.NV_SIFILIS) bancoNovo['NV_TOXO'] = list(banco.NV_TOXO.replace(['IgG reagente','IgM reagente'],['Reagente','Reagente'])) bancoNovo['NV_CMV'] =list( banco.NV_CMV)",
"banco.NV_TC_VENTR texto = texto + ' ' + banco.NV_RM_VENTR missImagem = pd.Series([np.nan]*len(sexo)) for",
"organize database tamanhoCabe = banco.headcirc bancoNovo['sexo'] = list(sexo) bancoNovo['tamanhoCabe'] = list(tamanhoCabe) bancoNovo['classFeto'] =",
"banco.NV_RM_VENTR missImagem = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if len(banco.NV_USG_RESULT[i].strip())<2 and len(banco.NV_TC_RESULT[i].strip())<2 and",
"texto + ' ' + banco.NV_RM_VENTR missImagem = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)):",
"else: count_storch[i]=count_storch[i]+1 if len(bancoNovo.NV_TOXO[i].strip())>1: if count_storch.isnull()[i]: count_storch[i]=1 else: count_storch[i]=count_storch[i]+1 banco['count_storch'] = count_storch bancoNovo['count_storch']",
"').replace('%',' ').replace('\\n',' ').replace('\"',' ').lower() bancoNovo['missImagem'] = list(missImagem) bancoNovo['casegr'] = list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return texto,bancoNovo",
"else: missImagem[i] = 0 texto = texto + ' ' + banco.DS_OBSERVACOES_GERAIS for",
"= texto + ' ' + banco.NV_RM_VENTR missImagem = pd.Series([np.nan]*len(sexo)) for i in",
"').replace('¿',' ').replace('%',' ').replace('\\n',' ').replace('\"',' ').lower() bancoNovo['missImagem'] = list(missImagem) bancoNovo['casegr'] = list(banco.casegr) bancoNovo['classFinal']=list(classFinal) return",
"'Discarded' classFinal[banco.NV_TC_RESULT=='Normal'] = 'Discarded' classFinal[banco.NV_ZIKA=='Positivo'] = 'Definite' # organize database tamanhoCabe = banco.headcirc",
"texto = texto + ' ' + banco.NV_USG_CALC_DESC texto = texto + '",
"else: micro[i]=0 bancoNovo['micro'] = list(micro) banco['micro']=micro bancoNovo['NV_TC_MICRO'] = list(banco.NV_TC_MICRO) #sorologia bancoNovo['NV_Storch'] =list(banco.lab_STORCH) bancoNovo['NV_sifilis']",
"texto + ' ' + banco.NV_RM_OUTRO texto = texto + ' ' +",
"08:49:21 2020 @author: rafae \"\"\" import pandas as pd import numpy as np",
"missImagem[i] = 0 texto = texto + ' ' + banco.DS_OBSERVACOES_GERAIS for i",
"missing[semanaGes.isnull()]=1 micro = pd.Series([np.nan]*len(sexo)) for i in range(len(sexo)): if missing[i]!=1: if semanaGes[i]<=42 and",
"bancoNovo['classFeto'] = list(banco.TP_CLASSIFICACAO_FETO_RN) semanaGes = banco.SINASC_SEMAGESTAC missing = pd.Series([np.nan]*len(sexo)) missing[bancoNovo.tamanhoCabe.isnull()]=1 missing[sexo.isnull()]=1 missing[bancoNovo.classFeto.isnull()]=1 missing[semanaGes.isnull()]=1"
] |
[
"inside `for .. in ..` without skipping on `send` if isGen: g.send(extCmd) def",
"collections \"\"\" Collection of methods for working with Generators, which respects `yield ..",
"except StopIteration: return () def gChain(*gens): for g in gens: isGen=isinstance(g, types.GeneratorType) for",
"extCmd=(yield o) if extCmd is not None: yield # this allows to use",
"is not None: yield # this allows to use our generator inside `for",
"for o in g: extCmd=(yield o) if extCmd is not None: yield #",
"raise TypeError('Wrong type, second arg must be Generator') if isinstance(prepend, _gType): gPrepend=prepend elif",
"extCmd is not None: yield # this allows to use our generator inside",
"gAppend=None else: raise TypeError('Wrong type, arg `append` must be Generator or Iterable') for",
"`for .. in ..` without skipping on `send` g.send(extCmd) # if append is",
"respects `yield .. send ..` ability. \"\"\" def gExtend(prepend, g, append=None): _gType=types.GeneratorType _iType=collections.Iterable",
"use our generator inside `for .. in ..` without skipping on `send` if",
"without skipping on `send` gPrepend.send(extCmd) # for v in g: extCmd=(yield v) if",
"Iterable') for v in prepend: extCmd=(yield v) if extCmd is not None: yield",
"in gens: isGen=isinstance(g, types.GeneratorType) for o in g: extCmd=(yield o) if extCmd is",
"inside `for .. in ..` without skipping on `send` g.send(extCmd) # if append",
"# -*- coding: utf-8 -*- import types, collections \"\"\" Collection of methods for",
"`send` if isGen: g.send(extCmd) def grouper(n, obj, fill=None): # group items by n",
"not None: for v in prepend: extCmd=(yield v) if extCmd is not None:",
"types.GeneratorType) for o in g: extCmd=(yield o) if extCmd is not None: yield",
"be Generator or Iterable') for v in prepend: extCmd=(yield v) if extCmd is",
"gExtend((next(g),), g) except StopIteration: return () def gChain(*gens): for g in gens: isGen=isinstance(g,",
"not isinstance(g, _gType): raise TypeError('Wrong type, second arg must be Generator') if isinstance(prepend,",
"without skipping on `send` g.send(extCmd) # if append is not None: for v",
"_iType): gAppend=None else: raise TypeError('Wrong type, arg `append` must be Generator or Iterable')",
"import types, collections \"\"\" Collection of methods for working with Generators, which respects",
"skipping on `send` if isGen: g.send(extCmd) def grouper(n, obj, fill=None): # group items",
"return gExtend((next(g),), g) except StopIteration: return () def gChain(*gens): for g in gens:",
"to use our generator inside `for .. in ..` without skipping on `send`",
"Generator or Iterable') for v in prepend: extCmd=(yield v) if extCmd is not",
"def gCheck(g): try: return gExtend((next(g),), g) except StopIteration: return () def gChain(*gens): for",
"Generator') if isinstance(prepend, _gType): gPrepend=prepend elif isinstance(prepend, _iType): gPrepend=g else: raise TypeError('Wrong type,",
"our generator inside `for .. in ..` without skipping on `send` gPrepend.send(extCmd) #",
"is not None: gAppend.send(extCmd) def gCheck(g): try: return gExtend((next(g),), g) except StopIteration: return",
"inside `for .. in ..` without skipping on `send` if gAppend is not",
"not None: gAppend.send(extCmd) def gCheck(g): try: return gExtend((next(g),), g) except StopIteration: return ()",
"return () def gChain(*gens): for g in gens: isGen=isinstance(g, types.GeneratorType) for o in",
"arg `append` must be Generator or Iterable') for v in prepend: extCmd=(yield v)",
"in ..` without skipping on `send` if isGen: g.send(extCmd) def grouper(n, obj, fill=None):",
"items by n (ABCDEFG --> ABC DEF Gxx if n=3) args=[iter(obj)]*n return izip_longest(fill=fill,",
"Collection of methods for working with Generators, which respects `yield .. send ..`",
"yield # this allows to use our generator inside `for .. in ..`",
"in g: extCmd=(yield v) if extCmd is not None: yield # this allows",
"if isinstance(prepend, _gType): gPrepend=prepend elif isinstance(prepend, _iType): gPrepend=g else: raise TypeError('Wrong type, first",
"Generators, which respects `yield .. send ..` ability. \"\"\" def gExtend(prepend, g, append=None):",
"def grouper(n, obj, fill=None): # group items by n (ABCDEFG --> ABC DEF",
"inside `for .. in ..` without skipping on `send` gPrepend.send(extCmd) # for v",
".. in ..` without skipping on `send` gPrepend.send(extCmd) # for v in g:",
"skipping on `send` gPrepend.send(extCmd) # for v in g: extCmd=(yield v) if extCmd",
"isGen=isinstance(g, types.GeneratorType) for o in g: extCmd=(yield o) if extCmd is not None:",
".. send ..` ability. \"\"\" def gExtend(prepend, g, append=None): _gType=types.GeneratorType _iType=collections.Iterable if not",
"grouper(n, obj, fill=None): # group items by n (ABCDEFG --> ABC DEF Gxx",
"if not isinstance(g, _gType): raise TypeError('Wrong type, second arg must be Generator') if",
"types, collections \"\"\" Collection of methods for working with Generators, which respects `yield",
"_gType): gPrepend=prepend elif isinstance(prepend, _iType): gPrepend=g else: raise TypeError('Wrong type, first arg must",
"for v in g: extCmd=(yield v) if extCmd is not None: yield #",
"_gType): raise TypeError('Wrong type, second arg must be Generator') if isinstance(prepend, _gType): gPrepend=prepend",
"our generator inside `for .. in ..` without skipping on `send` g.send(extCmd) #",
"methods for working with Generators, which respects `yield .. send ..` ability. \"\"\"",
"`send` g.send(extCmd) # if append is not None: for v in prepend: extCmd=(yield",
"must be Generator or Iterable') if append is None: gAppend=None elif isinstance(append, _gType):",
".. in ..` without skipping on `send` g.send(extCmd) # if append is not",
"gens: isGen=isinstance(g, types.GeneratorType) for o in g: extCmd=(yield o) if extCmd is not",
"o in g: extCmd=(yield o) if extCmd is not None: yield # this",
"`for .. in ..` without skipping on `send` if isGen: g.send(extCmd) def grouper(n,",
"allows to use our generator inside `for .. in ..` without skipping on",
"`yield .. send ..` ability. \"\"\" def gExtend(prepend, g, append=None): _gType=types.GeneratorType _iType=collections.Iterable if",
"raise TypeError('Wrong type, first arg must be Generator or Iterable') if append is",
"if isGen: g.send(extCmd) def grouper(n, obj, fill=None): # group items by n (ABCDEFG",
"fill=None): # group items by n (ABCDEFG --> ABC DEF Gxx if n=3)",
"or Iterable') for v in prepend: extCmd=(yield v) if extCmd is not None:",
"utf-8 -*- import types, collections \"\"\" Collection of methods for working with Generators,",
"gPrepend.send(extCmd) # for v in g: extCmd=(yield v) if extCmd is not None:",
"if gAppend is not None: gAppend.send(extCmd) def gCheck(g): try: return gExtend((next(g),), g) except",
"`send` gPrepend.send(extCmd) # for v in g: extCmd=(yield v) if extCmd is not",
"<gh_stars>0 # -*- coding: utf-8 -*- import types, collections \"\"\" Collection of methods",
"None: yield # this allows to use our generator inside `for .. in",
"use our generator inside `for .. in ..` without skipping on `send` gPrepend.send(extCmd)",
"\"\"\" def gExtend(prepend, g, append=None): _gType=types.GeneratorType _iType=collections.Iterable if not isinstance(g, _gType): raise TypeError('Wrong",
"arg must be Generator') if isinstance(prepend, _gType): gPrepend=prepend elif isinstance(prepend, _iType): gPrepend=g else:",
"or Iterable') if append is None: gAppend=None elif isinstance(append, _gType): gAppend=append elif isinstance(append,",
"coding: utf-8 -*- import types, collections \"\"\" Collection of methods for working with",
"second arg must be Generator') if isinstance(prepend, _gType): gPrepend=prepend elif isinstance(prepend, _iType): gPrepend=g",
"arg must be Generator or Iterable') if append is None: gAppend=None elif isinstance(append,",
"this allows to use our generator inside `for .. in ..` without skipping",
"isinstance(g, _gType): raise TypeError('Wrong type, second arg must be Generator') if isinstance(prepend, _gType):",
"is not None: for v in prepend: extCmd=(yield v) if extCmd is not",
"our generator inside `for .. in ..` without skipping on `send` if isGen:",
"gChain(*gens): for g in gens: isGen=isinstance(g, types.GeneratorType) for o in g: extCmd=(yield o)",
"elif isinstance(prepend, _iType): gPrepend=g else: raise TypeError('Wrong type, first arg must be Generator",
"our generator inside `for .. in ..` without skipping on `send` if gAppend",
"type, second arg must be Generator') if isinstance(prepend, _gType): gPrepend=prepend elif isinstance(prepend, _iType):",
"else: raise TypeError('Wrong type, first arg must be Generator or Iterable') if append",
"in ..` without skipping on `send` if gAppend is not None: gAppend.send(extCmd) def",
"without skipping on `send` if gAppend is not None: gAppend.send(extCmd) def gCheck(g): try:",
"_iType): gPrepend=g else: raise TypeError('Wrong type, first arg must be Generator or Iterable')",
"gAppend=append elif isinstance(append, _iType): gAppend=None else: raise TypeError('Wrong type, arg `append` must be",
"gAppend.send(extCmd) def gCheck(g): try: return gExtend((next(g),), g) except StopIteration: return () def gChain(*gens):",
"# this allows to use our generator inside `for .. in ..` without",
"which respects `yield .. send ..` ability. \"\"\" def gExtend(prepend, g, append=None): _gType=types.GeneratorType",
"type, first arg must be Generator or Iterable') if append is None: gAppend=None",
"elif isinstance(append, _iType): gAppend=None else: raise TypeError('Wrong type, arg `append` must be Generator",
"gCheck(g): try: return gExtend((next(g),), g) except StopIteration: return () def gChain(*gens): for g",
"g) except StopIteration: return () def gChain(*gens): for g in gens: isGen=isinstance(g, types.GeneratorType)",
"`send` if gAppend is not None: gAppend.send(extCmd) def gCheck(g): try: return gExtend((next(g),), g)",
"..` without skipping on `send` gPrepend.send(extCmd) # for v in g: extCmd=(yield v)",
"first arg must be Generator or Iterable') if append is None: gAppend=None elif",
"must be Generator or Iterable') for v in prepend: extCmd=(yield v) if extCmd",
"isinstance(append, _gType): gAppend=append elif isinstance(append, _iType): gAppend=None else: raise TypeError('Wrong type, arg `append`",
"gPrepend=g else: raise TypeError('Wrong type, first arg must be Generator or Iterable') if",
"must be Generator') if isinstance(prepend, _gType): gPrepend=prepend elif isinstance(prepend, _iType): gPrepend=g else: raise",
"gExtend(prepend, g, append=None): _gType=types.GeneratorType _iType=collections.Iterable if not isinstance(g, _gType): raise TypeError('Wrong type, second",
"..` without skipping on `send` g.send(extCmd) # if append is not None: for",
"without skipping on `send` if isGen: g.send(extCmd) def grouper(n, obj, fill=None): # group",
"if append is not None: for v in prepend: extCmd=(yield v) if extCmd",
"() def gChain(*gens): for g in gens: isGen=isinstance(g, types.GeneratorType) for o in g:",
"o) if extCmd is not None: yield # this allows to use our",
"..` ability. \"\"\" def gExtend(prepend, g, append=None): _gType=types.GeneratorType _iType=collections.Iterable if not isinstance(g, _gType):",
"StopIteration: return () def gChain(*gens): for g in gens: isGen=isinstance(g, types.GeneratorType) for o",
"# if append is not None: for v in prepend: extCmd=(yield v) if",
"on `send` gPrepend.send(extCmd) # for v in g: extCmd=(yield v) if extCmd is",
"use our generator inside `for .. in ..` without skipping on `send` g.send(extCmd)",
"g: extCmd=(yield o) if extCmd is not None: yield # this allows to",
"working with Generators, which respects `yield .. send ..` ability. \"\"\" def gExtend(prepend,",
"append is not None: for v in prepend: extCmd=(yield v) if extCmd is",
"of methods for working with Generators, which respects `yield .. send ..` ability.",
"in ..` without skipping on `send` g.send(extCmd) # if append is not None:",
"g in gens: isGen=isinstance(g, types.GeneratorType) for o in g: extCmd=(yield o) if extCmd",
"generator inside `for .. in ..` without skipping on `send` if isGen: g.send(extCmd)",
"`for .. in ..` without skipping on `send` gPrepend.send(extCmd) # for v in",
".. in ..` without skipping on `send` if isGen: g.send(extCmd) def grouper(n, obj,",
"\"\"\" Collection of methods for working with Generators, which respects `yield .. send",
"skipping on `send` g.send(extCmd) # if append is not None: for v in",
"for working with Generators, which respects `yield .. send ..` ability. \"\"\" def",
"isinstance(prepend, _gType): gPrepend=prepend elif isinstance(prepend, _iType): gPrepend=g else: raise TypeError('Wrong type, first arg",
"append is None: gAppend=None elif isinstance(append, _gType): gAppend=append elif isinstance(append, _iType): gAppend=None else:",
"_gType): gAppend=append elif isinstance(append, _iType): gAppend=None else: raise TypeError('Wrong type, arg `append` must",
"extCmd=(yield v) if extCmd is not None: yield # this allows to use",
"generator inside `for .. in ..` without skipping on `send` gPrepend.send(extCmd) # for",
"if append is None: gAppend=None elif isinstance(append, _gType): gAppend=append elif isinstance(append, _iType): gAppend=None",
"TypeError('Wrong type, first arg must be Generator or Iterable') if append is None:",
"for v in prepend: extCmd=(yield v) if extCmd is not None: yield #",
"..` without skipping on `send` if gAppend is not None: gAppend.send(extCmd) def gCheck(g):",
"TypeError('Wrong type, second arg must be Generator') if isinstance(prepend, _gType): gPrepend=prepend elif isinstance(prepend,",
"v in prepend: extCmd=(yield v) if extCmd is not None: yield # this",
"with Generators, which respects `yield .. send ..` ability. \"\"\" def gExtend(prepend, g,",
"is None: gAppend=None elif isinstance(append, _gType): gAppend=append elif isinstance(append, _iType): gAppend=None else: raise",
"TypeError('Wrong type, arg `append` must be Generator or Iterable') for v in prepend:",
"g.send(extCmd) # if append is not None: for v in prepend: extCmd=(yield v)",
"None: gAppend=None elif isinstance(append, _gType): gAppend=append elif isinstance(append, _iType): gAppend=None else: raise TypeError('Wrong",
"append=None): _gType=types.GeneratorType _iType=collections.Iterable if not isinstance(g, _gType): raise TypeError('Wrong type, second arg must",
"on `send` if isGen: g.send(extCmd) def grouper(n, obj, fill=None): # group items by",
"_iType=collections.Iterable if not isinstance(g, _gType): raise TypeError('Wrong type, second arg must be Generator')",
"..` without skipping on `send` if isGen: g.send(extCmd) def grouper(n, obj, fill=None): #",
"group items by n (ABCDEFG --> ABC DEF Gxx if n=3) args=[iter(obj)]*n return",
"-*- import types, collections \"\"\" Collection of methods for working with Generators, which",
"be Generator') if isinstance(prepend, _gType): gPrepend=prepend elif isinstance(prepend, _iType): gPrepend=g else: raise TypeError('Wrong",
"gPrepend=prepend elif isinstance(prepend, _iType): gPrepend=g else: raise TypeError('Wrong type, first arg must be",
"g.send(extCmd) def grouper(n, obj, fill=None): # group items by n (ABCDEFG --> ABC",
"gAppend=None elif isinstance(append, _gType): gAppend=append elif isinstance(append, _iType): gAppend=None else: raise TypeError('Wrong type,",
"be Generator or Iterable') if append is None: gAppend=None elif isinstance(append, _gType): gAppend=append",
"raise TypeError('Wrong type, arg `append` must be Generator or Iterable') for v in",
"None: for v in prepend: extCmd=(yield v) if extCmd is not None: yield",
"def gExtend(prepend, g, append=None): _gType=types.GeneratorType _iType=collections.Iterable if not isinstance(g, _gType): raise TypeError('Wrong type,",
"elif isinstance(append, _gType): gAppend=append elif isinstance(append, _iType): gAppend=None else: raise TypeError('Wrong type, arg",
"`for .. in ..` without skipping on `send` if gAppend is not None:",
"skipping on `send` if gAppend is not None: gAppend.send(extCmd) def gCheck(g): try: return",
"type, arg `append` must be Generator or Iterable') for v in prepend: extCmd=(yield",
"generator inside `for .. in ..` without skipping on `send` if gAppend is",
"g, append=None): _gType=types.GeneratorType _iType=collections.Iterable if not isinstance(g, _gType): raise TypeError('Wrong type, second arg",
"# for v in g: extCmd=(yield v) if extCmd is not None: yield",
"send ..` ability. \"\"\" def gExtend(prepend, g, append=None): _gType=types.GeneratorType _iType=collections.Iterable if not isinstance(g,",
"try: return gExtend((next(g),), g) except StopIteration: return () def gChain(*gens): for g in",
"v) if extCmd is not None: yield # this allows to use our",
"`append` must be Generator or Iterable') for v in prepend: extCmd=(yield v) if",
"else: raise TypeError('Wrong type, arg `append` must be Generator or Iterable') for v",
"not None: yield # this allows to use our generator inside `for ..",
"Iterable') if append is None: gAppend=None elif isinstance(append, _gType): gAppend=append elif isinstance(append, _iType):",
".. in ..` without skipping on `send` if gAppend is not None: gAppend.send(extCmd)",
"ability. \"\"\" def gExtend(prepend, g, append=None): _gType=types.GeneratorType _iType=collections.Iterable if not isinstance(g, _gType): raise",
"isinstance(prepend, _iType): gPrepend=g else: raise TypeError('Wrong type, first arg must be Generator or",
"prepend: extCmd=(yield v) if extCmd is not None: yield # this allows to",
"Generator or Iterable') if append is None: gAppend=None elif isinstance(append, _gType): gAppend=append elif",
"# group items by n (ABCDEFG --> ABC DEF Gxx if n=3) args=[iter(obj)]*n",
"g: extCmd=(yield v) if extCmd is not None: yield # this allows to",
"in g: extCmd=(yield o) if extCmd is not None: yield # this allows",
"def gChain(*gens): for g in gens: isGen=isinstance(g, types.GeneratorType) for o in g: extCmd=(yield",
"for g in gens: isGen=isinstance(g, types.GeneratorType) for o in g: extCmd=(yield o) if",
"on `send` if gAppend is not None: gAppend.send(extCmd) def gCheck(g): try: return gExtend((next(g),),",
"by n (ABCDEFG --> ABC DEF Gxx if n=3) args=[iter(obj)]*n return izip_longest(fill=fill, *args)",
"gAppend is not None: gAppend.send(extCmd) def gCheck(g): try: return gExtend((next(g),), g) except StopIteration:",
"v in g: extCmd=(yield v) if extCmd is not None: yield # this",
"None: gAppend.send(extCmd) def gCheck(g): try: return gExtend((next(g),), g) except StopIteration: return () def",
"in prepend: extCmd=(yield v) if extCmd is not None: yield # this allows",
"on `send` g.send(extCmd) # if append is not None: for v in prepend:",
"if extCmd is not None: yield # this allows to use our generator",
"isGen: g.send(extCmd) def grouper(n, obj, fill=None): # group items by n (ABCDEFG -->",
"obj, fill=None): # group items by n (ABCDEFG --> ABC DEF Gxx if",
"_gType=types.GeneratorType _iType=collections.Iterable if not isinstance(g, _gType): raise TypeError('Wrong type, second arg must be",
"in ..` without skipping on `send` gPrepend.send(extCmd) # for v in g: extCmd=(yield",
"generator inside `for .. in ..` without skipping on `send` g.send(extCmd) # if",
"isinstance(append, _iType): gAppend=None else: raise TypeError('Wrong type, arg `append` must be Generator or",
"-*- coding: utf-8 -*- import types, collections \"\"\" Collection of methods for working"
] |
[
"alt_names: self.name, self.alt_name, self.id = genetic_codes[alt_names[alt_name]] return raise ValueError(f\"Unknown alternative name {alt_name}.\") assert",
"\"\": alt_names[alt_name] = len(genetic_codes) ids[id] = len(genetic_codes) genetic_codes.append((name, alt_name, id)) register_ncbi_genetic_code( \"Standard\", \"SGC0\",",
") register_ncbi_genetic_code( \"Peritrich Nuclear\", \"\", 30, ) register_ncbi_genetic_code( \"Blastocrithidia Nuclear\", \"\", 31, )",
"Nuclear\", \"SGC5\", 6, ) register_ncbi_genetic_code( \"Echinoderm Mitochondrial; Flatworm Mitochondrial\", \"SGC8\", 9, ) register_ncbi_genetic_code(",
"5, ) register_ncbi_genetic_code( \"Ciliate Nuclear; Dasycladacean Nuclear; Hexamita Nuclear\", \"SGC5\", 6, ) register_ncbi_genetic_code(",
"int] = {} @dataclass class GeneticCode: name: str alt_name: str id: int def",
"= None, ): n = sum([name is None, alt_name is None, id is",
"= len(genetic_codes) genetic_codes.append((name, alt_name, id)) register_ncbi_genetic_code( \"Standard\", \"SGC0\", 1, ) register_ncbi_genetic_code( \"Vertebrate Mitochondrial\",",
"\"Trematode Mitochondrial\", \"\", 21, ) register_ncbi_genetic_code( \"Scenedesmus obliquus Mitochondrial\", \"\", 22, ) register_ncbi_genetic_code(",
"\"SGC9\", 10, ) register_ncbi_genetic_code( \"Bacterial, Archaeal and Plant Plastid\", \"\", 11, ) register_ncbi_genetic_code(",
"code table version 4.6 from dataclasses import dataclass from typing import Dict, List,",
"\"\", 12, ) register_ncbi_genetic_code( \"Ascidian Mitochondrial\", \"\", 13, ) register_ncbi_genetic_code( \"Alternative Flatworm Mitochondrial\",",
"@dataclass class GeneticCode: name: str alt_name: str id: int def __init__( self, name:",
"def __init__( self, name: Optional[str] = None, alt_name: Optional[str] = None, id: Optional[int]",
"one, parameter.\") if name is not None: if name in names: self.name, self.alt_name,",
"\"\", 22, ) register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\", \"\", 23, ) register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\", \"\",",
"29, ) register_ncbi_genetic_code( \"Peritrich Nuclear\", \"\", 30, ) register_ncbi_genetic_code( \"Blastocrithidia Nuclear\", \"\", 31,",
"id: Optional[int] = None, ): n = sum([name is None, alt_name is None,",
"Mitochondrial\", \"SGC1\", 2, ) register_ncbi_genetic_code( \"Yeast Mitochondrial\", \"SGC2\", 3, ) register_ncbi_genetic_code( \"Mold Mitochondrial;",
"\"\", 29, ) register_ncbi_genetic_code( \"Peritrich Nuclear\", \"\", 30, ) register_ncbi_genetic_code( \"Blastocrithidia Nuclear\", \"\",",
"alt_name != \"\": alt_names[alt_name] = len(genetic_codes) ids[id] = len(genetic_codes) genetic_codes.append((name, alt_name, id)) register_ncbi_genetic_code(",
"): n = sum([name is None, alt_name is None, id is None]) if",
"15, ) register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\", \"\", 16, ) register_ncbi_genetic_code( \"Trematode Mitochondrial\", \"\", 21,",
"Mitochondrial\", \"\", 16, ) register_ncbi_genetic_code( \"Trematode Mitochondrial\", \"\", 21, ) register_ncbi_genetic_code( \"Scenedesmus obliquus",
"is None]) if n != 2: raise ValueError(\"You must use one, and only",
"str id: int def __init__( self, name: Optional[str] = None, alt_name: Optional[str] =",
"if n != 2: raise ValueError(\"You must use one, and only one, parameter.\")",
"register_ncbi_genetic_code( \"Echinoderm Mitochondrial; Flatworm Mitochondrial\", \"SGC8\", 9, ) register_ncbi_genetic_code( \"Euplotid Nuclear\", \"SGC9\", 10,",
"Mycoplasma; Spiroplasma\", \"SGC3\", 4, ) register_ncbi_genetic_code( \"Invertebrate Mitochondrial\", \"SGC4\", 5, ) register_ncbi_genetic_code( \"Ciliate",
"in alt_names: self.name, self.alt_name, self.id = genetic_codes[alt_names[alt_name]] return raise ValueError(f\"Unknown alternative name {alt_name}.\")",
"from dataclasses import dataclass from typing import Dict, List, Optional, Tuple __all__ =",
"from typing import Dict, List, Optional, Tuple __all__ = [\"GeneticCode\"] genetic_codes: List[Tuple[str, str,",
"14, ) register_ncbi_genetic_code( \"Blepharisma Macronuclear\", \"\", 15, ) register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\", \"\", 16,",
"21, ) register_ncbi_genetic_code( \"Scenedesmus obliquus Mitochondrial\", \"\", 22, ) register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\", \"\",",
"\"SGC4\", 5, ) register_ncbi_genetic_code( \"Ciliate Nuclear; Dasycladacean Nuclear; Hexamita Nuclear\", \"SGC5\", 6, )",
"{} @dataclass class GeneticCode: name: str alt_name: str id: int def __init__( self,",
"6, ) register_ncbi_genetic_code( \"Echinoderm Mitochondrial; Flatworm Mitochondrial\", \"SGC8\", 9, ) register_ncbi_genetic_code( \"Euplotid Nuclear\",",
"is None, id is None]) if n != 2: raise ValueError(\"You must use",
"None, ): n = sum([name is None, alt_name is None, id is None])",
"Mitochondrial; Protozoan Mitochondrial; Coelenterate \" \"Mitochondrial; Mycoplasma; Spiroplasma\", \"SGC3\", 4, ) register_ncbi_genetic_code( \"Invertebrate",
"\"\", 27, ) register_ncbi_genetic_code( \"Condylostoma Nuclear\", \"\", 28, ) register_ncbi_genetic_code( \"Mesodinium Nuclear\", \"\",",
"\"\", 11, ) register_ncbi_genetic_code( \"Alternative Yeast Nuclear\", \"\", 12, ) register_ncbi_genetic_code( \"Ascidian Mitochondrial\",",
"version 4.6 from dataclasses import dataclass from typing import Dict, List, Optional, Tuple",
"name is not None: if name in names: self.name, self.alt_name, self.id = genetic_codes[names[name]]",
"import dataclass from typing import Dict, List, Optional, Tuple __all__ = [\"GeneticCode\"] genetic_codes:",
"if alt_name in alt_names: self.name, self.alt_name, self.id = genetic_codes[alt_names[alt_name]] return raise ValueError(f\"Unknown alternative",
"Protozoan Mitochondrial; Coelenterate \" \"Mitochondrial; Mycoplasma; Spiroplasma\", \"SGC3\", 4, ) register_ncbi_genetic_code( \"Invertebrate Mitochondrial\",",
"\"Candidate Division SR1 and Gracilibacteria\", \"\", 25, ) register_ncbi_genetic_code( \"Pachysolen tannophilus Nuclear\", \"\",",
"genetic_codes.append((name, alt_name, id)) register_ncbi_genetic_code( \"Standard\", \"SGC0\", 1, ) register_ncbi_genetic_code( \"Vertebrate Mitochondrial\", \"SGC1\", 2,",
"\" \"Mitochondrial; Mycoplasma; Spiroplasma\", \"SGC3\", 4, ) register_ncbi_genetic_code( \"Invertebrate Mitochondrial\", \"SGC4\", 5, )",
") register_ncbi_genetic_code( \"Trematode Mitochondrial\", \"\", 21, ) register_ncbi_genetic_code( \"Scenedesmus obliquus Mitochondrial\", \"\", 22,",
"Nuclear\", \"\", 30, ) register_ncbi_genetic_code( \"Blastocrithidia Nuclear\", \"\", 31, ) register_ncbi_genetic_code( \"Balanophoraceae Plastid\",",
"= {} alt_names: Dict[str, int] = {} ids: Dict[int, int] = {} @dataclass",
"Mitochondrial\", \"SGC4\", 5, ) register_ncbi_genetic_code( \"Ciliate Nuclear; Dasycladacean Nuclear; Hexamita Nuclear\", \"SGC5\", 6,",
"\"\", 21, ) register_ncbi_genetic_code( \"Scenedesmus obliquus Mitochondrial\", \"\", 22, ) register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\",",
"2: raise ValueError(\"You must use one, and only one, parameter.\") if name is",
"register_ncbi_genetic_code( \"Euplotid Nuclear\", \"SGC9\", 10, ) register_ncbi_genetic_code( \"Bacterial, Archaeal and Plant Plastid\", \"\",",
"dataclasses import dataclass from typing import Dict, List, Optional, Tuple __all__ = [\"GeneticCode\"]",
"register_ncbi_genetic_code( \"Invertebrate Mitochondrial\", \"SGC4\", 5, ) register_ncbi_genetic_code( \"Ciliate Nuclear; Dasycladacean Nuclear; Hexamita Nuclear\",",
"register_ncbi_genetic_code( \"Condylostoma Nuclear\", \"\", 28, ) register_ncbi_genetic_code( \"Mesodinium Nuclear\", \"\", 29, ) register_ncbi_genetic_code(",
") register_ncbi_genetic_code( \"Mesodinium Nuclear\", \"\", 29, ) register_ncbi_genetic_code( \"Peritrich Nuclear\", \"\", 30, )",
"24, ) register_ncbi_genetic_code( \"Candidate Division SR1 and Gracilibacteria\", \"\", 25, ) register_ncbi_genetic_code( \"Pachysolen",
"self.alt_name, self.id = genetic_codes[names[name]] return raise ValueError(f\"Unknown name {name}.\") if alt_name is not",
"[\"GeneticCode\"] genetic_codes: List[Tuple[str, str, int]] = [] names: Dict[str, int] = {} alt_names:",
"13, ) register_ncbi_genetic_code( \"Alternative Flatworm Mitochondrial\", \"\", 14, ) register_ncbi_genetic_code( \"Blepharisma Macronuclear\", \"\",",
"3, ) register_ncbi_genetic_code( \"Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate \" \"Mitochondrial; Mycoplasma; Spiroplasma\", \"SGC3\",",
"genetic_codes: List[Tuple[str, str, int]] = [] names: Dict[str, int] = {} alt_names: Dict[str,",
"\"Peritrich Nuclear\", \"\", 30, ) register_ncbi_genetic_code( \"Blastocrithidia Nuclear\", \"\", 31, ) register_ncbi_genetic_code( \"Balanophoraceae",
"Nuclear\", \"\", 12, ) register_ncbi_genetic_code( \"Ascidian Mitochondrial\", \"\", 13, ) register_ncbi_genetic_code( \"Alternative Flatworm",
"\"Mitochondrial; Mycoplasma; Spiroplasma\", \"SGC3\", 4, ) register_ncbi_genetic_code( \"Invertebrate Mitochondrial\", \"SGC4\", 5, ) register_ncbi_genetic_code(",
"\"Invertebrate Mitochondrial\", \"SGC4\", 5, ) register_ncbi_genetic_code( \"Ciliate Nuclear; Dasycladacean Nuclear; Hexamita Nuclear\", \"SGC5\",",
") register_ncbi_genetic_code( \"Blastocrithidia Nuclear\", \"\", 31, ) register_ncbi_genetic_code( \"Balanophoraceae Plastid\", \"\", 32, )",
"!= 2: raise ValueError(\"You must use one, and only one, parameter.\") if name",
"table version 4.6 from dataclasses import dataclass from typing import Dict, List, Optional,",
"Nuclear\", \"\", 31, ) register_ncbi_genetic_code( \"Balanophoraceae Plastid\", \"\", 32, ) register_ncbi_genetic_code( \"Cephalodiscidae Mitochondrial\",",
"str, int]] = [] names: Dict[str, int] = {} alt_names: Dict[str, int] =",
"\"Karyorelict Nuclear\", \"\", 27, ) register_ncbi_genetic_code( \"Condylostoma Nuclear\", \"\", 28, ) register_ncbi_genetic_code( \"Mesodinium",
"Dict, List, Optional, Tuple __all__ = [\"GeneticCode\"] genetic_codes: List[Tuple[str, str, int]] = []",
"\"Blepharisma Macronuclear\", \"\", 15, ) register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\", \"\", 16, ) register_ncbi_genetic_code( \"Trematode",
"if alt_name is not None: if alt_name in alt_names: self.name, self.alt_name, self.id =",
"register_ncbi_genetic_code( \"Blastocrithidia Nuclear\", \"\", 31, ) register_ncbi_genetic_code( \"Balanophoraceae Plastid\", \"\", 32, ) register_ncbi_genetic_code(",
"id: int): names[name] = len(genetic_codes) if alt_name != \"\": alt_names[alt_name] = len(genetic_codes) ids[id]",
"None, id: Optional[int] = None, ): n = sum([name is None, alt_name is",
"register_ncbi_genetic_code( \"Ciliate Nuclear; Dasycladacean Nuclear; Hexamita Nuclear\", \"SGC5\", 6, ) register_ncbi_genetic_code( \"Echinoderm Mitochondrial;",
"= genetic_codes[names[name]] return raise ValueError(f\"Unknown name {name}.\") if alt_name is not None: if",
"self.alt_name, self.id = genetic_codes[ids[id]] def register_ncbi_genetic_code(name: str, alt_name: str, id: int): names[name] =",
"4, ) register_ncbi_genetic_code( \"Invertebrate Mitochondrial\", \"SGC4\", 5, ) register_ncbi_genetic_code( \"Ciliate Nuclear; Dasycladacean Nuclear;",
"register_ncbi_genetic_code( \"Scenedesmus obliquus Mitochondrial\", \"\", 22, ) register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\", \"\", 23, )",
"\"Rhabdopleuridae Mitochondrial\", \"\", 24, ) register_ncbi_genetic_code( \"Candidate Division SR1 and Gracilibacteria\", \"\", 25,",
"\"Bacterial, Archaeal and Plant Plastid\", \"\", 11, ) register_ncbi_genetic_code( \"Alternative Yeast Nuclear\", \"\",",
"register_ncbi_genetic_code(name: str, alt_name: str, id: int): names[name] = len(genetic_codes) if alt_name != \"\":",
"alt_names[alt_name] = len(genetic_codes) ids[id] = len(genetic_codes) genetic_codes.append((name, alt_name, id)) register_ncbi_genetic_code( \"Standard\", \"SGC0\", 1,",
"Mitochondrial\", \"\", 22, ) register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\", \"\", 23, ) register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\",",
"Dict[int, int] = {} @dataclass class GeneticCode: name: str alt_name: str id: int",
"GeneticCode: name: str alt_name: str id: int def __init__( self, name: Optional[str] =",
"Mitochondrial; Flatworm Mitochondrial\", \"SGC8\", 9, ) register_ncbi_genetic_code( \"Euplotid Nuclear\", \"SGC9\", 10, ) register_ncbi_genetic_code(",
"Coelenterate \" \"Mitochondrial; Mycoplasma; Spiroplasma\", \"SGC3\", 4, ) register_ncbi_genetic_code( \"Invertebrate Mitochondrial\", \"SGC4\", 5,",
"len(genetic_codes) genetic_codes.append((name, alt_name, id)) register_ncbi_genetic_code( \"Standard\", \"SGC0\", 1, ) register_ncbi_genetic_code( \"Vertebrate Mitochondrial\", \"SGC1\",",
"Plastid\", \"\", 11, ) register_ncbi_genetic_code( \"Alternative Yeast Nuclear\", \"\", 12, ) register_ncbi_genetic_code( \"Ascidian",
"self.name, self.alt_name, self.id = genetic_codes[ids[id]] def register_ncbi_genetic_code(name: str, alt_name: str, id: int): names[name]",
"int]] = [] names: Dict[str, int] = {} alt_names: Dict[str, int] = {}",
"Nuclear\", \"\", 26, ) register_ncbi_genetic_code( \"Karyorelict Nuclear\", \"\", 27, ) register_ncbi_genetic_code( \"Condylostoma Nuclear\",",
"Yeast Nuclear\", \"\", 12, ) register_ncbi_genetic_code( \"Ascidian Mitochondrial\", \"\", 13, ) register_ncbi_genetic_code( \"Alternative",
"raise ValueError(f\"Unknown alternative name {alt_name}.\") assert id is not None self.name, self.alt_name, self.id",
"alt_name in alt_names: self.name, self.alt_name, self.id = genetic_codes[alt_names[alt_name]] return raise ValueError(f\"Unknown alternative name",
"register_ncbi_genetic_code( \"Peritrich Nuclear\", \"\", 30, ) register_ncbi_genetic_code( \"Blastocrithidia Nuclear\", \"\", 31, ) register_ncbi_genetic_code(",
"Nuclear\", \"\", 28, ) register_ncbi_genetic_code( \"Mesodinium Nuclear\", \"\", 29, ) register_ncbi_genetic_code( \"Peritrich Nuclear\",",
"register_ncbi_genetic_code( \"Alternative Yeast Nuclear\", \"\", 12, ) register_ncbi_genetic_code( \"Ascidian Mitochondrial\", \"\", 13, )",
"register_ncbi_genetic_code( \"Ascidian Mitochondrial\", \"\", 13, ) register_ncbi_genetic_code( \"Alternative Flatworm Mitochondrial\", \"\", 14, )",
"\"\", 16, ) register_ncbi_genetic_code( \"Trematode Mitochondrial\", \"\", 21, ) register_ncbi_genetic_code( \"Scenedesmus obliquus Mitochondrial\",",
"Mitochondrial\", \"\", 21, ) register_ncbi_genetic_code( \"Scenedesmus obliquus Mitochondrial\", \"\", 22, ) register_ncbi_genetic_code( \"Thraustochytrium",
"Macronuclear\", \"\", 15, ) register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\", \"\", 16, ) register_ncbi_genetic_code( \"Trematode Mitochondrial\",",
"\"SGC2\", 3, ) register_ncbi_genetic_code( \"Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate \" \"Mitochondrial; Mycoplasma; Spiroplasma\",",
") register_ncbi_genetic_code( \"Condylostoma Nuclear\", \"\", 28, ) register_ncbi_genetic_code( \"Mesodinium Nuclear\", \"\", 29, )",
") register_ncbi_genetic_code( \"Ciliate Nuclear; Dasycladacean Nuclear; Hexamita Nuclear\", \"SGC5\", 6, ) register_ncbi_genetic_code( \"Echinoderm",
"n = sum([name is None, alt_name is None, id is None]) if n",
"name in names: self.name, self.alt_name, self.id = genetic_codes[names[name]] return raise ValueError(f\"Unknown name {name}.\")",
"register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\", \"\", 23, ) register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\", \"\", 24, ) register_ncbi_genetic_code(",
"Optional, Tuple __all__ = [\"GeneticCode\"] genetic_codes: List[Tuple[str, str, int]] = [] names: Dict[str,",
"Mitochondrial\", \"SGC2\", 3, ) register_ncbi_genetic_code( \"Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate \" \"Mitochondrial; Mycoplasma;",
"\"\", 13, ) register_ncbi_genetic_code( \"Alternative Flatworm Mitochondrial\", \"\", 14, ) register_ncbi_genetic_code( \"Blepharisma Macronuclear\",",
"return raise ValueError(f\"Unknown alternative name {alt_name}.\") assert id is not None self.name, self.alt_name,",
"= genetic_codes[ids[id]] def register_ncbi_genetic_code(name: str, alt_name: str, id: int): names[name] = len(genetic_codes) if",
"genetic_codes[names[name]] return raise ValueError(f\"Unknown name {name}.\") if alt_name is not None: if alt_name",
"Mitochondrial\", \"\", 14, ) register_ncbi_genetic_code( \"Blepharisma Macronuclear\", \"\", 15, ) register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\",",
"Nuclear\", \"\", 27, ) register_ncbi_genetic_code( \"Condylostoma Nuclear\", \"\", 28, ) register_ncbi_genetic_code( \"Mesodinium Nuclear\",",
"Nuclear; Hexamita Nuclear\", \"SGC5\", 6, ) register_ncbi_genetic_code( \"Echinoderm Mitochondrial; Flatworm Mitochondrial\", \"SGC8\", 9,",
"{} ids: Dict[int, int] = {} @dataclass class GeneticCode: name: str alt_name: str",
"\"Alternative Flatworm Mitochondrial\", \"\", 14, ) register_ncbi_genetic_code( \"Blepharisma Macronuclear\", \"\", 15, ) register_ncbi_genetic_code(",
"register_ncbi_genetic_code( \"Bacterial, Archaeal and Plant Plastid\", \"\", 11, ) register_ncbi_genetic_code( \"Alternative Yeast Nuclear\",",
"\"Yeast Mitochondrial\", \"SGC2\", 3, ) register_ncbi_genetic_code( \"Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate \" \"Mitochondrial;",
"Nuclear\", \"\", 29, ) register_ncbi_genetic_code( \"Peritrich Nuclear\", \"\", 30, ) register_ncbi_genetic_code( \"Blastocrithidia Nuclear\",",
"in names: self.name, self.alt_name, self.id = genetic_codes[names[name]] return raise ValueError(f\"Unknown name {name}.\") if",
"names[name] = len(genetic_codes) if alt_name != \"\": alt_names[alt_name] = len(genetic_codes) ids[id] = len(genetic_codes)",
"{alt_name}.\") assert id is not None self.name, self.alt_name, self.id = genetic_codes[ids[id]] def register_ncbi_genetic_code(name:",
"None, alt_name is None, id is None]) if n != 2: raise ValueError(\"You",
"= [\"GeneticCode\"] genetic_codes: List[Tuple[str, str, int]] = [] names: Dict[str, int] = {}",
"SR1 and Gracilibacteria\", \"\", 25, ) register_ncbi_genetic_code( \"Pachysolen tannophilus Nuclear\", \"\", 26, )",
"Plant Plastid\", \"\", 11, ) register_ncbi_genetic_code( \"Alternative Yeast Nuclear\", \"\", 12, ) register_ncbi_genetic_code(",
"dataclass from typing import Dict, List, Optional, Tuple __all__ = [\"GeneticCode\"] genetic_codes: List[Tuple[str,",
"name: str alt_name: str id: int def __init__( self, name: Optional[str] = None,",
") register_ncbi_genetic_code( \"Scenedesmus obliquus Mitochondrial\", \"\", 22, ) register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\", \"\", 23,",
"self.id = genetic_codes[alt_names[alt_name]] return raise ValueError(f\"Unknown alternative name {alt_name}.\") assert id is not",
"genetic_codes[alt_names[alt_name]] return raise ValueError(f\"Unknown alternative name {alt_name}.\") assert id is not None self.name,",
"is not None self.name, self.alt_name, self.id = genetic_codes[ids[id]] def register_ncbi_genetic_code(name: str, alt_name: str,",
"Nuclear\", \"SGC9\", 10, ) register_ncbi_genetic_code( \"Bacterial, Archaeal and Plant Plastid\", \"\", 11, )",
"\"Ciliate Nuclear; Dasycladacean Nuclear; Hexamita Nuclear\", \"SGC5\", 6, ) register_ncbi_genetic_code( \"Echinoderm Mitochondrial; Flatworm",
") register_ncbi_genetic_code( \"Vertebrate Mitochondrial\", \"SGC1\", 2, ) register_ncbi_genetic_code( \"Yeast Mitochondrial\", \"SGC2\", 3, )",
"\"\", 30, ) register_ncbi_genetic_code( \"Blastocrithidia Nuclear\", \"\", 31, ) register_ncbi_genetic_code( \"Balanophoraceae Plastid\", \"\",",
"Mitochondrial\", \"\", 24, ) register_ncbi_genetic_code( \"Candidate Division SR1 and Gracilibacteria\", \"\", 25, )",
"register_ncbi_genetic_code( \"Mesodinium Nuclear\", \"\", 29, ) register_ncbi_genetic_code( \"Peritrich Nuclear\", \"\", 30, ) register_ncbi_genetic_code(",
"4.6 from dataclasses import dataclass from typing import Dict, List, Optional, Tuple __all__",
"class GeneticCode: name: str alt_name: str id: int def __init__( self, name: Optional[str]",
") register_ncbi_genetic_code( \"Echinoderm Mitochondrial; Flatworm Mitochondrial\", \"SGC8\", 9, ) register_ncbi_genetic_code( \"Euplotid Nuclear\", \"SGC9\",",
") register_ncbi_genetic_code( \"Pachysolen tannophilus Nuclear\", \"\", 26, ) register_ncbi_genetic_code( \"Karyorelict Nuclear\", \"\", 27,",
"int] = {} ids: Dict[int, int] = {} @dataclass class GeneticCode: name: str",
"and only one, parameter.\") if name is not None: if name in names:",
"assert id is not None self.name, self.alt_name, self.id = genetic_codes[ids[id]] def register_ncbi_genetic_code(name: str,",
"parameter.\") if name is not None: if name in names: self.name, self.alt_name, self.id",
"Division SR1 and Gracilibacteria\", \"\", 25, ) register_ncbi_genetic_code( \"Pachysolen tannophilus Nuclear\", \"\", 26,",
"return raise ValueError(f\"Unknown name {name}.\") if alt_name is not None: if alt_name in",
"\"\", 25, ) register_ncbi_genetic_code( \"Pachysolen tannophilus Nuclear\", \"\", 26, ) register_ncbi_genetic_code( \"Karyorelict Nuclear\",",
") register_ncbi_genetic_code( \"Bacterial, Archaeal and Plant Plastid\", \"\", 11, ) register_ncbi_genetic_code( \"Alternative Yeast",
"name {alt_name}.\") assert id is not None self.name, self.alt_name, self.id = genetic_codes[ids[id]] def",
"not None self.name, self.alt_name, self.id = genetic_codes[ids[id]] def register_ncbi_genetic_code(name: str, alt_name: str, id:",
"None: if name in names: self.name, self.alt_name, self.id = genetic_codes[names[name]] return raise ValueError(f\"Unknown",
"__all__ = [\"GeneticCode\"] genetic_codes: List[Tuple[str, str, int]] = [] names: Dict[str, int] =",
"22, ) register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\", \"\", 23, ) register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\", \"\", 24,",
"len(genetic_codes) if alt_name != \"\": alt_names[alt_name] = len(genetic_codes) ids[id] = len(genetic_codes) genetic_codes.append((name, alt_name,",
"len(genetic_codes) ids[id] = len(genetic_codes) genetic_codes.append((name, alt_name, id)) register_ncbi_genetic_code( \"Standard\", \"SGC0\", 1, ) register_ncbi_genetic_code(",
"use one, and only one, parameter.\") if name is not None: if name",
"must use one, and only one, parameter.\") if name is not None: if",
") register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\", \"\", 23, ) register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\", \"\", 24, )",
"alt_name is not None: if alt_name in alt_names: self.name, self.alt_name, self.id = genetic_codes[alt_names[alt_name]]",
") register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\", \"\", 16, ) register_ncbi_genetic_code( \"Trematode Mitochondrial\", \"\", 21, )",
"ValueError(\"You must use one, and only one, parameter.\") if name is not None:",
"\"Thraustochytrium Mitochondrial\", \"\", 23, ) register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\", \"\", 24, ) register_ncbi_genetic_code( \"Candidate",
"def register_ncbi_genetic_code(name: str, alt_name: str, id: int): names[name] = len(genetic_codes) if alt_name !=",
"not None: if alt_name in alt_names: self.name, self.alt_name, self.id = genetic_codes[alt_names[alt_name]] return raise",
"2, ) register_ncbi_genetic_code( \"Yeast Mitochondrial\", \"SGC2\", 3, ) register_ncbi_genetic_code( \"Mold Mitochondrial; Protozoan Mitochondrial;",
"Dasycladacean Nuclear; Hexamita Nuclear\", \"SGC5\", 6, ) register_ncbi_genetic_code( \"Echinoderm Mitochondrial; Flatworm Mitochondrial\", \"SGC8\",",
") register_ncbi_genetic_code( \"Alternative Yeast Nuclear\", \"\", 12, ) register_ncbi_genetic_code( \"Ascidian Mitochondrial\", \"\", 13,",
"only one, parameter.\") if name is not None: if name in names: self.name,",
"\"\", 31, ) register_ncbi_genetic_code( \"Balanophoraceae Plastid\", \"\", 32, ) register_ncbi_genetic_code( \"Cephalodiscidae Mitochondrial\", \"\",",
") register_ncbi_genetic_code( \"Euplotid Nuclear\", \"SGC9\", 10, ) register_ncbi_genetic_code( \"Bacterial, Archaeal and Plant Plastid\",",
"register_ncbi_genetic_code( \"Blepharisma Macronuclear\", \"\", 15, ) register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\", \"\", 16, ) register_ncbi_genetic_code(",
"alternative name {alt_name}.\") assert id is not None self.name, self.alt_name, self.id = genetic_codes[ids[id]]",
"Optional[str] = None, id: Optional[int] = None, ): n = sum([name is None,",
"\"SGC0\", 1, ) register_ncbi_genetic_code( \"Vertebrate Mitochondrial\", \"SGC1\", 2, ) register_ncbi_genetic_code( \"Yeast Mitochondrial\", \"SGC2\",",
"ids[id] = len(genetic_codes) genetic_codes.append((name, alt_name, id)) register_ncbi_genetic_code( \"Standard\", \"SGC0\", 1, ) register_ncbi_genetic_code( \"Vertebrate",
"name: Optional[str] = None, alt_name: Optional[str] = None, id: Optional[int] = None, ):",
"\"\", 23, ) register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\", \"\", 24, ) register_ncbi_genetic_code( \"Candidate Division SR1",
"Dict[str, int] = {} ids: Dict[int, int] = {} @dataclass class GeneticCode: name:",
"Flatworm Mitochondrial\", \"\", 14, ) register_ncbi_genetic_code( \"Blepharisma Macronuclear\", \"\", 15, ) register_ncbi_genetic_code( \"Chlorophycean",
"16, ) register_ncbi_genetic_code( \"Trematode Mitochondrial\", \"\", 21, ) register_ncbi_genetic_code( \"Scenedesmus obliquus Mitochondrial\", \"\",",
"Hexamita Nuclear\", \"SGC5\", 6, ) register_ncbi_genetic_code( \"Echinoderm Mitochondrial; Flatworm Mitochondrial\", \"SGC8\", 9, )",
"\"Mesodinium Nuclear\", \"\", 29, ) register_ncbi_genetic_code( \"Peritrich Nuclear\", \"\", 30, ) register_ncbi_genetic_code( \"Blastocrithidia",
"= len(genetic_codes) ids[id] = len(genetic_codes) genetic_codes.append((name, alt_name, id)) register_ncbi_genetic_code( \"Standard\", \"SGC0\", 1, )",
"register_ncbi_genetic_code( \"Karyorelict Nuclear\", \"\", 27, ) register_ncbi_genetic_code( \"Condylostoma Nuclear\", \"\", 28, ) register_ncbi_genetic_code(",
"\"Condylostoma Nuclear\", \"\", 28, ) register_ncbi_genetic_code( \"Mesodinium Nuclear\", \"\", 29, ) register_ncbi_genetic_code( \"Peritrich",
"\"Blastocrithidia Nuclear\", \"\", 31, ) register_ncbi_genetic_code( \"Balanophoraceae Plastid\", \"\", 32, ) register_ncbi_genetic_code( \"Cephalodiscidae",
"List, Optional, Tuple __all__ = [\"GeneticCode\"] genetic_codes: List[Tuple[str, str, int]] = [] names:",
"Mitochondrial\", \"\", 13, ) register_ncbi_genetic_code( \"Alternative Flatworm Mitochondrial\", \"\", 14, ) register_ncbi_genetic_code( \"Blepharisma",
"9, ) register_ncbi_genetic_code( \"Euplotid Nuclear\", \"SGC9\", 10, ) register_ncbi_genetic_code( \"Bacterial, Archaeal and Plant",
"28, ) register_ncbi_genetic_code( \"Mesodinium Nuclear\", \"\", 29, ) register_ncbi_genetic_code( \"Peritrich Nuclear\", \"\", 30,",
"self.alt_name, self.id = genetic_codes[alt_names[alt_name]] return raise ValueError(f\"Unknown alternative name {alt_name}.\") assert id is",
"is not None: if alt_name in alt_names: self.name, self.alt_name, self.id = genetic_codes[alt_names[alt_name]] return",
"n != 2: raise ValueError(\"You must use one, and only one, parameter.\") if",
"is not None: if name in names: self.name, self.alt_name, self.id = genetic_codes[names[name]] return",
") register_ncbi_genetic_code( \"Balanophoraceae Plastid\", \"\", 32, ) register_ncbi_genetic_code( \"Cephalodiscidae Mitochondrial\", \"\", 33, )",
"self.name, self.alt_name, self.id = genetic_codes[names[name]] return raise ValueError(f\"Unknown name {name}.\") if alt_name is",
"obliquus Mitochondrial\", \"\", 22, ) register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\", \"\", 23, ) register_ncbi_genetic_code( \"Rhabdopleuridae",
"ValueError(f\"Unknown name {name}.\") if alt_name is not None: if alt_name in alt_names: self.name,",
"25, ) register_ncbi_genetic_code( \"Pachysolen tannophilus Nuclear\", \"\", 26, ) register_ncbi_genetic_code( \"Karyorelict Nuclear\", \"\",",
"__init__( self, name: Optional[str] = None, alt_name: Optional[str] = None, id: Optional[int] =",
"= len(genetic_codes) if alt_name != \"\": alt_names[alt_name] = len(genetic_codes) ids[id] = len(genetic_codes) genetic_codes.append((name,",
"register_ncbi_genetic_code( \"Candidate Division SR1 and Gracilibacteria\", \"\", 25, ) register_ncbi_genetic_code( \"Pachysolen tannophilus Nuclear\",",
"genetic_codes[ids[id]] def register_ncbi_genetic_code(name: str, alt_name: str, id: int): names[name] = len(genetic_codes) if alt_name",
"int] = {} alt_names: Dict[str, int] = {} ids: Dict[int, int] = {}",
"None: if alt_name in alt_names: self.name, self.alt_name, self.id = genetic_codes[alt_names[alt_name]] return raise ValueError(f\"Unknown",
"\"Chlorophycean Mitochondrial\", \"\", 16, ) register_ncbi_genetic_code( \"Trematode Mitochondrial\", \"\", 21, ) register_ncbi_genetic_code( \"Scenedesmus",
"None, alt_name: Optional[str] = None, id: Optional[int] = None, ): n = sum([name",
"register_ncbi_genetic_code( \"Vertebrate Mitochondrial\", \"SGC1\", 2, ) register_ncbi_genetic_code( \"Yeast Mitochondrial\", \"SGC2\", 3, ) register_ncbi_genetic_code(",
"alt_name: Optional[str] = None, id: Optional[int] = None, ): n = sum([name is",
"\"Echinoderm Mitochondrial; Flatworm Mitochondrial\", \"SGC8\", 9, ) register_ncbi_genetic_code( \"Euplotid Nuclear\", \"SGC9\", 10, )",
"import Dict, List, Optional, Tuple __all__ = [\"GeneticCode\"] genetic_codes: List[Tuple[str, str, int]] =",
"register_ncbi_genetic_code( \"Pachysolen tannophilus Nuclear\", \"\", 26, ) register_ncbi_genetic_code( \"Karyorelict Nuclear\", \"\", 27, )",
"Gracilibacteria\", \"\", 25, ) register_ncbi_genetic_code( \"Pachysolen tannophilus Nuclear\", \"\", 26, ) register_ncbi_genetic_code( \"Karyorelict",
"<filename>iseq/gencode.py # NCBI genetic code table version 4.6 from dataclasses import dataclass from",
"str, id: int): names[name] = len(genetic_codes) if alt_name != \"\": alt_names[alt_name] = len(genetic_codes)",
"register_ncbi_genetic_code( \"Trematode Mitochondrial\", \"\", 21, ) register_ncbi_genetic_code( \"Scenedesmus obliquus Mitochondrial\", \"\", 22, )",
"\"SGC8\", 9, ) register_ncbi_genetic_code( \"Euplotid Nuclear\", \"SGC9\", 10, ) register_ncbi_genetic_code( \"Bacterial, Archaeal and",
"and Gracilibacteria\", \"\", 25, ) register_ncbi_genetic_code( \"Pachysolen tannophilus Nuclear\", \"\", 26, ) register_ncbi_genetic_code(",
"Optional[str] = None, alt_name: Optional[str] = None, id: Optional[int] = None, ): n",
"raise ValueError(f\"Unknown name {name}.\") if alt_name is not None: if alt_name in alt_names:",
"Spiroplasma\", \"SGC3\", 4, ) register_ncbi_genetic_code( \"Invertebrate Mitochondrial\", \"SGC4\", 5, ) register_ncbi_genetic_code( \"Ciliate Nuclear;",
"30, ) register_ncbi_genetic_code( \"Blastocrithidia Nuclear\", \"\", 31, ) register_ncbi_genetic_code( \"Balanophoraceae Plastid\", \"\", 32,",
"23, ) register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\", \"\", 24, ) register_ncbi_genetic_code( \"Candidate Division SR1 and",
"names: Dict[str, int] = {} alt_names: Dict[str, int] = {} ids: Dict[int, int]",
"26, ) register_ncbi_genetic_code( \"Karyorelict Nuclear\", \"\", 27, ) register_ncbi_genetic_code( \"Condylostoma Nuclear\", \"\", 28,",
"Dict[str, int] = {} alt_names: Dict[str, int] = {} ids: Dict[int, int] =",
"12, ) register_ncbi_genetic_code( \"Ascidian Mitochondrial\", \"\", 13, ) register_ncbi_genetic_code( \"Alternative Flatworm Mitochondrial\", \"\",",
") register_ncbi_genetic_code( \"Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate \" \"Mitochondrial; Mycoplasma; Spiroplasma\", \"SGC3\", 4,",
"\"SGC5\", 6, ) register_ncbi_genetic_code( \"Echinoderm Mitochondrial; Flatworm Mitochondrial\", \"SGC8\", 9, ) register_ncbi_genetic_code( \"Euplotid",
"{} alt_names: Dict[str, int] = {} ids: Dict[int, int] = {} @dataclass class",
"\"\", 15, ) register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\", \"\", 16, ) register_ncbi_genetic_code( \"Trematode Mitochondrial\", \"\",",
"id is None]) if n != 2: raise ValueError(\"You must use one, and",
"Flatworm Mitochondrial\", \"SGC8\", 9, ) register_ncbi_genetic_code( \"Euplotid Nuclear\", \"SGC9\", 10, ) register_ncbi_genetic_code( \"Bacterial,",
"raise ValueError(\"You must use one, and only one, parameter.\") if name is not",
"register_ncbi_genetic_code( \"Standard\", \"SGC0\", 1, ) register_ncbi_genetic_code( \"Vertebrate Mitochondrial\", \"SGC1\", 2, ) register_ncbi_genetic_code( \"Yeast",
"alt_name, id)) register_ncbi_genetic_code( \"Standard\", \"SGC0\", 1, ) register_ncbi_genetic_code( \"Vertebrate Mitochondrial\", \"SGC1\", 2, )",
"= None, alt_name: Optional[str] = None, id: Optional[int] = None, ): n =",
") register_ncbi_genetic_code( \"Yeast Mitochondrial\", \"SGC2\", 3, ) register_ncbi_genetic_code( \"Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate",
"if name is not None: if name in names: self.name, self.alt_name, self.id =",
"Mitochondrial; Coelenterate \" \"Mitochondrial; Mycoplasma; Spiroplasma\", \"SGC3\", 4, ) register_ncbi_genetic_code( \"Invertebrate Mitochondrial\", \"SGC4\",",
"None self.name, self.alt_name, self.id = genetic_codes[ids[id]] def register_ncbi_genetic_code(name: str, alt_name: str, id: int):",
"if name in names: self.name, self.alt_name, self.id = genetic_codes[names[name]] return raise ValueError(f\"Unknown name",
"[] names: Dict[str, int] = {} alt_names: Dict[str, int] = {} ids: Dict[int,",
"!= \"\": alt_names[alt_name] = len(genetic_codes) ids[id] = len(genetic_codes) genetic_codes.append((name, alt_name, id)) register_ncbi_genetic_code( \"Standard\",",
"register_ncbi_genetic_code( \"Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate \" \"Mitochondrial; Mycoplasma; Spiroplasma\", \"SGC3\", 4, )",
"# NCBI genetic code table version 4.6 from dataclasses import dataclass from typing",
"\"SGC3\", 4, ) register_ncbi_genetic_code( \"Invertebrate Mitochondrial\", \"SGC4\", 5, ) register_ncbi_genetic_code( \"Ciliate Nuclear; Dasycladacean",
"Optional[int] = None, ): n = sum([name is None, alt_name is None, id",
"None]) if n != 2: raise ValueError(\"You must use one, and only one,",
"name {name}.\") if alt_name is not None: if alt_name in alt_names: self.name, self.alt_name,",
"Tuple __all__ = [\"GeneticCode\"] genetic_codes: List[Tuple[str, str, int]] = [] names: Dict[str, int]",
"self.id = genetic_codes[ids[id]] def register_ncbi_genetic_code(name: str, alt_name: str, id: int): names[name] = len(genetic_codes)",
"ids: Dict[int, int] = {} @dataclass class GeneticCode: name: str alt_name: str id:",
"ValueError(f\"Unknown alternative name {alt_name}.\") assert id is not None self.name, self.alt_name, self.id =",
"int def __init__( self, name: Optional[str] = None, alt_name: Optional[str] = None, id:",
"id is not None self.name, self.alt_name, self.id = genetic_codes[ids[id]] def register_ncbi_genetic_code(name: str, alt_name:",
") register_ncbi_genetic_code( \"Ascidian Mitochondrial\", \"\", 13, ) register_ncbi_genetic_code( \"Alternative Flatworm Mitochondrial\", \"\", 14,",
"register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\", \"\", 24, ) register_ncbi_genetic_code( \"Candidate Division SR1 and Gracilibacteria\", \"\",",
") register_ncbi_genetic_code( \"Alternative Flatworm Mitochondrial\", \"\", 14, ) register_ncbi_genetic_code( \"Blepharisma Macronuclear\", \"\", 15,",
"\"Scenedesmus obliquus Mitochondrial\", \"\", 22, ) register_ncbi_genetic_code( \"Thraustochytrium Mitochondrial\", \"\", 23, ) register_ncbi_genetic_code(",
"List[Tuple[str, str, int]] = [] names: Dict[str, int] = {} alt_names: Dict[str, int]",
"and Plant Plastid\", \"\", 11, ) register_ncbi_genetic_code( \"Alternative Yeast Nuclear\", \"\", 12, )",
"NCBI genetic code table version 4.6 from dataclasses import dataclass from typing import",
"self.id = genetic_codes[names[name]] return raise ValueError(f\"Unknown name {name}.\") if alt_name is not None:",
"typing import Dict, List, Optional, Tuple __all__ = [\"GeneticCode\"] genetic_codes: List[Tuple[str, str, int]]",
"\"Standard\", \"SGC0\", 1, ) register_ncbi_genetic_code( \"Vertebrate Mitochondrial\", \"SGC1\", 2, ) register_ncbi_genetic_code( \"Yeast Mitochondrial\",",
"\"Alternative Yeast Nuclear\", \"\", 12, ) register_ncbi_genetic_code( \"Ascidian Mitochondrial\", \"\", 13, ) register_ncbi_genetic_code(",
"10, ) register_ncbi_genetic_code( \"Bacterial, Archaeal and Plant Plastid\", \"\", 11, ) register_ncbi_genetic_code( \"Alternative",
"\"\", 28, ) register_ncbi_genetic_code( \"Mesodinium Nuclear\", \"\", 29, ) register_ncbi_genetic_code( \"Peritrich Nuclear\", \"\",",
"= [] names: Dict[str, int] = {} alt_names: Dict[str, int] = {} ids:",
") register_ncbi_genetic_code( \"Blepharisma Macronuclear\", \"\", 15, ) register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\", \"\", 16, )",
"id: int def __init__( self, name: Optional[str] = None, alt_name: Optional[str] = None,",
"\"\", 24, ) register_ncbi_genetic_code( \"Candidate Division SR1 and Gracilibacteria\", \"\", 25, ) register_ncbi_genetic_code(",
"str, alt_name: str, id: int): names[name] = len(genetic_codes) if alt_name != \"\": alt_names[alt_name]",
"1, ) register_ncbi_genetic_code( \"Vertebrate Mitochondrial\", \"SGC1\", 2, ) register_ncbi_genetic_code( \"Yeast Mitochondrial\", \"SGC2\", 3,",
"11, ) register_ncbi_genetic_code( \"Alternative Yeast Nuclear\", \"\", 12, ) register_ncbi_genetic_code( \"Ascidian Mitochondrial\", \"\",",
"genetic code table version 4.6 from dataclasses import dataclass from typing import Dict,",
"sum([name is None, alt_name is None, id is None]) if n != 2:",
"= None, id: Optional[int] = None, ): n = sum([name is None, alt_name",
"is None, alt_name is None, id is None]) if n != 2: raise",
"tannophilus Nuclear\", \"\", 26, ) register_ncbi_genetic_code( \"Karyorelict Nuclear\", \"\", 27, ) register_ncbi_genetic_code( \"Condylostoma",
"\"Ascidian Mitochondrial\", \"\", 13, ) register_ncbi_genetic_code( \"Alternative Flatworm Mitochondrial\", \"\", 14, ) register_ncbi_genetic_code(",
"Mitochondrial\", \"\", 23, ) register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\", \"\", 24, ) register_ncbi_genetic_code( \"Candidate Division",
"one, and only one, parameter.\") if name is not None: if name in",
"= {} ids: Dict[int, int] = {} @dataclass class GeneticCode: name: str alt_name:",
"31, ) register_ncbi_genetic_code( \"Balanophoraceae Plastid\", \"\", 32, ) register_ncbi_genetic_code( \"Cephalodiscidae Mitochondrial\", \"\", 33,",
"\"Vertebrate Mitochondrial\", \"SGC1\", 2, ) register_ncbi_genetic_code( \"Yeast Mitochondrial\", \"SGC2\", 3, ) register_ncbi_genetic_code( \"Mold",
"= sum([name is None, alt_name is None, id is None]) if n !=",
"{name}.\") if alt_name is not None: if alt_name in alt_names: self.name, self.alt_name, self.id",
"27, ) register_ncbi_genetic_code( \"Condylostoma Nuclear\", \"\", 28, ) register_ncbi_genetic_code( \"Mesodinium Nuclear\", \"\", 29,",
"\"\", 26, ) register_ncbi_genetic_code( \"Karyorelict Nuclear\", \"\", 27, ) register_ncbi_genetic_code( \"Condylostoma Nuclear\", \"\",",
"Mitochondrial\", \"SGC8\", 9, ) register_ncbi_genetic_code( \"Euplotid Nuclear\", \"SGC9\", 10, ) register_ncbi_genetic_code( \"Bacterial, Archaeal",
") register_ncbi_genetic_code( \"Candidate Division SR1 and Gracilibacteria\", \"\", 25, ) register_ncbi_genetic_code( \"Pachysolen tannophilus",
"alt_name is None, id is None]) if n != 2: raise ValueError(\"You must",
"\"\", 14, ) register_ncbi_genetic_code( \"Blepharisma Macronuclear\", \"\", 15, ) register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\", \"\",",
"Nuclear; Dasycladacean Nuclear; Hexamita Nuclear\", \"SGC5\", 6, ) register_ncbi_genetic_code( \"Echinoderm Mitochondrial; Flatworm Mitochondrial\",",
") register_ncbi_genetic_code( \"Rhabdopleuridae Mitochondrial\", \"\", 24, ) register_ncbi_genetic_code( \"Candidate Division SR1 and Gracilibacteria\",",
"register_ncbi_genetic_code( \"Alternative Flatworm Mitochondrial\", \"\", 14, ) register_ncbi_genetic_code( \"Blepharisma Macronuclear\", \"\", 15, )",
"= {} @dataclass class GeneticCode: name: str alt_name: str id: int def __init__(",
"\"Pachysolen tannophilus Nuclear\", \"\", 26, ) register_ncbi_genetic_code( \"Karyorelict Nuclear\", \"\", 27, ) register_ncbi_genetic_code(",
"int): names[name] = len(genetic_codes) if alt_name != \"\": alt_names[alt_name] = len(genetic_codes) ids[id] =",
") register_ncbi_genetic_code( \"Karyorelict Nuclear\", \"\", 27, ) register_ncbi_genetic_code( \"Condylostoma Nuclear\", \"\", 28, )",
"None, id is None]) if n != 2: raise ValueError(\"You must use one,",
"\"Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate \" \"Mitochondrial; Mycoplasma; Spiroplasma\", \"SGC3\", 4, ) register_ncbi_genetic_code(",
"alt_name: str id: int def __init__( self, name: Optional[str] = None, alt_name: Optional[str]",
"Archaeal and Plant Plastid\", \"\", 11, ) register_ncbi_genetic_code( \"Alternative Yeast Nuclear\", \"\", 12,",
"register_ncbi_genetic_code( \"Yeast Mitochondrial\", \"SGC2\", 3, ) register_ncbi_genetic_code( \"Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate \"",
"self, name: Optional[str] = None, alt_name: Optional[str] = None, id: Optional[int] = None,",
"id)) register_ncbi_genetic_code( \"Standard\", \"SGC0\", 1, ) register_ncbi_genetic_code( \"Vertebrate Mitochondrial\", \"SGC1\", 2, ) register_ncbi_genetic_code(",
"register_ncbi_genetic_code( \"Chlorophycean Mitochondrial\", \"\", 16, ) register_ncbi_genetic_code( \"Trematode Mitochondrial\", \"\", 21, ) register_ncbi_genetic_code(",
") register_ncbi_genetic_code( \"Invertebrate Mitochondrial\", \"SGC4\", 5, ) register_ncbi_genetic_code( \"Ciliate Nuclear; Dasycladacean Nuclear; Hexamita",
"\"Euplotid Nuclear\", \"SGC9\", 10, ) register_ncbi_genetic_code( \"Bacterial, Archaeal and Plant Plastid\", \"\", 11,",
"\"SGC1\", 2, ) register_ncbi_genetic_code( \"Yeast Mitochondrial\", \"SGC2\", 3, ) register_ncbi_genetic_code( \"Mold Mitochondrial; Protozoan",
"alt_names: Dict[str, int] = {} ids: Dict[int, int] = {} @dataclass class GeneticCode:",
"not None: if name in names: self.name, self.alt_name, self.id = genetic_codes[names[name]] return raise",
"str alt_name: str id: int def __init__( self, name: Optional[str] = None, alt_name:",
"alt_name: str, id: int): names[name] = len(genetic_codes) if alt_name != \"\": alt_names[alt_name] =",
"names: self.name, self.alt_name, self.id = genetic_codes[names[name]] return raise ValueError(f\"Unknown name {name}.\") if alt_name",
"= genetic_codes[alt_names[alt_name]] return raise ValueError(f\"Unknown alternative name {alt_name}.\") assert id is not None",
"self.name, self.alt_name, self.id = genetic_codes[alt_names[alt_name]] return raise ValueError(f\"Unknown alternative name {alt_name}.\") assert id",
"if alt_name != \"\": alt_names[alt_name] = len(genetic_codes) ids[id] = len(genetic_codes) genetic_codes.append((name, alt_name, id))"
] |
[
"integers, return all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3],",
"Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ''' class Solution: def",
"[1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ''' class Solution: def permute(self, nums: List[int])",
"[2,3,1], [3,1,2], [3,2,1] ] ''' class Solution: def permute(self, nums: List[int]) -> List[List[int]]:",
"if len(curr) == len(nums): ret.append(list(curr)) return for num in nums: if num in",
"permute(self, nums: List[int]) -> List[List[int]]: def generate_permutation(nums, ret, curr, visited): if len(curr) ==",
"Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] '''",
"len(nums): ret.append(list(curr)) return for num in nums: if num in visited: continue visited.add(num)",
"== len(nums): ret.append(list(curr)) return for num in nums: if num in visited: continue",
"''' class Solution: def permute(self, nums: List[int]) -> List[List[int]]: def generate_permutation(nums, ret, curr,",
"[1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ''' class Solution:",
"ret, curr, visited): if len(curr) == len(nums): ret.append(list(curr)) return for num in nums:",
"[] curr = [] visited = set() generate_permutation(nums, ret, curr, visited) return ret",
"possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]",
"curr, visited): if len(curr) == len(nums): ret.append(list(curr)) return for num in nums: if",
"visited): if len(curr) == len(nums): ret.append(list(curr)) return for num in nums: if num",
"= [] curr = [] visited = set() generate_permutation(nums, ret, curr, visited) return",
"[2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ''' class Solution: def permute(self, nums: List[int]) ->",
"visited.add(num) curr.append(num) generate_permutation(nums, ret, curr, visited) curr.pop() visited.remove(num) ret = [] curr =",
"Given a collection of distinct integers, return all possible permutations. Example: Input: [1,2,3]",
"def generate_permutation(nums, ret, curr, visited): if len(curr) == len(nums): ret.append(list(curr)) return for num",
"curr, visited) curr.pop() visited.remove(num) ret = [] curr = [] visited = set()",
"class Solution: def permute(self, nums: List[int]) -> List[List[int]]: def generate_permutation(nums, ret, curr, visited):",
"num in nums: if num in visited: continue visited.add(num) curr.append(num) generate_permutation(nums, ret, curr,",
"visited) curr.pop() visited.remove(num) ret = [] curr = [] visited = set() generate_permutation(nums,",
"permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]",
"nums: if num in visited: continue visited.add(num) curr.append(num) generate_permutation(nums, ret, curr, visited) curr.pop()",
"return for num in nums: if num in visited: continue visited.add(num) curr.append(num) generate_permutation(nums,",
"in visited: continue visited.add(num) curr.append(num) generate_permutation(nums, ret, curr, visited) curr.pop() visited.remove(num) ret =",
"distinct integers, return all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2],",
"Solution: def permute(self, nums: List[int]) -> List[List[int]]: def generate_permutation(nums, ret, curr, visited): if",
"for num in nums: if num in visited: continue visited.add(num) curr.append(num) generate_permutation(nums, ret,",
"num in visited: continue visited.add(num) curr.append(num) generate_permutation(nums, ret, curr, visited) curr.pop() visited.remove(num) ret",
"ret, curr, visited) curr.pop() visited.remove(num) ret = [] curr = [] visited =",
"] ''' class Solution: def permute(self, nums: List[int]) -> List[List[int]]: def generate_permutation(nums, ret,",
"if num in visited: continue visited.add(num) curr.append(num) generate_permutation(nums, ret, curr, visited) curr.pop() visited.remove(num)",
"-> List[List[int]]: def generate_permutation(nums, ret, curr, visited): if len(curr) == len(nums): ret.append(list(curr)) return",
"generate_permutation(nums, ret, curr, visited): if len(curr) == len(nums): ret.append(list(curr)) return for num in",
"all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2],",
"''' Given a collection of distinct integers, return all possible permutations. Example: Input:",
"a collection of distinct integers, return all possible permutations. Example: Input: [1,2,3] Output:",
"visited.remove(num) ret = [] curr = [] visited = set() generate_permutation(nums, ret, curr,",
"List[int]) -> List[List[int]]: def generate_permutation(nums, ret, curr, visited): if len(curr) == len(nums): ret.append(list(curr))",
"def permute(self, nums: List[int]) -> List[List[int]]: def generate_permutation(nums, ret, curr, visited): if len(curr)",
"continue visited.add(num) curr.append(num) generate_permutation(nums, ret, curr, visited) curr.pop() visited.remove(num) ret = [] curr",
"[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ''' class Solution: def permute(self,",
"visited: continue visited.add(num) curr.append(num) generate_permutation(nums, ret, curr, visited) curr.pop() visited.remove(num) ret = []",
"curr.append(num) generate_permutation(nums, ret, curr, visited) curr.pop() visited.remove(num) ret = [] curr = []",
"generate_permutation(nums, ret, curr, visited) curr.pop() visited.remove(num) ret = [] curr = [] visited",
"List[List[int]]: def generate_permutation(nums, ret, curr, visited): if len(curr) == len(nums): ret.append(list(curr)) return for",
"nums: List[int]) -> List[List[int]]: def generate_permutation(nums, ret, curr, visited): if len(curr) == len(nums):",
"ret.append(list(curr)) return for num in nums: if num in visited: continue visited.add(num) curr.append(num)",
"[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ''' class Solution: def permute(self, nums:",
"len(curr) == len(nums): ret.append(list(curr)) return for num in nums: if num in visited:",
"of distinct integers, return all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3],",
"Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ''' class",
"[3,1,2], [3,2,1] ] ''' class Solution: def permute(self, nums: List[int]) -> List[List[int]]: def",
"return all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1],",
"[3,2,1] ] ''' class Solution: def permute(self, nums: List[int]) -> List[List[int]]: def generate_permutation(nums,",
"ret = [] curr = [] visited = set() generate_permutation(nums, ret, curr, visited)",
"collection of distinct integers, return all possible permutations. Example: Input: [1,2,3] Output: [",
"in nums: if num in visited: continue visited.add(num) curr.append(num) generate_permutation(nums, ret, curr, visited)",
"curr.pop() visited.remove(num) ret = [] curr = [] visited = set() generate_permutation(nums, ret,"
] |
[
") if __name__ == '__main__': _client = SentinelClient(url='redis://localhost:26379') _pub_sub = _client.client.pubsub() _pub_sub.psubscribe('*') for",
"is healthy. \"\"\" self.client = StrictRedis.from_url( url=url, db=db, client_name=name, health_check_interval=health_check_interval, decode_responses=True ) if",
"health_check_interval=30): \"\"\"create a redis client. Args: url: redis server url. db: redis database,",
"redis database, default 0. name: client name, default 'default'. health_check_interval: how many seconds",
"url. db: redis database, default 0. name: client name, default 'default'. health_check_interval: how",
"= StrictRedis.from_url( url=url, db=db, client_name=name, health_check_interval=health_check_interval, decode_responses=True ) if __name__ == '__main__': _client",
"default 0. name: client name, default 'default'. health_check_interval: how many seconds to check",
"check whether the redis server is healthy. \"\"\" self.client = StrictRedis.from_url( url=url, db=db,",
"== '__main__': _client = SentinelClient(url='redis://localhost:26379') _pub_sub = _client.client.pubsub() _pub_sub.psubscribe('*') for i in _pub_sub.listen():",
"client name, default 'default'. health_check_interval: how many seconds to check whether the redis",
"SentinelClient(object): def __init__(self, url, db=None, name='default', health_check_interval=30): \"\"\"create a redis client. Args: url:",
"name='default', health_check_interval=30): \"\"\"create a redis client. Args: url: redis server url. db: redis",
"url: redis server url. db: redis database, default 0. name: client name, default",
"redis import StrictRedis class SentinelClient(object): def __init__(self, url, db=None, name='default', health_check_interval=30): \"\"\"create a",
"to check whether the redis server is healthy. \"\"\" self.client = StrictRedis.from_url( url=url,",
"healthy. \"\"\" self.client = StrictRedis.from_url( url=url, db=db, client_name=name, health_check_interval=health_check_interval, decode_responses=True ) if __name__",
"name: client name, default 'default'. health_check_interval: how many seconds to check whether the",
"if __name__ == '__main__': _client = SentinelClient(url='redis://localhost:26379') _pub_sub = _client.client.pubsub() _pub_sub.psubscribe('*') for i",
"a redis client. Args: url: redis server url. db: redis database, default 0.",
"\"\"\"create a redis client. Args: url: redis server url. db: redis database, default",
"StrictRedis.from_url( url=url, db=db, client_name=name, health_check_interval=health_check_interval, decode_responses=True ) if __name__ == '__main__': _client =",
"'default'. health_check_interval: how many seconds to check whether the redis server is healthy.",
"server url. db: redis database, default 0. name: client name, default 'default'. health_check_interval:",
"db=db, client_name=name, health_check_interval=health_check_interval, decode_responses=True ) if __name__ == '__main__': _client = SentinelClient(url='redis://localhost:26379') _pub_sub",
"self.client = StrictRedis.from_url( url=url, db=db, client_name=name, health_check_interval=health_check_interval, decode_responses=True ) if __name__ == '__main__':",
"StrictRedis class SentinelClient(object): def __init__(self, url, db=None, name='default', health_check_interval=30): \"\"\"create a redis client.",
"\"\"\" self.client = StrictRedis.from_url( url=url, db=db, client_name=name, health_check_interval=health_check_interval, decode_responses=True ) if __name__ ==",
"many seconds to check whether the redis server is healthy. \"\"\" self.client =",
"health_check_interval: how many seconds to check whether the redis server is healthy. \"\"\"",
"'__main__': _client = SentinelClient(url='redis://localhost:26379') _pub_sub = _client.client.pubsub() _pub_sub.psubscribe('*') for i in _pub_sub.listen(): print(i)",
"url=url, db=db, client_name=name, health_check_interval=health_check_interval, decode_responses=True ) if __name__ == '__main__': _client = SentinelClient(url='redis://localhost:26379')",
"redis server url. db: redis database, default 0. name: client name, default 'default'.",
"database, default 0. name: client name, default 'default'. health_check_interval: how many seconds to",
"redis server is healthy. \"\"\" self.client = StrictRedis.from_url( url=url, db=db, client_name=name, health_check_interval=health_check_interval, decode_responses=True",
"redis client. Args: url: redis server url. db: redis database, default 0. name:",
"__init__(self, url, db=None, name='default', health_check_interval=30): \"\"\"create a redis client. Args: url: redis server",
"health_check_interval=health_check_interval, decode_responses=True ) if __name__ == '__main__': _client = SentinelClient(url='redis://localhost:26379') _pub_sub = _client.client.pubsub()",
"decode_responses=True ) if __name__ == '__main__': _client = SentinelClient(url='redis://localhost:26379') _pub_sub = _client.client.pubsub() _pub_sub.psubscribe('*')",
"client. Args: url: redis server url. db: redis database, default 0. name: client",
"import StrictRedis class SentinelClient(object): def __init__(self, url, db=None, name='default', health_check_interval=30): \"\"\"create a redis",
"client_name=name, health_check_interval=health_check_interval, decode_responses=True ) if __name__ == '__main__': _client = SentinelClient(url='redis://localhost:26379') _pub_sub =",
"def __init__(self, url, db=None, name='default', health_check_interval=30): \"\"\"create a redis client. Args: url: redis",
"class SentinelClient(object): def __init__(self, url, db=None, name='default', health_check_interval=30): \"\"\"create a redis client. Args:",
"the redis server is healthy. \"\"\" self.client = StrictRedis.from_url( url=url, db=db, client_name=name, health_check_interval=health_check_interval,",
"server is healthy. \"\"\" self.client = StrictRedis.from_url( url=url, db=db, client_name=name, health_check_interval=health_check_interval, decode_responses=True )",
"whether the redis server is healthy. \"\"\" self.client = StrictRedis.from_url( url=url, db=db, client_name=name,",
"Args: url: redis server url. db: redis database, default 0. name: client name,",
"default 'default'. health_check_interval: how many seconds to check whether the redis server is",
"__name__ == '__main__': _client = SentinelClient(url='redis://localhost:26379') _pub_sub = _client.client.pubsub() _pub_sub.psubscribe('*') for i in",
"db: redis database, default 0. name: client name, default 'default'. health_check_interval: how many",
"name, default 'default'. health_check_interval: how many seconds to check whether the redis server",
"seconds to check whether the redis server is healthy. \"\"\" self.client = StrictRedis.from_url(",
"url, db=None, name='default', health_check_interval=30): \"\"\"create a redis client. Args: url: redis server url.",
"0. name: client name, default 'default'. health_check_interval: how many seconds to check whether",
"from redis import StrictRedis class SentinelClient(object): def __init__(self, url, db=None, name='default', health_check_interval=30): \"\"\"create",
"db=None, name='default', health_check_interval=30): \"\"\"create a redis client. Args: url: redis server url. db:",
"how many seconds to check whether the redis server is healthy. \"\"\" self.client"
] |
[
"harmonic transform of the instrumental beam \\ (assumed to be rotationally symmetric -",
"alms[:, :, 1] return alms def get_templates(self): \"\"\" Returns a 3D array ([ntemp][nmap][npix])",
"0 to 3*nside-1). :param purify_e: use pure E-modes? :param purify_b: use pure B-modes?",
"# Flatten if 2D maps try: templates = np.array(templates) if wt.flip_th: templates =",
"maps = np.array(maps) if wt.flip_th: maps = maps[:, ::-1, :] if wt.flip_ph: maps",
"using the IAU convention \\ (i.e. x grows with declination). In this case,",
"was initialized with contaminant \\ templates, the maps returned by this function have",
"(lmax)) beam_use = beam else: if beam is None: beam_use = np.ones(lmax+1) else:",
"and 2 for spin-2 \\ fields, and nx,ny define the patch. The best-fit",
"as np from pymaster.utils import NmtWCSTranslator class NmtField(object): \"\"\" An NmtField object contains",
"alms = [] for imap in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms))) alms = np.array(alms).reshape([self.fl.nmaps,",
"should \\ have at least as many elements as the maximum multipole sampled",
":param purify_e: use pure E-modes? :param purify_b: use pure B-modes? :param n_iter_mask_purify: number",
"else: if beam is None: beam_use = np.array([[-1.], [-1.]]) else: raise ValueError(\"Input beam",
"<= lmax: raise ValueError(\"Input beam must have at least %d elements \" \"given",
"or None\\n\") if mask_only: self.fl = lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta,",
"range(self.fl.nmaps): maps[imap, :] = lib.get_map_flat(self.fl, imap, int(self.fl.npix)) mps = maps.reshape([self.fl.nmaps, self.ny, self.nx]) return",
"input, and will default to 2 if there are 2 maps. :param templates:",
"values of l for which de beam is defined, with beam[1] \\ containing",
"fields\") # Flatten if 2D maps if (not mask_only) and (wt.is_healpix == 0):",
"masks \\ and contaminant templates. :param float lx,ly: size of the patch in",
"if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\") maps = np.zeros([self.fl.nmaps, self.fl.npix])",
"as many elements as the maximum multipole sampled by \\ the maps +",
"no maps. The field \\ can then be used to compute a mode-coupling",
"3 * nside - 1 for HEALPix maps). :param masked_on_input: set to `True`",
"\"\"\" Returns a 3D array ([nmap][ny][nx]) corresponding to the observed \\ maps for",
"\" \"To use this function, create an `NmtFieldFlat` \" \"object with `lite=False`.\") maps",
"field's mask. :param maps: 2 2D arrays (nmaps,nx,ny) containing the observed maps \\",
"is not None: lib.field_flat_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns this field's",
"__del__(self): if self.fl is not None: if lib.field_flat_free is not None: lib.field_flat_free(self.fl) self.fl",
"2: raise ValueError(\"Purification only implemented for spin-2 fields\") # Flatten if 2D maps",
"which should be 1 for a spin-0 field and 2 otherwise. \\ The",
"If negative or zero, the maximum multipole given the map \\ resolution will",
"try: maps = np.array(maps) if wt.flip_th: maps = maps[:, ::-1, :] if wt.flip_ph:",
"= beam else: if beam is None: beam_use = np.ones(lmax+1) else: raise ValueError(\"Input",
"given the map \\ resolution will be used (e.g. 3 * nside -",
"have their best-fit \\ contribution from these contaminants removed. :return: 3D array of",
"beam: spherical harmonic transform of the instrumental beam \\ (assumed to be rotationally",
":param tol_pinv: when computing the pseudo-inverse of the contaminant \\ covariance matrix, all",
"which map power spectra will be \\ computed. If negative or zero, the",
"singular values, where max_eval is the largest eigenvalue. \\ Only relevant if passing",
"np.ndarray)): if len(beam) <= lmax: raise ValueError(\"Input beam must have at least %d",
"are likely to be highly correlated. :param masked_on_input: set to `True` if input",
"maps for this field. Should be \\ at least 2-dimensional. The first dimension",
"templates: array containing a set of contaminant templates for \\ this field. This",
"(not mask_only) and (wt.is_healpix == 0): try: maps = np.array(maps) if wt.flip_th: maps",
"def get_mask(self): \"\"\" Returns this field's mask as a 1D array. :return: mask",
"np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2]) alms = alms[:, :, 0] + 1j * alms[:, :,",
"the usual Q/U Stokes parameters for \\ polarization, or e1/e2 (gamma1/gamma2 etc.) in",
"len(templates) if (len(templates[0]) != 1) and (len(templates[0]) != 2): raise ValueError(\"Must supply 1",
"SHT of the mask when using E/B purification. :param tol_pinv: when computing the",
"\"\"\" def __init__(self, lx, ly, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, tol_pinv=1E-10,",
"maps (ntemp,nmaps,nx,ny) containing a set \\ of contaminant templates for this field. This",
"False nmaps = len(maps) if (nmaps != 1) and (nmaps != 2): raise",
"templates = templates[:, :, :, ::-1] templates = templates.reshape([ntemp, len(maps), wt.npix]) except (IndexError,",
"per field\") if wt.is_healpix == 0: # Flatten if 2D maps try: templates",
"spin = 0 else: spin = 2 else: if (((spin != 0) and",
"\\ if you're using purification. :param lite: set to `True` if you want",
"contaminant \\ covariance matrix, all eigenvalues below tol_pinv * max_eval will \\ be",
"self.fl = lib.field_alloc_new_notemp( wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin,",
"tuple, np.ndarray)): ntemp = len(templates) if (len(templates[0]) != 1) and (len(templates[0]) != 2):",
"return mps def get_templates(self): \"\"\" Returns a 4D array ([ntemp][nmap][ny][nx]) corresponding to the",
"automatically removed \\ from the maps unless templates=None. :param beam: spherical harmonic transform",
"for spin-2 fields\") # Flatten if 2D maps if (not mask_only) and (wt.is_healpix",
"if len(templates[0][0]) != len(mask): raise ValueError(\"All maps must have the same resolution\") else:",
"int(self.fl.npix)).reshape([self.ny, self.nx]) return msk def get_maps(self): \"\"\" Returns a 3D array ([nmap][ny][nx]) corresponding",
"FT of the instrumental beam \\ (assumed to be rotationally symmetric). beam[0] should",
"de beam is defined, with beam[1] \\ containing the beam values. If None,",
"this field's mask as a 2D array ([ny][nx]). :return: 2D mask. \"\"\" msk",
"`NmtFieldFlat` \" \"object with `lite=False`.\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in",
"relevant if passing contaminant templates that are likely to be \\ highly correlated.",
"np.array(tmps) else: if templates is not None: raise ValueError(\"Input templates can only be",
"\\ ntemp is the number of templates, nmap should be 1 for spin-0",
"dimension corresponds to the number \\ of maps, which should be 1 for",
"lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, beam_use, pure_e, pure_b, n_iter_mask_purify)",
"and len(maps) == 1) or ((spin == 0) and len(maps) != 1)): raise",
"get_mask(self): \"\"\" Returns this field's mask as a 2D array ([ny][nx]). :return: 2D",
"be [npix] for HEALPix maps or \\ [ny,nx] for maps with rectangular pixels.",
"for lightweight fields\") alms = [] for imap in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms)))",
"\"associated with a single map\") if (pure_e or pure_b) and spin != 2:",
"`True` if you want to only store the bare minimum \\ necessary to",
"0: if wt.flip_th: mask = mask[::-1, :] if wt.flip_ph: mask = mask[:, ::-1]",
"if (pure_e or pure_b) and spin != 2: raise ValueError(\"Purification only implemented for",
"create an `NmtFieldFlat` \" \"object with `lite=False`.\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap",
"lib.get_map_flat(self.fl, imap, int(self.fl.npix)) mps = maps.reshape([self.fl.nmaps, self.ny, self.nx]) return mps def get_templates(self): \"\"\"",
"this field's mask as a 1D array. :return: mask \"\"\" return lib.get_mask(self.fl, int(self.fl.npix))",
"of the instrumental beam \\ (assumed to be rotationally symmetric). beam[0] should contain",
"use pure B-modes? :param n_iter_mask_purify: number of iterations used to compute an \\",
"= np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2]) alms = alms[:, :, 0] + 1j * alms[:,",
"map, it should contain 3*nside \\ elements, corresponding to multipoles from 0 to",
"tol_pinv * max_eval will be \\ treated as singular values, where max_eval is",
"self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap, :]",
"None, no beam will be corrected \\ for. :param purify_e: use pure E-modes?",
"for \" \"flat-sky field\") # Flatten arrays and check dimensions shape_2D = np.shape(mask)",
"their best-fit \\ contribution from these contaminants removed. :return: 3D array of flat-sky",
"otherwise. \\ If `None`, this field will only contain a mask but no",
"in templates: tmp = [] if len(t) != nmaps: raise ValueError(\"Maps and templates",
"be \\ at least 2-dimensional. The first dimension corresponds to the number \\",
"elements, corresponding to multipoles from 0 to 3*nside-1). :param purify_e: use pure E-modes?",
"spin, mask, maps, beam_use, pure_e, pure_b, n_iter_mask_purify, n_iter, masked_input, int(lite)) self.lite = lite",
"which should be 1 for a spin-0 field and 2 otherwise. \\ If",
"e1/e2 (gamma1/gamma2 etc.) in the case of cosmic \\ shear. It is important",
"store the bare minimum \\ necessary to run a standard pseudo-Cl with deprojection",
"by the resulting object. \"\"\" def __init__(self, mask, maps, spin=None, templates=None, beam=None, purify_e=False,",
"The first dimension corresponds to the number \\ of maps, which should be",
"the number of \\ templates, nmap should be 1 for spin-0 fields and",
"number of \\ templates, nmap should be 1 for spin-0 fields and 2",
"input maps and templates are already multiplied by the masks. Note that this",
"\"To use this function, create an `NmtFieldFlat` \" \"object with `lite=False`.\") temp =",
"for m in maps: if np.shape(m) != shape_2D: raise ValueError(\"Mask and maps don't",
"removed. :return: 2D array of maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable",
"nx,ny define the patch. The best-fit contribution \\ from each contaminant is automatically",
"the \\ flat-sky fields to correlate, including their observed maps, masks \\ and",
"single map\") if (pure_e or pure_b) and spin != 2: raise ValueError(\"Purification only",
"be an array or None\\n\") if mask_only: self.fl = lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht, wt.nx,",
"for galaxy ellipticities to be provided using the IAU convention \\ (i.e. x",
"1-dimensional for a HEALPix map or 2-dimensional for a map \\ with rectangular",
"__init__(self, lx, ly, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, tol_pinv=1E-10, masked_on_input=False, lite=False):",
"1 or 2 maps per field\") if spin is None: if nmaps ==",
"= len(templates) if (len(templates[0]) != 1) and (len(templates[0]) != 2): raise ValueError(\"Must supply",
"beam will be corrected \\ for. :param purify_e: use pure E-modes? :param purify_b:",
"it to create an \\ NmtField. See more \\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\",
"= [] for m in maps: if np.shape(m) != shape_2D: raise ValueError(\"Mask and",
"masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp( wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta,",
"lx, ly, spin, msk, mps, tmps, beam_use, pure_e, pure_b, tol_pinv, masked_input, int(lite)) else:",
"beam is None: beam_use = np.ones(lmax+1) else: raise ValueError(\"Input beam can only be",
"lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx]) return msk def get_maps(self): \"\"\" Returns a 3D array ([nmap][ny][nx])",
"spin, msk, beam_use, pure_e, pure_b) else: # Generate field if isinstance(templates, (list, tuple,",
"2 maps per field\") if spin is None: if nmaps == 1: spin",
"field spin\") lite = True else: mask_only = False if (len(maps) != 1)",
":return: 3D array of flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable",
"describing the \\ flat-sky fields to correlate, including their observed maps, masks \\",
"or 2 maps per field\") if spin is None: if nmaps == 1:",
"= 2 else: if (((spin != 0) and nmaps == 1) or ((spin",
"an `NmtFieldFlat` \" \"object with `lite=False`.\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp",
"templates = templates[:, :, ::-1, :] if wt.flip_ph: templates = templates[:, :, :,",
"lmax_sht: maximum multipole up to which map power spectra will be \\ computed.",
"\\ shear. It is important to note that NaMaster uses the same \\",
"of contaminant templates for \\ this field. This array should have shape [ntemp][nmap]...,",
"maps[:, :, ::-1] maps = maps.reshape([len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input maps",
"maps don't have the same shape\") mps.append((m.astype(np.float64)).flatten()) mps = np.array(mps) # Flatten templates",
"map should be swapped before using it to create an \\ NmtField. See",
"get_maps(self): \"\"\" Returns a 2D array ([nmap][npix]) corresponding to the observed maps \\",
"\"\"\" Returns this field's mask as a 1D array. :return: mask \"\"\" return",
"up by the resulting object. \"\"\" def __init__(self, lx, ly, mask, maps, spin=None,",
"have \" \"the same shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps = np.array(tmps) else: if templates",
"pseudo-inverse of the contaminant \\ covariance matrix, all eigenvalues below tol_pinv * max_eval",
"contains all the information describing the \\ flat-sky fields to correlate, including their",
"spectra. :param spin: field's spin. If `None` it will be set to 0",
"on input, and will default to 2 if there are 2 maps. :param",
":param templates: array containing a set of contaminant templates for \\ this field.",
"from these contaminants removed. :return: 3D array of flat-sky maps \"\"\" if self.lite:",
"it should contain 3*nside \\ elements, corresponding to multipoles from 0 to 3*nside-1).",
"including their observed maps, masks \\ and contaminant templates. :param float lx,ly: size",
"memory taken up by the resulting object. \"\"\" def __init__(self, lx, ly, mask,",
"should be 1 for a spin-0 field and 2 otherwise. \\ If `None`,",
"lib.field_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns this field's mask as a",
"shear. It is important to note that NaMaster uses the same \\ polarization",
"tuple, np.ndarray)): beam_use = beam else: if beam is None: beam_use = np.array([[-1.],",
":return: 3D array of maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for",
"if (len(maps) != 1) and (len(maps) != 2): raise ValueError(\"Must supply 1 or",
"for spin-0 fields \\ and 2 otherwise. The other dimensions should be [npix]",
"wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, beam_use, pure_e, pure_b, n_iter_mask_purify, n_iter, masked_input,",
"function have their best-fit \\ contribution from these contaminants removed. :return: 2D array",
"tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps = np.array(tmps) else: if templates is not None: raise ValueError(\"Input",
"field. This array should have shape [ntemp][nmap]..., where \\ ntemp is the number",
"fields are \" \"associated with a single map\") if (pure_e or pure_b) and",
"must have at least %d elements \" \"given the input map resolution\" %",
"maps is None: mask_only = True if spin is None: raise ValueError(\"Please supply",
"isinstance(templates, (list, tuple, np.ndarray)): tmps = [] for t in templates: tmp =",
"__del__(self): if self.fl is not None: if lib.field_free is not None: lib.field_free(self.fl) self.fl",
"((spin == 0) and len(maps) != 1)): raise ValueError(\"Spin-zero fields are \" \"associated",
"\"To use this function, create an `NmtFieldFlat` \" \"object with `lite=False`.\") maps =",
"wrong shape\") if len(templates[0][0]) != len(mask): raise ValueError(\"All maps must have the same",
"i.e. no m dependence). If \\ None, no beam will be corrected for.",
"3D array of maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight",
":param purify_e: use pure E-modes? :param purify_b: use pure B-modes? :param tol_pinv: when",
"supply sensible dimensions for \" \"flat-sky field\") # Flatten arrays and check dimensions",
"spin = 2 else: if (((spin != 0) and nmaps == 1) or",
"raise ValueError(\"Alms unavailable for lightweight fields\") alms = [] for imap in range(self.fl.nmaps):",
"for. Otherwise, this array should \\ have at least as many elements as",
"unless templates=None. :param beam: spherical harmonic transform of the instrumental beam \\ (assumed",
"self.fl, itemp, imap, int(self.fl.npix) ) else: tmps = temp return tmps class NmtFieldFlat(object):",
"= lib.field_alloc_empty_flat(self.nx, self.ny, lx, ly, spin, msk, beam_use, pure_e, pure_b) else: # Generate",
"this field. Should be \\ at least 2-dimensional. The first dimension corresponds to",
"if lib.field_free is not None: lib.field_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns",
"default to 2 if there are 2 maps. :param templates: array containing a",
"self.nx]) return msk def get_maps(self): \"\"\" Returns a 3D array ([nmap][ny][nx]) corresponding to",
"multipole given the map \\ resolution will be used (e.g. 3 * nside",
"= None def get_mask(self): \"\"\" Returns this field's mask as a 1D array.",
"!= 2: raise ValueError(\"Purification only implemented for spin-2 fields\") # Flatten if 2D",
"deprojection bias. This \\ will reduce the memory taken up by the resulting",
"self.lite: raise ValueError(\"Alms unavailable for lightweight fields\") alms = [] for imap in",
"mask_only: self.fl = lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin,",
"this field. :return: 2D array of alms \"\"\" if self.lite: raise ValueError(\"Alms unavailable",
"will be corrected for. Otherwise, this array should \\ have at least as",
"\" \"or None\") # Form beam if isinstance(beam, (list, tuple, np.ndarray)): beam_use =",
"else: if (((spin != 0) and nmaps == 1) or ((spin == 0)",
"mask but no maps. The field \\ can then be used to compute",
"for maps with rectangular pixels. For a spin>0 field, the two \\ maps",
"a 3D array ([ntemp][nmap][npix]) corresponding to the \\ contaminant templates passed when initializing",
"ntemp is the number of \\ templates, nmap should be 1 for spin-0",
"mask. \\ Should be 1-dimensional for a HEALPix map or 2-dimensional for a",
"symmetric). beam[0] should contain \\ the values of l for which de beam",
"templates, nmap should be 1 for spin-0 fields and 2 for spin-2 \\",
"field and 2 otherwise. \\ If `None`, this field will only contain a",
"if wt.is_healpix == 0: if wt.flip_th: mask = mask[::-1, :] if wt.flip_ph: mask",
"the \\ e2/gamma2 map should be swapped before using it to create an",
"def get_templates(self): \"\"\" Returns a 4D array ([ntemp][nmap][ny][nx]) corresponding to the \\ contaminant",
"field's mask as a 2D array ([ny][nx]). :return: 2D mask. \"\"\" msk =",
"* max_eval will \\ be treated as singular values, where max_eval is the",
"to be rotationally symmetric). beam[0] should contain \\ the values of l for",
"a 3D array ([nmap][ny][nx]) corresponding to the observed \\ maps for this field.",
"object contains all the information describing the \\ flat-sky fields to correlate, including",
"if self.fl is not None: if lib.field_flat_free is not None: lib.field_flat_free(self.fl) self.fl =",
"HEALPix maps or [ny,nx] for maps with rectangular pixels. The \\ best-fit contribution",
"field\") # Flatten arrays and check dimensions shape_2D = np.shape(mask) self.ny = shape_2D[0]",
"colatitude theta). It is however more common \\ for galaxy ellipticities to be",
"tuple, np.ndarray)): self.fl = lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max,",
"(not mask_only): # Flatten maps mps = [] for m in maps: if",
":param lite: set to `True` if you want to only store the bare",
"implemented for spin-2 fields\") # Flatten mask msk = (mask.astype(np.float64)).flatten() if (not mask_only):",
"1 for HEALPix maps). :param masked_on_input: set to `True` if input maps and",
"maps returned by this function have their best-fit \\ contribution from these contaminants",
"y directions (in \\ radians) :param mask: 2D array (nx,ny) containing a HEALPix",
"or \" \"None\") if mask_only: self.fl = lib.field_alloc_empty_flat(self.nx, self.ny, lx, ly, spin, msk,",
"be \\ highly correlated. :param wcs: a WCS object if using rectangular pixels",
"is defined, with beam[1] \\ containing the beam values. If None, no beam",
"(len(maps) != 2): raise ValueError(\"Must supply 1 or 2 maps per field\") if",
"ValueError(\"Mask and templates don't have \" \"the same shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps =",
"contains all the information describing the fields to correlate, including their observed maps,",
"maps, masks and contaminant templates. :param mask: array containing a map corresponding to",
"([ntemp][nmap][npix]) corresponding to the \\ contaminant templates passed when initializing this field. :return:",
"field. This array should have \\ shape [ntemp][nmap][nx][ny], where ntemp is the number",
"number \\ of maps, which should be 1 for a spin-0 field and",
"\\ (assumed to be rotationally symmetric - i.e. no m dependence). If \\",
"(nmaps,nx,ny) containing the observed maps \\ for this field. The first dimension corresponds",
"np.ones(lmax+1) else: raise ValueError(\"Input beam can only be an array or None\\n\") if",
"with beam[1] \\ containing the beam values. If None, no beam will be",
"beam: 2D array (2,nl) defining the FT of the instrumental beam \\ (assumed",
"same shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps = np.array(tmps) else: if templates is not None:",
"mode-coupling matrix, for instance, \\ but not actual power spectra. :param spin: field's",
"range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp_flat( self.fl, itemp, imap, int(self.fl.npix) ) tmps =",
"arrays and check dimensions shape_2D = np.shape(mask) self.ny = shape_2D[0] self.nx = shape_2D[1]",
"maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None, n_iter=3, lmax_sht=-1, masked_on_input=False, lite=False):",
"tmp = [] if len(t) != nmaps: raise ValueError(\"Maps and templates should have",
"maps. The field \\ can then be used to compute a mode-coupling matrix,",
"2D array ([ny][nx]). :return: 2D mask. \"\"\" msk = lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx]) return",
"if mask_only: self.fl = lib.field_alloc_empty_flat(self.nx, self.ny, lx, ly, spin, msk, beam_use, pure_e, pure_b)",
"case of cosmic \\ shear. It is important to note that NaMaster uses",
"def get_maps(self): \"\"\" Returns a 3D array ([nmap][ny][nx]) corresponding to the observed \\",
"raise ValueError(\"Purification only implemented for spin-2 fields\") # Flatten if 2D maps if",
"If `None`, this field will only contain a mask but no maps. The",
"get_mask(self): \"\"\" Returns this field's mask as a 1D array. :return: mask \"\"\"",
"pixels (see \\ http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter: number of iterations when computing a_lms. :param",
"values. If None, no beam will be corrected \\ for. :param purify_e: use",
"= lib.field_alloc_new_flat(self.nx, self.ny, lx, ly, spin, msk, mps, tmps, beam_use, pure_e, pure_b, tol_pinv,",
"lite def __del__(self): if self.fl is not None: if lib.field_free is not None:",
"must have the same resolution\") else: if templates is not None: raise ValueError(\"Input",
"not None: lib.field_flat_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns this field's mask",
"same shape\") mps.append((m.astype(np.float64)).flatten()) mps = np.array(mps) # Flatten templates if isinstance(templates, (list, tuple,",
"by the resulting object. \"\"\" def __init__(self, lx, ly, mask, maps, spin=None, templates=None,",
"If \\ None, no beam will be corrected for. Otherwise, this array should",
"standard pseudo-Cl with deprojection and \\ purification, but you don't care about deprojection",
"if passing contaminant templates that are likely to be \\ highly correlated. :param",
"\"\"\" msk = lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx]) return msk def get_maps(self): \"\"\" Returns a",
"2D maps if (not mask_only) and (wt.is_healpix == 0): try: maps = np.array(maps)",
"This array should have \\ shape [ntemp][nmap][nx][ny], where ntemp is the number of",
"fields and 2 for spin-2 \\ fields, and nx,ny define the patch. The",
"with contaminant \\ templates, the maps returned by this function have their best-fit",
"maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, tol_pinv=1E-10, masked_on_input=False, lite=False): self.fl = None pure_e",
"unavailable for lightweight fields. \" \"To use this function, create an `NmtFieldFlat` \"",
"Returns this field's mask as a 1D array. :return: mask \"\"\" return lib.get_mask(self.fl,",
"m in t: if np.shape(m) != shape_2D: raise ValueError(\"Mask and templates don't have",
"the same resolution\") if (pure_e or pure_b) and spin != 2: raise ValueError(\"Purification",
"nmaps == 1) or ((spin == 0) and nmaps != 1)): raise ValueError(\"Spin-zero",
"return lib.get_mask(self.fl, int(self.fl.npix)) def get_maps(self): \"\"\" Returns a 2D array ([nmap][npix]) corresponding to",
"shape\") if len(templates[0][0]) != len(mask): raise ValueError(\"All maps must have the same resolution\")",
"n_iter, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp( wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi,",
"== 1: spin = 0 else: spin = 2 else: if (((spin !=",
"raise ValueError(\"Input templates can only be an array \" \"or None\") # Form",
"there are 2 maps. :param templates: array of maps (ntemp,nmaps,nx,ny) containing a set",
"best-fit \\ contribution from these contaminants removed. :return: 3D array of flat-sky maps",
"in range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp( self.fl, itemp,",
"use pure B-modes? :param tol_pinv: when computing the pseudo-inverse of the contaminant \\",
"np.ndarray)): ntemp = len(templates) if (len(templates[0]) != 1) and (len(templates[0]) != 2): raise",
"the wrong shape\") if isinstance(templates, (list, tuple, np.ndarray)): ntemp = len(templates) if (len(templates[0])",
"the masks. Note that this is not advisable if you're using purification. :param",
"resolution\") else: if templates is not None: raise ValueError(\"Input templates can only be",
"[npix] for \\ HEALPix maps or [ny,nx] for maps with rectangular pixels. The",
"with rectangular pixels. The \\ best-fit contribution from each contaminant is automatically removed",
"map \\ with rectangular pixelization. :param maps: array containing the observed maps for",
"single map on input, and will default to 2 if there are 2",
"there are 2 maps. :param templates: array containing a set of contaminant templates",
"ly, spin, msk, mps, tmps, beam_use, pure_e, pure_b, tol_pinv, masked_input, int(lite)) else: self.fl",
"ValueError(\"Input maps unavailable for lightweight fields\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in",
"a 1D array. :return: mask \"\"\" return lib.get_mask(self.fl, int(self.fl.npix)) def get_maps(self): \"\"\" Returns",
"tuple, np.ndarray)): if len(beam) <= lmax: raise ValueError(\"Input beam must have at least",
"def get_alms(self): \"\"\" Returns a 2D array ([nmap][nlm]) corresponding to the observed \\",
"don't have the same shape\") mps.append((m.astype(np.float64)).flatten()) mps = np.array(mps) # Flatten templates if",
"== 1) or ((spin == 0) and nmaps != 1)): raise ValueError(\"Spin-zero fields",
"first dimension corresponds to the number of \\ maps, which should be 1",
"\\ shape [ntemp][nmap][nx][ny], where ntemp is the number of \\ templates, nmap should",
"observed \\ harmonic coefficients of this field. :return: 2D array of alms \"\"\"",
"masks and contaminant templates. :param mask: array containing a map corresponding to the",
"contaminants removed. :return: 3D array of flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input",
"of templates, nmap should be 1 for spin-0 fields \\ and 2 otherwise.",
"multiplied by the masks. Note that this is not advisable if you're using",
"for spin-2 fields\") # Flatten mask msk = (mask.astype(np.float64)).flatten() if (not mask_only): #",
"\"\"\" An NmtField object contains all the information describing the fields to correlate,",
"of cosmic \\ shear. It is important to note that NaMaster uses the",
"0 if masked_on_input: masked_input = 1 if (lx < 0) or (ly <",
"wt.flip_th: templates = templates[:, :, ::-1, :] if wt.flip_ph: templates = templates[:, :,",
"ValueError(\"Maps and templates should have the \" \"same number of maps\") for m",
"instrumental beam \\ (assumed to be rotationally symmetric - i.e. no m dependence).",
"<https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\ If `None`, this field will only contain a mask but",
"observed maps \\ for this field. The first dimension corresponds to the number",
"(((spin != 0) and nmaps == 1) or ((spin == 0) and nmaps",
"object if using rectangular pixels (see \\ http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter: number of iterations",
"wt.theta_max, spin, mask, maps, templates, beam_use, pure_e, pure_b, n_iter_mask_purify, tol_pinv, n_iter, masked_input, int(lite))",
"are \\ already multiplied by the masks. Note that this is not advisable",
"values, where max_eval is the largest \\ eigenvalue. Only relevant if passing contaminant",
"!= 2): raise ValueError(\"Must supply 1 or 2 maps per field\") if wt.is_healpix",
"0 if there is a single map on input, and will default to",
"maps try: templates = np.array(templates) if wt.flip_th: templates = templates[:, :, ::-1, :]",
"be treated as singular values, where max_eval is the largest \\ eigenvalue. Only",
"the memory taken up by the resulting object. \"\"\" def __init__(self, mask, maps,",
"wt.flip_th: mask = mask[::-1, :] if wt.flip_ph: mask = mask[:, ::-1] mask =",
"flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields. \"",
"wt.d_theta, wt.phi0, wt.theta_max, spin, mask, beam_use, pure_e, pure_b, n_iter_mask_purify) else: if isinstance(templates, (list,",
"\\ polarization, or e1/e2 (gamma1/gamma2 etc.) in the case of cosmic \\ shear.",
"contribution from these contaminants removed. :return: 2D array of maps \"\"\" if self.lite:",
"the largest \\ eigenvalue. Only relevant if passing contaminant templates that \\ are",
"1 or 2 maps per field\") if wt.is_healpix == 0: # Flatten if",
"!= 1) and (nmaps != 2): raise ValueError(\"Must supply 1 or 2 maps",
"\"None\") if mask_only: self.fl = lib.field_alloc_empty_flat(self.nx, self.ny, lx, ly, spin, msk, beam_use, pure_e,",
"beam_use, pure_e, pure_b) else: # Generate field if isinstance(templates, (list, tuple, np.ndarray)): self.fl",
"\\ templates, the maps returned by this function have their best-fit \\ contribution",
"\\ resolution will be used (e.g. 3 * nside - 1 for HEALPix",
"Returns this field's mask as a 2D array ([ny][nx]). :return: 2D mask. \"\"\"",
"= lite def __del__(self): if self.fl is not None: if lib.field_flat_free is not",
"ValueError(\"Purification only implemented for spin-2 fields\") # Flatten if 2D maps if (not",
"with a single map\") if wt.is_healpix and (len(maps[0]) != len(mask)): raise ValueError(\"All maps",
"itemp in range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp_flat( self.fl,",
"beam[0] should contain \\ the values of l for which de beam is",
"if isinstance(beam, (list, tuple, np.ndarray)): if len(beam) <= lmax: raise ValueError(\"Input beam must",
"wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, beam_use, pure_e,",
"2 otherwise. \\ If `None`, this field will only contain a mask but",
"2D array (2,nl) defining the FT of the instrumental beam \\ (assumed to",
"= mask[::-1, :] if wt.flip_ph: mask = mask[:, ::-1] mask = mask.reshape(wt.npix) if",
"1) and (nmaps != 2): raise ValueError(\"Must supply 1 or 2 maps per",
"negative or zero, the maximum multipole given the map \\ resolution will be",
"least 2-dimensional. The first dimension corresponds to the number \\ of maps, which",
"unavailable for lightweight fields\") alms = [] for imap in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap,",
"maps: 2 2D arrays (nmaps,nx,ny) containing the observed maps \\ for this field.",
"will only contain a mask but no maps. The field \\ can then",
"initializing this field. :return: 3D array of maps \"\"\" if self.lite: raise ValueError(\"Input",
"which de beam is defined, with beam[1] \\ containing the beam values. If",
"HEALPix maps). :param masked_on_input: set to `True` if input maps and templates are",
"is None: if nmaps == 1: spin = 0 else: spin = 2",
"lib.get_map(self.fl, imap, int(self.fl.npix)) else: mps = maps return mps def get_alms(self): \"\"\" Returns",
"to be highly correlated. :param masked_on_input: set to `True` if input maps and",
"\\ treated as singular values, where max_eval is the largest eigenvalue. \\ Only",
"mps = maps.reshape([self.fl.nmaps, self.ny, self.nx]) return mps def get_templates(self): \"\"\" Returns a 4D",
"for this field. Should be \\ at least 2-dimensional. The first dimension corresponds",
"= 0 if masked_on_input: masked_input = 1 wt = NmtWCSTranslator(wcs, mask.shape) if wt.is_healpix",
":, ::-1] maps = maps.reshape([len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input maps have",
"number of \\ maps, which should be 1 for a spin-0 field and",
"and 2 otherwise. The other dimensions should be [npix] for \\ HEALPix maps",
"== 1) or ((spin == 0) and len(maps) != 1)): raise ValueError(\"Spin-zero fields",
"set to `True` if input maps and templates are already multiplied by the",
"See more \\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\ If `None`, this field will only",
"\\ containing the beam values. If None, no beam will be corrected \\",
"masked_on_input: set to `True` if input maps and templates are \\ already multiplied",
"def __init__(self, lx, ly, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, tol_pinv=1E-10, masked_on_input=False,",
"self.fl = lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx, ly, spin, msk, mps, beam_use, pure_e, pure_b, masked_input,",
"for imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp_flat( self.fl, itemp, imap, int(self.fl.npix)",
"or \\ [ny,nx] for maps with rectangular pixels. For a spin>0 field, the",
"with the x-coordinate \\ growing with increasing colatitude theta). It is however more",
"(IndexError, ValueError): raise ValueError(\"Input templates have the wrong shape\") if len(templates[0][0]) != len(mask):",
"= None pure_e = 0 if purify_e: pure_e = 1 pure_b = 0",
"def get_templates(self): \"\"\" Returns a 3D array ([ntemp][nmap][npix]) corresponding to the \\ contaminant",
"eigenvalues below tol_pinv * max_eval will \\ be treated as singular values, where",
"t in templates: tmp = [] if len(t) != nmaps: raise ValueError(\"Maps and",
"as a 1D array. :return: mask \"\"\" return lib.get_mask(self.fl, int(self.fl.npix)) def get_maps(self): \"\"\"",
"fields\") alms = [] for imap in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms))) alms =",
"else: if templates is not None: raise ValueError(\"Input templates can only be an",
"for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map(self.fl, imap, int(self.fl.npix)) else: mps =",
"n_iter, masked_input, int(lite)) self.lite = lite def __del__(self): if self.fl is not None:",
"masked_input = 0 if masked_on_input: masked_input = 1 wt = NmtWCSTranslator(wcs, mask.shape) if",
"pymaster.utils import NmtWCSTranslator class NmtField(object): \"\"\" An NmtField object contains all the information",
"\\ from the maps unless templates=None. :param beam: spherical harmonic transform of the",
"from pymaster import nmtlib as lib import numpy as np from pymaster.utils import",
"unavailable for lightweight fields\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp):",
"size of the patch in the x and y directions (in \\ radians)",
"class NmtField(object): \"\"\" An NmtField object contains all the information describing the fields",
"a HEALPix map or 2-dimensional for a map \\ with rectangular pixelization. :param",
"templates don't have \" \"the same shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps = np.array(tmps) else:",
"in maps: if np.shape(m) != shape_2D: raise ValueError(\"Mask and maps don't have the",
"self.ny, lx, ly, spin, msk, beam_use, pure_e, pure_b) else: # Generate field if",
"of \\ templates, nmap should be 1 for spin-0 fields and 2 for",
"purify_e=False, purify_b=False, tol_pinv=1E-10, masked_on_input=False, lite=False): self.fl = None pure_e = 0 if purify_e:",
":return: mask \"\"\" return lib.get_mask(self.fl, int(self.fl.npix)) def get_maps(self): \"\"\" Returns a 2D array",
"def get_mask(self): \"\"\" Returns this field's mask as a 2D array ([ny][nx]). :return:",
"\\ harmonic coefficients of this field. :return: 2D array of alms \"\"\" if",
"lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, beam_use, pure_e,",
"mask = mask.reshape(wt.npix) if maps is None: mask_only = True if spin is",
"by \\ the maps + 1 (e.g. if a HEALPix map, it should",
"these contaminants removed. :return: 3D array of flat-sky maps \"\"\" if self.lite: raise",
"maps with rectangular pixels. The \\ best-fit contribution from each contaminant is automatically",
"if input maps and templates are \\ already multiplied by the masks. Note",
"[] for t in templates: tmp = [] if len(t) != nmaps: raise",
"= beam else: if beam is None: beam_use = np.array([[-1.], [-1.]]) else: raise",
"None: beam_use = np.ones(lmax+1) else: raise ValueError(\"Input beam can only be an array",
"[ny,nx] for maps with rectangular pixels. The \\ best-fit contribution from each contaminant",
"array containing a map corresponding to the field's mask. \\ Should be 1-dimensional",
"spin. If `None` it will be set to 0 if there is a",
"for \\ this field. This array should have shape [ntemp][nmap]..., where \\ ntemp",
"with deprojection and \\ purification, but you don't care about deprojection bias. This",
"nmap should be 1 for spin-0 fields and 2 for spin-2 \\ fields,",
"have at least %d elements \" \"given the input map resolution\" % (lmax))",
":] if wt.flip_ph: templates = templates[:, :, :, ::-1] templates = templates.reshape([ntemp, len(maps),",
"True else: mask_only = False nmaps = len(maps) if (nmaps != 1) and",
"this function have their best-fit \\ contribution from these contaminants removed. :return: 3D",
"nmaps: raise ValueError(\"Maps and templates should have the \" \"same number of maps\")",
"the observed \\ maps for this field. If the field was initialized with",
"if mask_only: self.fl = lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max,",
"else: raise ValueError(\"Input beam can only be an array or None\\n\") if mask_only:",
"this array should \\ have at least as many elements as the maximum",
"the IAU convention \\ (i.e. x grows with declination). In this case, the",
"growing with increasing colatitude theta). It is however more common \\ for galaxy",
"should have shape [ntemp][nmap]..., where \\ ntemp is the number of templates, nmap",
"templates passed when initializing this field. :return: 4D array of flat-sky maps \"\"\"",
"\"the same shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps = np.array(tmps) else: if templates is not",
"the observed maps for this field. Should be \\ at least 2-dimensional. The",
"be the usual Q/U Stokes parameters for \\ polarization, or e1/e2 (gamma1/gamma2 etc.)",
"shape [ntemp][nmap][nx][ny], where ntemp is the number of \\ templates, nmap should be",
"corresponding to multipoles from 0 to 3*nside-1). :param purify_e: use pure E-modes? :param",
"if input maps and templates are already multiplied by the masks. Note that",
"be 1 for spin-0 fields \\ and 2 otherwise. The other dimensions should",
"None, no beam will be corrected for. Otherwise, this array should \\ have",
"used to compute a mode-coupling matrix, for instance, \\ but not actual power",
"to create an \\ NmtField. See more \\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\ If",
"is not None: if lib.field_free is not None: lib.field_free(self.fl) self.fl = None def",
"map corresponding \\ to the field's mask. :param maps: 2 2D arrays (nmaps,nx,ny)",
"the number of templates, nmap should be 1 for spin-0 fields \\ and",
"\\ the maps + 1 (e.g. if a HEALPix map, it should contain",
"for this field. If the field was initialized with contaminant \\ templates, the",
"array (nx,ny) containing a HEALPix map corresponding \\ to the field's mask. :param",
"initialized with contaminant \\ templates, the maps returned by this function have their",
"resolution\" % (lmax)) beam_use = beam else: if beam is None: beam_use =",
"declination). In this case, the sign of the \\ e2/gamma2 map should be",
"self.fl = lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask,",
"= lib.get_map_flat(self.fl, imap, int(self.fl.npix)) mps = maps.reshape([self.fl.nmaps, self.ny, self.nx]) return mps def get_templates(self):",
"mask_only = True if spin is None: raise ValueError(\"Please supply field spin\") lite",
"in range(self.fl.nmaps): maps[imap, :] = lib.get_map(self.fl, imap, int(self.fl.npix)) else: mps = maps return",
"\"flat-sky field\") # Flatten arrays and check dimensions shape_2D = np.shape(mask) self.ny =",
"(list, tuple, np.ndarray)): self.fl = lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0,",
"0 if masked_on_input: masked_input = 1 wt = NmtWCSTranslator(wcs, mask.shape) if wt.is_healpix ==",
"= lib.get_temp_flat( self.fl, itemp, imap, int(self.fl.npix) ) tmps = temp.reshape([self.fl.ntemp, self.fl.nmaps, self.ny, self.nx])",
"(list, tuple, np.ndarray)): ntemp = len(templates) if (len(templates[0]) != 1) and (len(templates[0]) !=",
"the map \\ resolution will be used (e.g. 3 * nside - 1",
"elements as the maximum multipole sampled by \\ the maps + 1 (e.g.",
"None\\n\") if lmax_sht > 0: lmax = lmax_sht else: lmax = wt.get_lmax() if",
"* max_eval will be \\ treated as singular values, where max_eval is the",
"to compute a mode-coupling matrix, for instance, \\ but not actual power spectra.",
"an array \" \"or None\") # Form beam if isinstance(beam, (list, tuple, np.ndarray)):",
"highly correlated. :param wcs: a WCS object if using rectangular pixels (see \\",
"in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp_flat( self.fl, itemp, imap, int(self.fl.npix) ) tmps",
"from pymaster.utils import NmtWCSTranslator class NmtField(object): \"\"\" An NmtField object contains all the",
"lib.field_alloc_new_notemp( wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps,",
"2D array ([nmap][nlm]) corresponding to the observed \\ harmonic coefficients of this field.",
"Flatten templates if isinstance(templates, (list, tuple, np.ndarray)): tmps = [] for t in",
"and (len(maps) != 2): raise ValueError(\"Must supply 1 or 2 maps per field\")",
"fields are \" \"associated with a single map\") if wt.is_healpix and (len(maps[0]) !=",
"pure_e = 1 pure_b = 0 if purify_b: pure_b = 1 masked_input =",
"::-1] maps = maps.reshape([len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input maps have the",
"are 2 maps. :param templates: array of maps (ntemp,nmaps,nx,ny) containing a set \\",
"should be [npix] for \\ HEALPix maps or [ny,nx] for maps with rectangular",
"= [] for imap in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms))) alms = np.array(alms).reshape([self.fl.nmaps, self.fl.nalms,",
"Flatten maps mps = [] for m in maps: if np.shape(m) != shape_2D:",
"The field \\ can then be used to compute a mode-coupling matrix, for",
"1j * alms[:, :, 1] return alms def get_templates(self): \"\"\" Returns a 3D",
"only implemented for spin-2 fields\") # Flatten mask msk = (mask.astype(np.float64)).flatten() if (not",
"imap, :] = lib.get_temp_flat( self.fl, itemp, imap, int(self.fl.npix) ) tmps = temp.reshape([self.fl.ntemp, self.fl.nmaps,",
"mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, tol_pinv=1E-10, masked_on_input=False, lite=False): self.fl = None",
"The best-fit contribution \\ from each contaminant is automatically removed from the maps",
"contribution from these contaminants removed. :return: 3D array of flat-sky maps \"\"\" if",
"beam values. If None, no beam will be corrected \\ for. :param purify_e:",
"shape\") if isinstance(templates, (list, tuple, np.ndarray)): ntemp = len(templates) if (len(templates[0]) != 1)",
"use pure E-modes? :param purify_b: use pure B-modes? :param tol_pinv: when computing the",
"if you want to only store the bare minimum \\ necessary to run",
"maps = maps[:, :, ::-1] maps = maps.reshape([len(maps), wt.npix]) except (IndexError, ValueError): raise",
"and check dimensions shape_2D = np.shape(mask) self.ny = shape_2D[0] self.nx = shape_2D[1] if",
"for this field. This array should have \\ shape [ntemp][nmap][nx][ny], where ntemp is",
":param masked_on_input: set to `True` if input maps and templates are \\ already",
"dimension corresponds to the number of \\ maps, which should be 1 for",
"map\") if wt.is_healpix and (len(maps[0]) != len(mask)): raise ValueError(\"All maps must have the",
"map resolution\" % (lmax)) beam_use = beam else: if beam is None: beam_use",
"a spin-0 field and 2 otherwise. \\ If `None`, this field will only",
"lx, ly, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, tol_pinv=1E-10, masked_on_input=False, lite=False): self.fl",
"spin != 2: raise ValueError(\"Purification only implemented for spin-2 fields\") # Flatten if",
"supply 1 or 2 maps per field\") if spin is None: if len(maps)",
":param mask: array containing a map corresponding to the field's mask. \\ Should",
"\\ HEALPix maps or [ny,nx] for maps with rectangular pixels. The \\ best-fit",
"values, where max_eval is the largest eigenvalue. \\ Only relevant if passing contaminant",
"if (len(templates[0]) != 1) and (len(templates[0]) != 2): raise ValueError(\"Must supply 1 or",
"the number \\ of maps, which should be 1 for a spin-0 field",
"mask_only = False nmaps = len(maps) if (nmaps != 1) and (nmaps !=",
"maximum multipole sampled by \\ the maps + 1 (e.g. if a HEALPix",
"import NmtWCSTranslator class NmtField(object): \"\"\" An NmtField object contains all the information describing",
"wt.theta_max, spin, mask, maps, beam_use, pure_e, pure_b, n_iter_mask_purify, n_iter, masked_input, int(lite)) self.lite =",
"ValueError(\"Must supply 1 or 2 maps per field\") if wt.is_healpix == 0: #",
"pure_e, pure_b, masked_input, int(lite)) self.lite = lite def __del__(self): if self.fl is not",
"per field\") if spin is None: if nmaps == 1: spin = 0",
"spherical harmonic transform of the instrumental beam \\ (assumed to be rotationally symmetric",
"2 else: if (((spin != 0) and len(maps) == 1) or ((spin ==",
"\\ best-fit contribution from each contaminant is automatically removed \\ from the maps",
"this field. The first dimension corresponds to the number of \\ maps, which",
"best-fit \\ contribution from these contaminants removed. :return: 2D array of maps \"\"\"",
"beam is None: beam_use = np.array([[-1.], [-1.]]) else: raise ValueError(\"Input beam can only",
"contaminant templates for \\ this field. This array should have shape [ntemp][nmap]..., where",
"rectangular pixels. The \\ best-fit contribution from each contaminant is automatically removed \\",
"spin-0 field and 2 otherwise. \\ The other dimensions should be [npix] for",
"None: if lib.field_free is not None: lib.field_free(self.fl) self.fl = None def get_mask(self): \"\"\"",
"only be an array or None\\n\") if mask_only: self.fl = lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht,",
"lib.field_flat_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns this field's mask as a",
"0): try: maps = np.array(maps) if wt.flip_th: maps = maps[:, ::-1, :] if",
"these contaminants removed. :return: 2D array of maps \"\"\" if self.lite: raise ValueError(\"Input",
"= templates[:, :, ::-1, :] if wt.flip_ph: templates = templates[:, :, :, ::-1]",
"\"\"\" Returns a 4D array ([ntemp][nmap][ny][nx]) corresponding to the \\ contaminant templates passed",
"set of contaminant templates for \\ this field. This array should have shape",
"of maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\") temp",
"= False if (len(maps) != 1) and (len(maps) != 2): raise ValueError(\"Must supply",
"3*nside \\ elements, corresponding to multipoles from 0 to 3*nside-1). :param purify_e: use",
"fields, and nx,ny define the patch. The best-fit contribution \\ from each contaminant",
"will default to 2 if there are 2 maps. :param templates: array containing",
"more \\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\ If `None`, this field will only contain",
"map power spectra will be \\ computed. If negative or zero, the maximum",
"t: if np.shape(m) != shape_2D: raise ValueError(\"Mask and templates don't have \" \"the",
"and 2 otherwise. \\ The other dimensions should be [npix] for HEALPix maps",
"\\ and contaminant templates. :param float lx,ly: size of the patch in the",
"maximum multipole up to which map power spectra will be \\ computed. If",
"m dependence). If \\ None, no beam will be corrected for. Otherwise, this",
"etc.) in the case of cosmic \\ shear. It is important to note",
"likely to be highly correlated. :param masked_on_input: set to `True` if input maps",
"and maps don't have the same shape\") mps.append((m.astype(np.float64)).flatten()) mps = np.array(mps) # Flatten",
"the maximum multipole sampled by \\ the maps + 1 (e.g. if a",
"= len(maps) if (nmaps != 1) and (nmaps != 2): raise ValueError(\"Must supply",
"a single map\") if wt.is_healpix and (len(maps[0]) != len(mask)): raise ValueError(\"All maps must",
"for itemp in range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp_flat(",
":] = lib.get_map(self.fl, imap, int(self.fl.npix)) else: mps = maps return mps def get_alms(self):",
"rotationally symmetric - i.e. no m dependence). If \\ None, no beam will",
"tol_pinv=1E-10, wcs=None, n_iter=3, lmax_sht=-1, masked_on_input=False, lite=False): self.fl = None pure_e = 0 if",
"2 maps. :param templates: array of maps (ntemp,nmaps,nx,ny) containing a set \\ of",
"== 0: # Flatten if 2D maps try: templates = np.array(templates) if wt.flip_th:",
"spin>0 field, the two \\ maps to pass should be the usual Q/U",
"if wt.flip_th: mask = mask[::-1, :] if wt.flip_ph: mask = mask[:, ::-1] mask",
"2 maps per field\") if wt.is_healpix == 0: # Flatten if 2D maps",
"this function have their best-fit \\ contribution from these contaminants removed. :return: 2D",
"corresponds to the number \\ of maps, which should be 1 for a",
"imap in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms))) alms = np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2]) alms =",
"if spin is None: if nmaps == 1: spin = 0 else: spin",
"contaminant is automatically removed \\ from the maps unless templates=None. :param beam: spherical",
"beam_use = np.array([[-1.], [-1.]]) else: raise ValueError(\"Input beam can only be an array",
"initializing this field. :return: 4D array of flat-sky maps \"\"\" if self.lite: raise",
":param n_iter: number of iterations when computing a_lms. :param lmax_sht: maximum multipole up",
"for. :param purify_e: use pure E-modes? :param purify_b: use pure B-modes? :param tol_pinv:",
"beam is defined, with beam[1] \\ containing the beam values. If None, no",
"information describing the \\ flat-sky fields to correlate, including their observed maps, masks",
"1 for spin-0 fields and 2 for spin-2 \\ fields, and nx,ny define",
"of maps\") for m in t: if np.shape(m) != shape_2D: raise ValueError(\"Mask and",
"wt.get_lmax() if isinstance(beam, (list, tuple, np.ndarray)): if len(beam) <= lmax: raise ValueError(\"Input beam",
"\"object with `lite=False`.\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp): for",
"when initializing this field. :return: 3D array of maps \"\"\" if self.lite: raise",
"wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, beam_use, pure_e, pure_b, n_iter_mask_purify,",
"many elements as the maximum multipole sampled by \\ the maps + 1",
"the \\ contaminant templates passed when initializing this field. :return: 3D array of",
"is not advisable if you're using purification. :param lite: set to `True` if",
"maps for this field. If the field was initialized with contaminant \\ templates,",
"E-modes? :param purify_b: use pure B-modes? :param tol_pinv: when computing the pseudo-inverse of",
"be an array or \" \"None\") if mask_only: self.fl = lib.field_alloc_empty_flat(self.nx, self.ny, lx,",
"= mask.reshape(wt.npix) if maps is None: mask_only = True if spin is None:",
"!= 0) and nmaps == 1) or ((spin == 0) and nmaps !=",
"= lite def __del__(self): if self.fl is not None: if lib.field_free is not",
"np from pymaster.utils import NmtWCSTranslator class NmtField(object): \"\"\" An NmtField object contains all",
"else: spin = 2 else: if (((spin != 0) and nmaps == 1)",
"raise ValueError(\"Input maps unavailable for lightweight fields. \" \"To use this function, create",
"B-modes? :param tol_pinv: when computing the pseudo-inverse of the contaminant \\ covariance matrix,",
"a 4D array ([ntemp][nmap][ny][nx]) corresponding to the \\ contaminant templates passed when initializing",
"beam_use = np.ones(lmax+1) else: raise ValueError(\"Input beam can only be an array or",
"mask = mask[:, ::-1] mask = mask.reshape(wt.npix) if maps is None: mask_only =",
"the maps returned by this function have their best-fit \\ contribution from these",
"other dimensions should be [npix] for HEALPix maps or \\ [ny,nx] for maps",
"return mps def get_alms(self): \"\"\" Returns a 2D array ([nmap][nlm]) corresponding to the",
"in the x and y directions (in \\ radians) :param mask: 2D array",
"maps or \\ [ny,nx] for maps with rectangular pixels. For a spin>0 field,",
"int(self.fl.npix) ) else: tmps = temp return tmps class NmtFieldFlat(object): \"\"\" An NmtFieldFlat",
"== 0): try: maps = np.array(maps) if wt.flip_th: maps = maps[:, ::-1, :]",
"1 masked_input = 0 if masked_on_input: masked_input = 1 if (lx < 0)",
"\\ templates, nmap should be 1 for spin-0 fields and 2 for spin-2",
"if np.shape(m) != shape_2D: raise ValueError(\"Mask and maps don't have the same shape\")",
"corresponding to the observed \\ maps for this field. If the field was",
"n_iter=3, lmax_sht=-1, masked_on_input=False, lite=False): self.fl = None pure_e = 0 if purify_e: pure_e",
"lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, templates, beam_use, pure_e,",
"be highly correlated. :param masked_on_input: set to `True` if input maps and templates",
"= 1 masked_input = 0 if masked_on_input: masked_input = 1 if (lx <",
"np.array(maps) if wt.flip_th: maps = maps[:, ::-1, :] if wt.flip_ph: maps = maps[:,",
"fields\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map(self.fl,",
"mps = maps return mps def get_alms(self): \"\"\" Returns a 2D array ([nmap][nlm])",
"= lmax_sht else: lmax = wt.get_lmax() if isinstance(beam, (list, tuple, np.ndarray)): if len(beam)",
"used to compute an \\ accurate SHT of the mask when using E/B",
"maps[:, ::-1, :] if wt.flip_ph: maps = maps[:, :, ::-1] maps = maps.reshape([len(maps),",
"!= shape_2D: raise ValueError(\"Mask and maps don't have the same shape\") mps.append((m.astype(np.float64)).flatten()) mps",
"maps return mps def get_alms(self): \"\"\" Returns a 2D array ([nmap][nlm]) corresponding to",
"The other dimensions should be [npix] for HEALPix maps or \\ [ny,nx] for",
"\\ contribution from these contaminants removed. :return: 3D array of flat-sky maps \"\"\"",
"masks. Note that this is not advisable \\ if you're using purification. :param",
"fields\") # Flatten mask msk = (mask.astype(np.float64)).flatten() if (not mask_only): # Flatten maps",
"not None: if lib.field_flat_free is not None: lib.field_flat_free(self.fl) self.fl = None def get_mask(self):",
"None: raise ValueError(\"Input templates can only be an array \" \"or None\\n\") if",
"maps, beam_use, pure_e, pure_b, n_iter_mask_purify, n_iter, masked_input, int(lite)) self.lite = lite def __del__(self):",
"tmps.append(tmp) tmps = np.array(tmps) else: if templates is not None: raise ValueError(\"Input templates",
"usual Q/U Stokes parameters for \\ polarization, or e1/e2 (gamma1/gamma2 etc.) in the",
"implemented for spin-2 fields\") # Flatten if 2D maps if (not mask_only) and",
"maps \\ unless templates=None :param beam: 2D array (2,nl) defining the FT of",
"= shape_2D[1] if maps is None: mask_only = True if spin is None:",
"use this function, create an `NmtFieldFlat` \" \"object with `lite=False`.\") temp = np.zeros([self.fl.ntemp,",
"masked_on_input=False, lite=False): self.fl = None pure_e = 0 if purify_e: pure_e = 1",
"should contain 3*nside \\ elements, corresponding to multipoles from 0 to 3*nside-1). :param",
"have the wrong shape\") if isinstance(templates, (list, tuple, np.ndarray)): ntemp = len(templates) if",
"None def get_mask(self): \"\"\" Returns this field's mask as a 1D array. :return:",
":param beam: spherical harmonic transform of the instrumental beam \\ (assumed to be",
"that this is not advisable if you're using purification. :param lite: set to",
"lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, beam_use, pure_e, pure_b,",
"maps. :param templates: array containing a set of contaminant templates for \\ this",
"mask_only = False if (len(maps) != 1) and (len(maps) != 2): raise ValueError(\"Must",
"correlate, including their observed maps, masks \\ and contaminant templates. :param float lx,ly:",
"(len(maps) != 1) and (len(maps) != 2): raise ValueError(\"Must supply 1 or 2",
"raise ValueError(\"Input beam can only be an array or None\\n\") if mask_only: self.fl",
"\" \"the same shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps = np.array(tmps) else: if templates is",
"have the wrong shape\") if len(templates[0][0]) != len(mask): raise ValueError(\"All maps must have",
"int(self.fl.npix)) def get_maps(self): \"\"\" Returns a 2D array ([nmap][npix]) corresponding to the observed",
"wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input templates have the wrong shape\") if len(templates[0][0])",
"NmtFieldFlat(object): \"\"\" An NmtFieldFlat object contains all the information describing the \\ flat-sky",
"elements \" \"given the input map resolution\" % (lmax)) beam_use = beam else:",
"with `lite=False`.\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp): for imap",
"a WCS object if using rectangular pixels (see \\ http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter: number",
"np.shape(mask) self.ny = shape_2D[0] self.nx = shape_2D[1] if maps is None: mask_only =",
"max_eval is the largest eigenvalue. \\ Only relevant if passing contaminant templates that",
"a 2D array ([nmap][npix]) corresponding to the observed maps \\ for this field.",
"automatically removed from the maps \\ unless templates=None :param beam: 2D array (2,nl)",
"be set to 0 if there is a single map on input, and",
"if templates is not None: raise ValueError(\"Input templates can only be an array",
"self.lite = lite def __del__(self): if self.fl is not None: if lib.field_flat_free is",
"templates are already multiplied by the masks. Note that this is not advisable",
"(mask.astype(np.float64)).flatten() if (not mask_only): # Flatten maps mps = [] for m in",
"that this is not advisable \\ if you're using purification. :param lite: set",
"be 1-dimensional for a HEALPix map or 2-dimensional for a map \\ with",
"using purification. :param lite: set to `True` if you want to only store",
"supply field spin\") lite = True else: mask_only = False nmaps = len(maps)",
"if masked_on_input: masked_input = 1 wt = NmtWCSTranslator(wcs, mask.shape) if wt.is_healpix == 0:",
"field. Should be \\ at least 2-dimensional. The first dimension corresponds to the",
"if lmax_sht > 0: lmax = lmax_sht else: lmax = wt.get_lmax() if isinstance(beam,",
"eigenvalue. \\ Only relevant if passing contaminant templates that are likely to be",
"wt.phi0, wt.theta_max, spin, mask, maps, templates, beam_use, pure_e, pure_b, n_iter_mask_purify, tol_pinv, n_iter, masked_input,",
"for lightweight fields. \" \"To use this function, create an `NmtFieldFlat` \" \"object",
"mask.reshape(wt.npix) if maps is None: mask_only = True if spin is None: raise",
"pure_e, pure_b, n_iter_mask_purify) else: if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new(wt.is_healpix, wt.nside,",
"mps def get_alms(self): \"\"\" Returns a 2D array ([nmap][nlm]) corresponding to the observed",
"mps, tmps, beam_use, pure_e, pure_b, tol_pinv, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp_flat(self.nx, self.ny,",
"the x and y directions (in \\ radians) :param mask: 2D array (nx,ny)",
"= templates.reshape([ntemp, len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input templates have the wrong",
"other dimensions should be [npix] for \\ HEALPix maps or [ny,nx] for maps",
"0 if purify_e: pure_e = 1 pure_b = 0 if purify_b: pure_b =",
"pure_e, pure_b, n_iter_mask_purify, tol_pinv, n_iter, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp( wt.is_healpix, wt.nside,",
"when computing the pseudo-inverse of the contaminant \\ covariance matrix, all eigenvalues below",
"\\ this field. This array should have shape [ntemp][nmap]..., where \\ ntemp is",
"1)): raise ValueError(\"Spin-zero fields are \" \"associated with a single map\") if wt.is_healpix",
"ValueError): raise ValueError(\"Input templates have the wrong shape\") if len(templates[0][0]) != len(mask): raise",
"alms = alms[:, :, 0] + 1j * alms[:, :, 1] return alms",
"least as many elements as the maximum multipole sampled by \\ the maps",
"and 2 otherwise. \\ If `None`, this field will only contain a mask",
"actual power spectra. :param spin: field's spin. If `None` it will be set",
"however more common \\ for galaxy ellipticities to be provided using the IAU",
"raise ValueError(\"Must supply 1 or 2 maps per field\") if spin is None:",
"shape_2D[1] if maps is None: mask_only = True if spin is None: raise",
"0) and nmaps != 1)): raise ValueError(\"Spin-zero fields are \" \"associated with a",
"otherwise. The other dimensions should be [npix] for \\ HEALPix maps or [ny,nx]",
"if a HEALPix map, it should contain 3*nside \\ elements, corresponding to multipoles",
"\" \"object with `lite=False`.\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp):",
"containing the observed maps \\ for this field. The first dimension corresponds to",
"this field. :return: 3D array of maps \"\"\" if self.lite: raise ValueError(\"Input maps",
"= np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp,",
"\"given the input map resolution\" % (lmax)) beam_use = beam else: if beam",
"by the masks. Note that this is not advisable \\ if you're using",
"\\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\ If `None`, this field will only contain a",
"\\ but not actual power spectra. :param spin: field's spin. If `None` it",
"minimum \\ necessary to run a standard pseudo-Cl with deprojection and \\ purification,",
"number of templates, nmap should be 1 for spin-0 fields \\ and 2",
"2 maps. :param templates: array containing a set of contaminant templates for \\",
"you want to only store the bare minimum \\ necessary to run a",
"\\ maps for this field. If the field was initialized with contaminant \\",
"spin: field's spin. If `None` it will be set to 0 if there",
"\\ Only relevant if passing contaminant templates that are likely to be \\",
"array containing a set of contaminant templates for \\ this field. This array",
"an \\ NmtField. See more \\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\ If `None`, this",
"the observed maps \\ for this field. The first dimension corresponds to the",
"1 if (lx < 0) or (ly < 0): raise ValueError(\"Must supply sensible",
"multipoles from 0 to 3*nside-1). :param purify_e: use pure E-modes? :param purify_b: use",
"same \\ polarization convention as HEALPix (i.e. with the x-coordinate \\ growing with",
"\\ at least 2-dimensional. The first dimension corresponds to the number \\ of",
"ly, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, tol_pinv=1E-10, masked_on_input=False, lite=False): self.fl =",
"a set \\ of contaminant templates for this field. This array should have",
"that \\ are likely to be highly correlated. :param masked_on_input: set to `True`",
"only be an array \" \"or None\") # Form beam if isinstance(beam, (list,",
"mask[:, ::-1] mask = mask.reshape(wt.npix) if maps is None: mask_only = True if",
"else: mps = maps return mps def get_alms(self): \"\"\" Returns a 2D array",
"pure_b, tol_pinv, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx, ly, spin, msk,",
"using it to create an \\ NmtField. See more \\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ .",
"the mask when using E/B purification. :param tol_pinv: when computing the pseudo-inverse of",
"self.nx = shape_2D[1] if maps is None: mask_only = True if spin is",
"\\ The other dimensions should be [npix] for HEALPix maps or \\ [ny,nx]",
"len(maps) if (nmaps != 1) and (nmaps != 2): raise ValueError(\"Must supply 1",
"that are likely to be \\ highly correlated. :param wcs: a WCS object",
"for a spin-0 field and 2 otherwise. \\ The other dimensions should be",
"symmetric - i.e. no m dependence). If \\ None, no beam will be",
":] if wt.flip_ph: mask = mask[:, ::-1] mask = mask.reshape(wt.npix) if maps is",
"contain 3*nside \\ elements, corresponding to multipoles from 0 to 3*nside-1). :param purify_e:",
"for itemp in range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp(",
"(list, tuple, np.ndarray)): self.fl = lib.field_alloc_new_flat(self.nx, self.ny, lx, ly, spin, msk, mps, tmps,",
"lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx, ly, spin, msk, mps, beam_use, pure_e, pure_b, masked_input, int(lite)) self.lite",
"not advisable \\ if you're using purification. :param lite: set to `True` if",
"imap, int(self.fl.npix)) mps = maps.reshape([self.fl.nmaps, self.ny, self.nx]) return mps def get_templates(self): \"\"\" Returns",
"if len(t) != nmaps: raise ValueError(\"Maps and templates should have the \" \"same",
"mps = np.array(mps) # Flatten templates if isinstance(templates, (list, tuple, np.ndarray)): tmps =",
"if nmaps == 1: spin = 0 else: spin = 2 else: if",
"if wt.flip_ph: mask = mask[:, ::-1] mask = mask.reshape(wt.npix) if maps is None:",
"wt.flip_ph: maps = maps[:, :, ::-1] maps = maps.reshape([len(maps), wt.npix]) except (IndexError, ValueError):",
"isinstance(beam, (list, tuple, np.ndarray)): beam_use = beam else: if beam is None: beam_use",
"as HEALPix (i.e. with the x-coordinate \\ growing with increasing colatitude theta). It",
"pure_e, pure_b, tol_pinv, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx, ly, spin,",
"__init__(self, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None, n_iter=3, lmax_sht=-1,",
"is None: beam_use = np.array([[-1.], [-1.]]) else: raise ValueError(\"Input beam can only be",
"is a single map on input, and will default to 2 if there",
"for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map_flat(self.fl, imap, int(self.fl.npix)) mps = maps.reshape([self.fl.nmaps,",
"fields to correlate, including their observed maps, masks and contaminant templates. :param mask:",
"raise ValueError(\"Input templates have the wrong shape\") if len(templates[0][0]) != len(mask): raise ValueError(\"All",
"pure B-modes? :param tol_pinv: when computing the pseudo-inverse of the contaminant \\ covariance",
"be 1 for a spin-0 field and 2 otherwise. \\ The other dimensions",
"= np.shape(mask) self.ny = shape_2D[0] self.nx = shape_2D[1] if maps is None: mask_only",
"`True` if input maps and templates are already multiplied by the masks. Note",
"Flatten if 2D maps if (not mask_only) and (wt.is_healpix == 0): try: maps",
"and (len(templates[0]) != 2): raise ValueError(\"Must supply 1 or 2 maps per field\")",
"of flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields.",
"templates if isinstance(templates, (list, tuple, np.ndarray)): tmps = [] for t in templates:",
"lib.field_flat_free is not None: lib.field_flat_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns this",
"increasing colatitude theta). It is however more common \\ for galaxy ellipticities to",
"2D array of alms \"\"\" if self.lite: raise ValueError(\"Alms unavailable for lightweight fields\")",
"Returns a 2D array ([nmap][nlm]) corresponding to the observed \\ harmonic coefficients of",
"maps per field\") if wt.is_healpix == 0: # Flatten if 2D maps try:",
"set to 0 if there is a single map on input, and will",
"[npix] for HEALPix maps or \\ [ny,nx] for maps with rectangular pixels. For",
"\"associated with a single map\") if wt.is_healpix and (len(maps[0]) != len(mask)): raise ValueError(\"All",
"templates, nmap should be 1 for spin-0 fields \\ and 2 otherwise. The",
"<reponame>LSSTDESC/NaMaster from pymaster import nmtlib as lib import numpy as np from pymaster.utils",
"(IndexError, ValueError): raise ValueError(\"Input maps have the wrong shape\") if isinstance(templates, (list, tuple,",
"passing contaminant templates that are likely to be \\ highly correlated. :param wcs:",
"for lightweight fields\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp): for",
"this field. This array should have shape [ntemp][nmap]..., where \\ ntemp is the",
"imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map(self.fl, imap, int(self.fl.npix)) else: mps = maps",
"in range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp_flat( self.fl, itemp,",
"2]) alms = alms[:, :, 0] + 1j * alms[:, :, 1] return",
"This \\ will reduce the memory taken up by the resulting object. \"\"\"",
"range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms))) alms = np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2]) alms = alms[:, :,",
"defining the FT of the instrumental beam \\ (assumed to be rotationally symmetric).",
"# Flatten maps mps = [] for m in maps: if np.shape(m) !=",
"for imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp( self.fl, itemp, imap, int(self.fl.npix)",
"maps per field\") if spin is None: if nmaps == 1: spin =",
"\\ eigenvalue. Only relevant if passing contaminant templates that \\ are likely to",
"1) and (len(templates[0]) != 2): raise ValueError(\"Must supply 1 or 2 maps per",
"field \\ can then be used to compute a mode-coupling matrix, for instance,",
"maximum multipole given the map \\ resolution will be used (e.g. 3 *",
"0) and len(maps) == 1) or ((spin == 0) and len(maps) != 1)):",
"tuple, np.ndarray)): self.fl = lib.field_alloc_new_flat(self.nx, self.ny, lx, ly, spin, msk, mps, tmps, beam_use,",
"\\ for galaxy ellipticities to be provided using the IAU convention \\ (i.e.",
"this function, create an `NmtFieldFlat` \" \"object with `lite=False`.\") maps = np.zeros([self.fl.nmaps, self.fl.npix])",
"self.lite = lite def __del__(self): if self.fl is not None: if lib.field_free is",
"an `NmtFieldFlat` \" \"object with `lite=False`.\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in",
"galaxy ellipticities to be provided using the IAU convention \\ (i.e. x grows",
"pure_e = 0 if purify_e: pure_e = 1 pure_b = 0 if purify_b:",
"1 masked_input = 0 if masked_on_input: masked_input = 1 wt = NmtWCSTranslator(wcs, mask.shape)",
"\\ to the field's mask. :param maps: 2 2D arrays (nmaps,nx,ny) containing the",
"corresponding to the \\ contaminant templates passed when initializing this field. :return: 3D",
"for a HEALPix map or 2-dimensional for a map \\ with rectangular pixelization.",
"`True` if input maps and templates are \\ already multiplied by the masks.",
"`None`, this field will only contain a mask but no maps. The field",
"((spin == 0) and nmaps != 1)): raise ValueError(\"Spin-zero fields are \" \"associated",
"raise ValueError(\"Mask and maps don't have the same shape\") mps.append((m.astype(np.float64)).flatten()) mps = np.array(mps)",
"= None def get_mask(self): \"\"\" Returns this field's mask as a 2D array",
"field if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new_flat(self.nx, self.ny, lx, ly, spin,",
"msk = (mask.astype(np.float64)).flatten() if (not mask_only): # Flatten maps mps = [] for",
"= mask[:, ::-1] mask = mask.reshape(wt.npix) if maps is None: mask_only = True",
"\" \"or None\\n\") if lmax_sht > 0: lmax = lmax_sht else: lmax =",
"Flatten arrays and check dimensions shape_2D = np.shape(mask) self.ny = shape_2D[0] self.nx =",
"important to note that NaMaster uses the same \\ polarization convention as HEALPix",
"def get_maps(self): \"\"\" Returns a 2D array ([nmap][npix]) corresponding to the observed maps",
"only contain a mask but no maps. The field \\ can then be",
"2D maps try: templates = np.array(templates) if wt.flip_th: templates = templates[:, :, ::-1,",
"get_templates(self): \"\"\" Returns a 4D array ([ntemp][nmap][ny][nx]) corresponding to the \\ contaminant templates",
"mps.append((m.astype(np.float64)).flatten()) mps = np.array(mps) # Flatten templates if isinstance(templates, (list, tuple, np.ndarray)): tmps",
"wt.is_healpix == 0: # Flatten if 2D maps try: templates = np.array(templates) if",
"if spin is None: raise ValueError(\"Please supply field spin\") lite = True else:",
"removed from the maps \\ unless templates=None :param beam: 2D array (2,nl) defining",
"masked_input, int(lite)) self.lite = lite def __del__(self): if self.fl is not None: if",
"not None: if lib.field_free is not None: lib.field_free(self.fl) self.fl = None def get_mask(self):",
"mask = mask[::-1, :] if wt.flip_ph: mask = mask[:, ::-1] mask = mask.reshape(wt.npix)",
"below tol_pinv * max_eval will \\ be treated as singular values, where max_eval",
"(list, tuple, np.ndarray)): beam_use = beam else: if beam is None: beam_use =",
"resulting object. \"\"\" def __init__(self, lx, ly, mask, maps, spin=None, templates=None, beam=None, purify_e=False,",
"templates for this field. This array should have \\ shape [ntemp][nmap][nx][ny], where ntemp",
"max_eval will \\ be treated as singular values, where max_eval is the largest",
"Note that this is not advisable \\ if you're using purification. :param lite:",
"computed. If negative or zero, the maximum multipole given the map \\ resolution",
"\\ fields, and nx,ny define the patch. The best-fit contribution \\ from each",
"beam_use, pure_e, pure_b, masked_input, int(lite)) self.lite = lite def __del__(self): if self.fl is",
"Flatten mask msk = (mask.astype(np.float64)).flatten() if (not mask_only): # Flatten maps mps =",
"(ly < 0): raise ValueError(\"Must supply sensible dimensions for \" \"flat-sky field\") #",
"len(maps) != 1)): raise ValueError(\"Spin-zero fields are \" \"associated with a single map\")",
"array. :return: mask \"\"\" return lib.get_mask(self.fl, int(self.fl.npix)) def get_maps(self): \"\"\" Returns a 2D",
"same resolution\") if (pure_e or pure_b) and spin != 2: raise ValueError(\"Purification only",
"raise ValueError(\"All maps must have the same resolution\") if (pure_e or pure_b) and",
"array ([ny][nx]). :return: 2D mask. \"\"\" msk = lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx]) return msk",
"highly correlated. :param masked_on_input: set to `True` if input maps and templates are",
"\\ will reduce the memory taken up by the resulting object. \"\"\" def",
"l for which de beam is defined, with beam[1] \\ containing the beam",
"[] if len(t) != nmaps: raise ValueError(\"Maps and templates should have the \"",
"the same shape\") mps.append((m.astype(np.float64)).flatten()) mps = np.array(mps) # Flatten templates if isinstance(templates, (list,",
"wt.phi0, wt.theta_max, spin, mask, maps, beam_use, pure_e, pure_b, n_iter_mask_purify, n_iter, masked_input, int(lite)) self.lite",
"\"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\") maps = np.zeros([self.fl.nmaps,",
"np.array(templates) if wt.flip_th: templates = templates[:, :, ::-1, :] if wt.flip_ph: templates =",
"all the information describing the fields to correlate, including their observed maps, masks",
"multiplied by the masks. Note that this is not advisable \\ if you're",
"array should have \\ shape [ntemp][nmap][nx][ny], where ntemp is the number of \\",
"= maps return mps def get_alms(self): \"\"\" Returns a 2D array ([nmap][nlm]) corresponding",
"templates: array of maps (ntemp,nmaps,nx,ny) containing a set \\ of contaminant templates for",
"mask when using E/B purification. :param tol_pinv: when computing the pseudo-inverse of the",
"2 otherwise. The other dimensions should be [npix] for \\ HEALPix maps or",
"the instrumental beam \\ (assumed to be rotationally symmetric - i.e. no m",
"= maps.reshape([self.fl.nmaps, self.ny, self.nx]) return mps def get_templates(self): \"\"\" Returns a 4D array",
"is important to note that NaMaster uses the same \\ polarization convention as",
"to be rotationally symmetric - i.e. no m dependence). If \\ None, no",
"pure B-modes? :param n_iter_mask_purify: number of iterations used to compute an \\ accurate",
"be rotationally symmetric - i.e. no m dependence). If \\ None, no beam",
"harmonic coefficients of this field. :return: 2D array of alms \"\"\" if self.lite:",
"taken up by the resulting object. \"\"\" def __init__(self, lx, ly, mask, maps,",
"(i.e. x grows with declination). In this case, the sign of the \\",
"no beam will be corrected for. Otherwise, this array should \\ have at",
"NmtFieldFlat object contains all the information describing the \\ flat-sky fields to correlate,",
"rectangular pixels. For a spin>0 field, the two \\ maps to pass should",
"maps and templates are \\ already multiplied by the masks. Note that this",
"correlated. :param wcs: a WCS object if using rectangular pixels (see \\ http://docs.astropy.org/en/stable/wcs/index.html).",
"n_iter_mask_purify: number of iterations used to compute an \\ accurate SHT of the",
"::-1] templates = templates.reshape([ntemp, len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input templates have",
"maps unless templates=None. :param beam: spherical harmonic transform of the instrumental beam \\",
"[] for m in maps: if np.shape(m) != shape_2D: raise ValueError(\"Mask and maps",
"a standard pseudo-Cl with deprojection and \\ purification, but you don't care about",
"self.fl = None def get_mask(self): \"\"\" Returns this field's mask as a 1D",
"mask \"\"\" return lib.get_mask(self.fl, int(self.fl.npix)) def get_maps(self): \"\"\" Returns a 2D array ([nmap][npix])",
"templates, the maps returned by this function have their best-fit \\ contribution from",
"of this field. :return: 2D array of alms \"\"\" if self.lite: raise ValueError(\"Alms",
"\" \"object with `lite=False`.\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap,",
"(len(templates[0]) != 1) and (len(templates[0]) != 2): raise ValueError(\"Must supply 1 or 2",
"[] for imap in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms))) alms = np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2])",
"templates[:, :, :, ::-1] templates = templates.reshape([ntemp, len(maps), wt.npix]) except (IndexError, ValueError): raise",
"* nside - 1 for HEALPix maps). :param masked_on_input: set to `True` if",
"the maps \\ unless templates=None :param beam: 2D array (2,nl) defining the FT",
"the information describing the fields to correlate, including their observed maps, masks and",
"mps, beam_use, pure_e, pure_b, masked_input, int(lite)) self.lite = lite def __del__(self): if self.fl",
"max_eval is the largest \\ eigenvalue. Only relevant if passing contaminant templates that",
"None: if len(maps) == 1: spin = 0 else: spin = 2 else:",
"masked_on_input: set to `True` if input maps and templates are already multiplied by",
"field will only contain a mask but no maps. The field \\ can",
"field\") if wt.is_healpix == 0: # Flatten if 2D maps try: templates =",
"and nmaps == 1) or ((spin == 0) and nmaps != 1)): raise",
"containing a HEALPix map corresponding \\ to the field's mask. :param maps: 2",
"\\ computed. If negative or zero, the maximum multipole given the map \\",
"will be \\ computed. If negative or zero, the maximum multipole given the",
"contaminant templates. :param float lx,ly: size of the patch in the x and",
"mask[::-1, :] if wt.flip_ph: mask = mask[:, ::-1] mask = mask.reshape(wt.npix) if maps",
"corresponding to the \\ contaminant templates passed when initializing this field. :return: 4D",
"corrected for. Otherwise, this array should \\ have at least as many elements",
"isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new_flat(self.nx, self.ny, lx, ly, spin, msk, mps,",
"None\\n\") if mask_only: self.fl = lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0,",
"their observed maps, masks \\ and contaminant templates. :param float lx,ly: size of",
"\\ of maps, which should be 1 for a spin-0 field and 2",
"beam_use, pure_e, pure_b, tol_pinv, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx, ly,",
"maps.reshape([len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input maps have the wrong shape\") if",
"accurate SHT of the mask when using E/B purification. :param tol_pinv: when computing",
"maps \\ for this field. If the field was initialized with contaminant \\",
"0) and len(maps) != 1)): raise ValueError(\"Spin-zero fields are \" \"associated with a",
"this function, create an `NmtFieldFlat` \" \"object with `lite=False`.\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps,",
"field. If the field was initialized with contaminant \\ templates, the maps returned",
"multipole sampled by \\ the maps + 1 (e.g. if a HEALPix map,",
"sampled by \\ the maps + 1 (e.g. if a HEALPix map, it",
"if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps,",
"input maps and templates are \\ already multiplied by the masks. Note that",
"contaminant \\ covariance matrix, all eigenvalues below tol_pinv * max_eval will be \\",
"ly, spin, msk, beam_use, pure_e, pure_b) else: # Generate field if isinstance(templates, (list,",
"# Generate field if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new_flat(self.nx, self.ny, lx,",
"and nx,ny define the patch. The best-fit contribution \\ from each contaminant is",
"be [npix] for \\ HEALPix maps or [ny,nx] for maps with rectangular pixels.",
"mask msk = (mask.astype(np.float64)).flatten() if (not mask_only): # Flatten maps mps = []",
"templates. :param mask: array containing a map corresponding to the field's mask. \\",
"lmax_sht > 0: lmax = lmax_sht else: lmax = wt.get_lmax() if isinstance(beam, (list,",
"a map \\ with rectangular pixelization. :param maps: array containing the observed maps",
"\\ [ny,nx] for maps with rectangular pixels. For a spin>0 field, the two",
"beam can only be an array or None\\n\") if mask_only: self.fl = lib.field_alloc_empty(wt.is_healpix,",
"# Flatten templates if isinstance(templates, (list, tuple, np.ndarray)): tmps = [] for t",
"covariance matrix, all eigenvalues below tol_pinv * max_eval will be \\ treated as",
"raise ValueError(\"Input templates can only be an array \" \"or None\\n\") if lmax_sht",
"else: lmax = wt.get_lmax() if isinstance(beam, (list, tuple, np.ndarray)): if len(beam) <= lmax:",
"None: mask_only = True if spin is None: raise ValueError(\"Please supply field spin\")",
"x and y directions (in \\ radians) :param mask: 2D array (nx,ny) containing",
"be \\ treated as singular values, where max_eval is the largest eigenvalue. \\",
"msk def get_maps(self): \"\"\" Returns a 3D array ([nmap][ny][nx]) corresponding to the observed",
"but not actual power spectra. :param spin: field's spin. If `None` it will",
"spin=None, templates=None, beam=None, purify_e=False, purify_b=False, tol_pinv=1E-10, masked_on_input=False, lite=False): self.fl = None pure_e =",
"if 2D maps try: templates = np.array(templates) if wt.flip_th: templates = templates[:, :,",
"= 0 if purify_e: pure_e = 1 pure_b = 0 if purify_b: pure_b",
"\" \"None\") if mask_only: self.fl = lib.field_alloc_empty_flat(self.nx, self.ny, lx, ly, spin, msk, beam_use,",
"but you don't care about deprojection bias. This \\ will reduce the memory",
"The first dimension corresponds to the number of \\ maps, which should be",
"masked_input = 0 if masked_on_input: masked_input = 1 if (lx < 0) or",
"number of iterations when computing a_lms. :param lmax_sht: maximum multipole up to which",
"where max_eval is the largest \\ eigenvalue. Only relevant if passing contaminant templates",
"= lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps,",
"None: if nmaps == 1: spin = 0 else: spin = 2 else:",
"raise ValueError(\"Spin-zero fields are \" \"associated with a single map\") if (pure_e or",
"their best-fit \\ contribution from these contaminants removed. :return: 2D array of maps",
"for maps with rectangular pixels. The \\ best-fit contribution from each contaminant is",
"the maximum multipole given the map \\ resolution will be used (e.g. 3",
"for instance, \\ but not actual power spectra. :param spin: field's spin. If",
"singular values, where max_eval is the largest \\ eigenvalue. Only relevant if passing",
"the wrong shape\") if len(templates[0][0]) != len(mask): raise ValueError(\"All maps must have the",
"maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map(self.fl, imap,",
"containing the observed maps for this field. Should be \\ at least 2-dimensional.",
"create an \\ NmtField. See more \\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\ If `None`,",
"\" \"To use this function, create an `NmtFieldFlat` \" \"object with `lite=False`.\") temp",
"(nx,ny) containing a HEALPix map corresponding \\ to the field's mask. :param maps:",
"in t: if np.shape(m) != shape_2D: raise ValueError(\"Mask and templates don't have \"",
"shape_2D[0] self.nx = shape_2D[1] if maps is None: mask_only = True if spin",
"wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, beam_use, pure_e, pure_b, n_iter_mask_purify, n_iter,",
"be used (e.g. 3 * nside - 1 for HEALPix maps). :param masked_on_input:",
"maps. :param templates: array of maps (ntemp,nmaps,nx,ny) containing a set \\ of contaminant",
"the x-coordinate \\ growing with increasing colatitude theta). It is however more common",
"defined, with beam[1] \\ containing the beam values. If None, no beam will",
"E/B purification. :param tol_pinv: when computing the pseudo-inverse of the contaminant \\ covariance",
"templates: tmp = [] if len(t) != nmaps: raise ValueError(\"Maps and templates should",
"ellipticities to be provided using the IAU convention \\ (i.e. x grows with",
"tmps = [] for t in templates: tmp = [] if len(t) !=",
"field. :return: 4D array of flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input maps",
"raise ValueError(\"Input maps have the wrong shape\") if isinstance(templates, (list, tuple, np.ndarray)): ntemp",
"array ([ntemp][nmap][npix]) corresponding to the \\ contaminant templates passed when initializing this field.",
"(len(maps[0]) != len(mask)): raise ValueError(\"All maps must have the same resolution\") if (pure_e",
"beam=None, purify_e=False, purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None, n_iter=3, lmax_sht=-1, masked_on_input=False, lite=False): self.fl = None",
"corresponding \\ to the field's mask. :param maps: 2 2D arrays (nmaps,nx,ny) containing",
"and templates are \\ already multiplied by the masks. Note that this is",
"raise ValueError(\"Input beam must have at least %d elements \" \"given the input",
"you don't care about deprojection bias. This \\ will reduce the memory taken",
"wcs: a WCS object if using rectangular pixels (see \\ http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter:",
"of the mask when using E/B purification. :param tol_pinv: when computing the pseudo-inverse",
"number of maps\") for m in t: if np.shape(m) != shape_2D: raise ValueError(\"Mask",
"beam \\ (assumed to be rotationally symmetric - i.e. no m dependence). If",
"(see \\ http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter: number of iterations when computing a_lms. :param lmax_sht:",
"purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None, n_iter=3, lmax_sht=-1, masked_on_input=False, lite=False): self.fl = None pure_e =",
"to 2 if there are 2 maps. :param templates: array of maps (ntemp,nmaps,nx,ny)",
"pure E-modes? :param purify_b: use pure B-modes? :param tol_pinv: when computing the pseudo-inverse",
"1: spin = 0 else: spin = 2 else: if (((spin != 0)",
"lib.get_temp( self.fl, itemp, imap, int(self.fl.npix) ) else: tmps = temp return tmps class",
"mask. :param maps: 2 2D arrays (nmaps,nx,ny) containing the observed maps \\ for",
"purify_b=False, tol_pinv=1E-10, masked_on_input=False, lite=False): self.fl = None pure_e = 0 if purify_e: pure_e",
"templates[:, :, ::-1, :] if wt.flip_ph: templates = templates[:, :, :, ::-1] templates",
"self.ny, lx, ly, spin, msk, mps, tmps, beam_use, pure_e, pure_b, tol_pinv, masked_input, int(lite))",
"sign of the \\ e2/gamma2 map should be swapped before using it to",
"\\ e2/gamma2 map should be swapped before using it to create an \\",
"from the maps \\ unless templates=None :param beam: 2D array (2,nl) defining the",
"lib.get_temp_flat( self.fl, itemp, imap, int(self.fl.npix) ) tmps = temp.reshape([self.fl.ntemp, self.fl.nmaps, self.ny, self.nx]) return",
"raise ValueError(\"Spin-zero fields are \" \"associated with a single map\") if wt.is_healpix and",
":, 1] return alms def get_templates(self): \"\"\" Returns a 3D array ([ntemp][nmap][npix]) corresponding",
"range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp( self.fl, itemp, imap,",
"mask, beam_use, pure_e, pure_b, n_iter_mask_purify) else: if isinstance(templates, (list, tuple, np.ndarray)): self.fl =",
"\\ are likely to be highly correlated. :param masked_on_input: set to `True` if",
"a single map\") if (pure_e or pure_b) and spin != 2: raise ValueError(\"Purification",
"mps = [] for m in maps: if np.shape(m) != shape_2D: raise ValueError(\"Mask",
"the masks. Note that this is not advisable \\ if you're using purification.",
"imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp_flat( self.fl, itemp, imap, int(self.fl.npix) )",
"the resulting object. \"\"\" def __init__(self, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False,",
"of iterations when computing a_lms. :param lmax_sht: maximum multipole up to which map",
"ValueError(\"Input beam can only be an array or \" \"None\") if mask_only: self.fl",
"range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp_flat( self.fl, itemp, imap,",
"lightweight fields\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] =",
"templates=None, beam=None, purify_e=False, purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None, n_iter=3, lmax_sht=-1, masked_on_input=False, lite=False): self.fl =",
"if you're using purification. :param lite: set to `True` if you want to",
"2): raise ValueError(\"Must supply 1 or 2 maps per field\") if spin is",
"tmps class NmtFieldFlat(object): \"\"\" An NmtFieldFlat object contains all the information describing the",
"maps unavailable for lightweight fields\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in",
"templates. :param float lx,ly: size of the patch in the x and y",
"\\ of contaminant templates for this field. This array should have \\ shape",
"beam_use, pure_e, pure_b, n_iter_mask_purify, n_iter, masked_input, int(lite)) self.lite = lite def __del__(self): if",
"else: if beam is None: beam_use = np.ones(lmax+1) else: raise ValueError(\"Input beam can",
"try: templates = np.array(templates) if wt.flip_th: templates = templates[:, :, ::-1, :] if",
"map\") if (pure_e or pure_b) and spin != 2: raise ValueError(\"Purification only implemented",
"raise ValueError(\"Must supply 1 or 2 maps per field\") if wt.is_healpix == 0:",
"None\") # Form beam if isinstance(beam, (list, tuple, np.ndarray)): beam_use = beam else:",
"self.fl = lib.field_alloc_new_flat(self.nx, self.ny, lx, ly, spin, msk, mps, tmps, beam_use, pure_e, pure_b,",
"templates for \\ this field. This array should have shape [ntemp][nmap]..., where \\",
"from 0 to 3*nside-1). :param purify_e: use pure E-modes? :param purify_b: use pure",
"!= 2): raise ValueError(\"Must supply 1 or 2 maps per field\") if spin",
"= np.array(mps) # Flatten templates if isinstance(templates, (list, tuple, np.ndarray)): tmps = []",
"4D array of flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for",
"\\ Should be 1-dimensional for a HEALPix map or 2-dimensional for a map",
"a HEALPix map, it should contain 3*nside \\ elements, corresponding to multipoles from",
"`here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\ If `None`, this field will only contain a mask",
"1) or ((spin == 0) and len(maps) != 1)): raise ValueError(\"Spin-zero fields are",
"create an `NmtFieldFlat` \" \"object with `lite=False`.\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for",
"maps: array containing the observed maps for this field. Should be \\ at",
"!= 1) and (len(templates[0]) != 2): raise ValueError(\"Must supply 1 or 2 maps",
"\\ http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter: number of iterations when computing a_lms. :param lmax_sht: maximum",
"(ntemp,nmaps,nx,ny) containing a set \\ of contaminant templates for this field. This array",
"likely to be \\ highly correlated. :param wcs: a WCS object if using",
"pure_b, n_iter_mask_purify, tol_pinv, n_iter, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp( wt.is_healpix, wt.nside, lmax_sht,",
"`None` it will be set to 0 if there is a single map",
"maps mps = [] for m in maps: if np.shape(m) != shape_2D: raise",
"function, create an `NmtFieldFlat` \" \"object with `lite=False`.\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix])",
"shape [ntemp][nmap]..., where \\ ntemp is the number of templates, nmap should be",
"raise ValueError(\"Input beam can only be an array or \" \"None\") if mask_only:",
"of the patch in the x and y directions (in \\ radians) :param",
"E-modes? :param purify_b: use pure B-modes? :param n_iter_mask_purify: number of iterations used to",
":return: 2D mask. \"\"\" msk = lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx]) return msk def get_maps(self):",
"= True if spin is None: raise ValueError(\"Please supply field spin\") lite =",
"ValueError(\"Mask and maps don't have the same shape\") mps.append((m.astype(np.float64)).flatten()) mps = np.array(mps) #",
"templates that are likely to be \\ highly correlated. :param wcs: a WCS",
"wcs=None, n_iter=3, lmax_sht=-1, masked_on_input=False, lite=False): self.fl = None pure_e = 0 if purify_e:",
"np.array(mps) # Flatten templates if isinstance(templates, (list, tuple, np.ndarray)): tmps = [] for",
"spin=None, templates=None, beam=None, purify_e=False, purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None, n_iter=3, lmax_sht=-1, masked_on_input=False, lite=False): self.fl",
"IAU convention \\ (i.e. x grows with declination). In this case, the sign",
"but no maps. The field \\ can then be used to compute a",
"will default to 2 if there are 2 maps. :param templates: array of",
"eigenvalue. Only relevant if passing contaminant templates that \\ are likely to be",
"each contaminant is automatically removed \\ from the maps unless templates=None. :param beam:",
"not actual power spectra. :param spin: field's spin. If `None` it will be",
"purify_e: use pure E-modes? :param purify_b: use pure B-modes? :param tol_pinv: when computing",
"should be swapped before using it to create an \\ NmtField. See more",
"len(mask)): raise ValueError(\"All maps must have the same resolution\") if (pure_e or pure_b)",
"len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input templates have the wrong shape\") if",
"np.array([[-1.], [-1.]]) else: raise ValueError(\"Input beam can only be an array or \"",
"lib.field_alloc_empty_flat(self.nx, self.ny, lx, ly, spin, msk, beam_use, pure_e, pure_b) else: # Generate field",
"An NmtField object contains all the information describing the fields to correlate, including",
"\"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\") temp = np.zeros([self.fl.ntemp,",
"with increasing colatitude theta). It is however more common \\ for galaxy ellipticities",
"imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp( self.fl, itemp, imap, int(self.fl.npix) )",
"wt.is_healpix == 0: if wt.flip_th: mask = mask[::-1, :] if wt.flip_ph: mask =",
"instance, \\ but not actual power spectra. :param spin: field's spin. If `None`",
"treated as singular values, where max_eval is the largest eigenvalue. \\ Only relevant",
"If the field was initialized with contaminant \\ templates, the maps returned by",
"for spin-2 \\ fields, and nx,ny define the patch. The best-fit contribution \\",
"pure_b = 1 masked_input = 0 if masked_on_input: masked_input = 1 wt =",
"= 0 if purify_b: pure_b = 1 masked_input = 0 if masked_on_input: masked_input",
"contaminant templates for this field. This array should have \\ shape [ntemp][nmap][nx][ny], where",
"= np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map_flat(self.fl, imap, int(self.fl.npix))",
"= maps.reshape([len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input maps have the wrong shape\")",
"and will default to 2 if there are 2 maps. :param templates: array",
"to the field's mask. :param maps: 2 2D arrays (nmaps,nx,ny) containing the observed",
"if spin is None: if len(maps) == 1: spin = 0 else: spin",
"pixels. The \\ best-fit contribution from each contaminant is automatically removed \\ from",
"msk, mps, beam_use, pure_e, pure_b, masked_input, int(lite)) self.lite = lite def __del__(self): if",
"to 3*nside-1). :param purify_e: use pure E-modes? :param purify_b: use pure B-modes? :param",
"templates are \\ already multiplied by the masks. Note that this is not",
"m in maps: if np.shape(m) != shape_2D: raise ValueError(\"Mask and maps don't have",
"mask_only) and (wt.is_healpix == 0): try: maps = np.array(maps) if wt.flip_th: maps =",
"(in \\ radians) :param mask: 2D array (nx,ny) containing a HEALPix map corresponding",
"be provided using the IAU convention \\ (i.e. x grows with declination). In",
"field\") if spin is None: if nmaps == 1: spin = 0 else:",
"+ 1j * alms[:, :, 1] return alms def get_templates(self): \"\"\" Returns a",
"wrong shape\") if isinstance(templates, (list, tuple, np.ndarray)): ntemp = len(templates) if (len(templates[0]) !=",
"= 1 wt = NmtWCSTranslator(wcs, mask.shape) if wt.is_healpix == 0: if wt.flip_th: mask",
"dimensions shape_2D = np.shape(mask) self.ny = shape_2D[0] self.nx = shape_2D[1] if maps is",
"self.fl = lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask,",
"\\ can then be used to compute a mode-coupling matrix, for instance, \\",
"corresponding to the field's mask. \\ Should be 1-dimensional for a HEALPix map",
"= templates[:, :, :, ::-1] templates = templates.reshape([ntemp, len(maps), wt.npix]) except (IndexError, ValueError):",
"is None: raise ValueError(\"Please supply field spin\") lite = True else: mask_only =",
"removed \\ from the maps unless templates=None. :param beam: spherical harmonic transform of",
"= 1 pure_b = 0 if purify_b: pure_b = 1 masked_input = 0",
"lmax_sht=-1, masked_on_input=False, lite=False): self.fl = None pure_e = 0 if purify_e: pure_e =",
":param maps: array containing the observed maps for this field. Should be \\",
"of alms \"\"\" if self.lite: raise ValueError(\"Alms unavailable for lightweight fields\") alms =",
"Returns a 3D array ([nmap][ny][nx]) corresponding to the observed \\ maps for this",
"lmax = wt.get_lmax() if isinstance(beam, (list, tuple, np.ndarray)): if len(beam) <= lmax: raise",
"will \\ be treated as singular values, where max_eval is the largest \\",
"range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp( self.fl, itemp, imap, int(self.fl.npix) ) else: tmps",
"mask: 2D array (nx,ny) containing a HEALPix map corresponding \\ to the field's",
"passing contaminant templates that \\ are likely to be highly correlated. :param masked_on_input:",
"self.lite: raise ValueError(\"Input maps unavailable for lightweight fields. \" \"To use this function,",
"raise ValueError(\"Maps and templates should have the \" \"same number of maps\") for",
"\" \"associated with a single map\") if (pure_e or pure_b) and spin !=",
"array of maps (ntemp,nmaps,nx,ny) containing a set \\ of contaminant templates for this",
"observed \\ maps for this field. If the field was initialized with contaminant",
"\"\"\" def __init__(self, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None,",
"or ((spin == 0) and len(maps) != 1)): raise ValueError(\"Spin-zero fields are \"",
"(gamma1/gamma2 etc.) in the case of cosmic \\ shear. It is important to",
"number of iterations used to compute an \\ accurate SHT of the mask",
"maps must have the same resolution\") if (pure_e or pure_b) and spin !=",
"raise ValueError(\"Mask and templates don't have \" \"the same shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps",
"pixelization. :param maps: array containing the observed maps for this field. Should be",
"spectra will be \\ computed. If negative or zero, the maximum multipole given",
"HEALPix map, it should contain 3*nside \\ elements, corresponding to multipoles from 0",
"no m dependence). If \\ None, no beam will be corrected for. Otherwise,",
"purification, but you don't care about deprojection bias. This \\ will reduce the",
"that NaMaster uses the same \\ polarization convention as HEALPix (i.e. with the",
"dimensions should be [npix] for HEALPix maps or \\ [ny,nx] for maps with",
"best-fit contribution from each contaminant is automatically removed \\ from the maps unless",
"wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, beam_use, pure_e, pure_b, n_iter_mask_purify) else: if isinstance(templates,",
"int(2*self.fl.nalms))) alms = np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2]) alms = alms[:, :, 0] + 1j",
"imap, int(self.fl.npix) ) else: tmps = temp return tmps class NmtFieldFlat(object): \"\"\" An",
"patch. The best-fit contribution \\ from each contaminant is automatically removed from the",
"msk, mps, tmps, beam_use, pure_e, pure_b, tol_pinv, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp_flat(self.nx,",
"purify_e: use pure E-modes? :param purify_b: use pure B-modes? :param n_iter_mask_purify: number of",
"provided using the IAU convention \\ (i.e. x grows with declination). In this",
"field and 2 otherwise. \\ The other dimensions should be [npix] for HEALPix",
"wt.flip_ph: mask = mask[:, ::-1] mask = mask.reshape(wt.npix) if maps is None: mask_only",
"of l for which de beam is defined, with beam[1] \\ containing the",
"# Flatten arrays and check dimensions shape_2D = np.shape(mask) self.ny = shape_2D[0] self.nx",
"ValueError(\"Alms unavailable for lightweight fields\") alms = [] for imap in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl,",
"from each contaminant is automatically removed from the maps \\ unless templates=None :param",
"beam else: if beam is None: beam_use = np.ones(lmax+1) else: raise ValueError(\"Input beam",
"the input map resolution\" % (lmax)) beam_use = beam else: if beam is",
"wt.flip_th: maps = maps[:, ::-1, :] if wt.flip_ph: maps = maps[:, :, ::-1]",
"\\ (i.e. x grows with declination). In this case, the sign of the",
"Form beam if isinstance(beam, (list, tuple, np.ndarray)): beam_use = beam else: if beam",
"return alms def get_templates(self): \"\"\" Returns a 3D array ([ntemp][nmap][npix]) corresponding to the",
"observed maps \\ for this field. If the field was initialized with contaminant",
"array ([nmap][nlm]) corresponding to the observed \\ harmonic coefficients of this field. :return:",
"array of alms \"\"\" if self.lite: raise ValueError(\"Alms unavailable for lightweight fields\") alms",
"templates=None :param beam: 2D array (2,nl) defining the FT of the instrumental beam",
"the same \\ polarization convention as HEALPix (i.e. with the x-coordinate \\ growing",
"be an array \" \"or None\\n\") if lmax_sht > 0: lmax = lmax_sht",
"fields to correlate, including their observed maps, masks \\ and contaminant templates. :param",
"pure_b) else: # Generate field if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new_flat(self.nx,",
"\"object with `lite=False`.\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :]",
"\\ growing with increasing colatitude theta). It is however more common \\ for",
"maps, masks \\ and contaminant templates. :param float lx,ly: size of the patch",
"maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\") temp =",
"wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, templates, beam_use, pure_e, pure_b, n_iter_mask_purify,",
"arrays (nmaps,nx,ny) containing the observed maps \\ for this field. The first dimension",
"using E/B purification. :param tol_pinv: when computing the pseudo-inverse of the contaminant \\",
"self.fl = None def get_mask(self): \"\"\" Returns this field's mask as a 2D",
"lx,ly: size of the patch in the x and y directions (in \\",
"wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, templates, beam_use, pure_e, pure_b, n_iter_mask_purify, tol_pinv, n_iter,",
"n_iter_mask_purify, tol_pinv, n_iter, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp( wt.is_healpix, wt.nside, lmax_sht, wt.nx,",
"imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map_flat(self.fl, imap, int(self.fl.npix)) mps = maps.reshape([self.fl.nmaps, self.ny,",
":] = lib.get_map_flat(self.fl, imap, int(self.fl.npix)) mps = maps.reshape([self.fl.nmaps, self.ny, self.nx]) return mps def",
"array containing the observed maps for this field. Should be \\ at least",
"templates = np.array(templates) if wt.flip_th: templates = templates[:, :, ::-1, :] if wt.flip_ph:",
"are already multiplied by the masks. Note that this is not advisable if",
"self.fl = lib.field_alloc_empty_flat(self.nx, self.ny, lx, ly, spin, msk, beam_use, pure_e, pure_b) else: #",
"the maps unless templates=None. :param beam: spherical harmonic transform of the instrumental beam",
"must have the same resolution\") if (pure_e or pure_b) and spin != 2:",
"use pure E-modes? :param purify_b: use pure B-modes? :param n_iter_mask_purify: number of iterations",
"if len(beam) <= lmax: raise ValueError(\"Input beam must have at least %d elements",
"with rectangular pixelization. :param maps: array containing the observed maps for this field.",
"2 if there are 2 maps. :param templates: array of maps (ntemp,nmaps,nx,ny) containing",
"!= 2: raise ValueError(\"Purification only implemented for spin-2 fields\") # Flatten mask msk",
"be rotationally symmetric). beam[0] should contain \\ the values of l for which",
"field's mask as a 1D array. :return: mask \"\"\" return lib.get_mask(self.fl, int(self.fl.npix)) def",
"be used to compute a mode-coupling matrix, for instance, \\ but not actual",
":, 0] + 1j * alms[:, :, 1] return alms def get_templates(self): \"\"\"",
"passed when initializing this field. :return: 4D array of flat-sky maps \"\"\" if",
"None: raise ValueError(\"Input templates can only be an array \" \"or None\") #",
"or e1/e2 (gamma1/gamma2 etc.) in the case of cosmic \\ shear. It is",
"(list, tuple, np.ndarray)): if len(beam) <= lmax: raise ValueError(\"Input beam must have at",
"= np.ones(lmax+1) else: raise ValueError(\"Input beam can only be an array or None\\n\")",
"= np.array([[-1.], [-1.]]) else: raise ValueError(\"Input beam can only be an array or",
"field. :return: 3D array of maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable",
"purification. :param tol_pinv: when computing the pseudo-inverse of the contaminant \\ covariance matrix,",
"\"\"\" Returns this field's mask as a 2D array ([ny][nx]). :return: 2D mask.",
"is None: if len(maps) == 1: spin = 0 else: spin = 2",
"containing a map corresponding to the field's mask. \\ Should be 1-dimensional for",
"= np.array(maps) if wt.flip_th: maps = maps[:, ::-1, :] if wt.flip_ph: maps =",
"1D array. :return: mask \"\"\" return lib.get_mask(self.fl, int(self.fl.npix)) def get_maps(self): \"\"\" Returns a",
"templates=None. :param beam: spherical harmonic transform of the instrumental beam \\ (assumed to",
"should be the usual Q/U Stokes parameters for \\ polarization, or e1/e2 (gamma1/gamma2",
"spin is None: raise ValueError(\"Please supply field spin\") lite = True else: mask_only",
"observed maps, masks \\ and contaminant templates. :param float lx,ly: size of the",
"polarization convention as HEALPix (i.e. with the x-coordinate \\ growing with increasing colatitude",
"the same resolution\") else: if templates is not None: raise ValueError(\"Input templates can",
"= 0 else: spin = 2 else: if (((spin != 0) and nmaps",
"if isinstance(beam, (list, tuple, np.ndarray)): beam_use = beam else: if beam is None:",
"computing the pseudo-inverse of the contaminant \\ covariance matrix, all eigenvalues below tol_pinv",
"ValueError(\"Input maps have the wrong shape\") if isinstance(templates, (list, tuple, np.ndarray)): ntemp =",
"1 or 2 maps per field\") if spin is None: if len(maps) ==",
"are \" \"associated with a single map\") if (pure_e or pure_b) and spin",
"transform of the instrumental beam \\ (assumed to be rotationally symmetric - i.e.",
":return: 4D array of flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable",
"0 else: spin = 2 else: if (((spin != 0) and nmaps ==",
"3*nside-1). :param purify_e: use pure E-modes? :param purify_b: use pure B-modes? :param n_iter_mask_purify:",
"is None: mask_only = True if spin is None: raise ValueError(\"Please supply field",
"resolution\") if (pure_e or pure_b) and spin != 2: raise ValueError(\"Purification only implemented",
"0 else: spin = 2 else: if (((spin != 0) and len(maps) ==",
"ValueError(\"Purification only implemented for spin-2 fields\") # Flatten mask msk = (mask.astype(np.float64)).flatten() if",
"(nmaps != 1) and (nmaps != 2): raise ValueError(\"Must supply 1 or 2",
"self.fl is not None: if lib.field_free is not None: lib.field_free(self.fl) self.fl = None",
"templates=None, beam=None, purify_e=False, purify_b=False, tol_pinv=1E-10, masked_on_input=False, lite=False): self.fl = None pure_e = 0",
"when computing a_lms. :param lmax_sht: maximum multipole up to which map power spectra",
"2D array (nx,ny) containing a HEALPix map corresponding \\ to the field's mask.",
"or zero, the maximum multipole given the map \\ resolution will be used",
"([nmap][nlm]) corresponding to the observed \\ harmonic coefficients of this field. :return: 2D",
":] if wt.flip_ph: maps = maps[:, :, ::-1] maps = maps.reshape([len(maps), wt.npix]) except",
"wt.is_healpix and (len(maps[0]) != len(mask)): raise ValueError(\"All maps must have the same resolution\")",
"HEALPix map corresponding \\ to the field's mask. :param maps: 2 2D arrays",
"contaminant is automatically removed from the maps \\ unless templates=None :param beam: 2D",
"contaminants removed. :return: 2D array of maps \"\"\" if self.lite: raise ValueError(\"Input maps",
"\"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields. \" \"To use",
"WCS object if using rectangular pixels (see \\ http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter: number of",
"= 0 if masked_on_input: masked_input = 1 if (lx < 0) or (ly",
"(assumed to be rotationally symmetric). beam[0] should contain \\ the values of l",
"\\ unless templates=None :param beam: 2D array (2,nl) defining the FT of the",
"to be provided using the IAU convention \\ (i.e. x grows with declination).",
"2D array ([nmap][npix]) corresponding to the observed maps \\ for this field. If",
"per field\") if spin is None: if len(maps) == 1: spin = 0",
"\\ the values of l for which de beam is defined, with beam[1]",
"get_templates(self): \"\"\" Returns a 3D array ([ntemp][nmap][npix]) corresponding to the \\ contaminant templates",
"spin\") lite = True else: mask_only = False if (len(maps) != 1) and",
"or pure_b) and spin != 2: raise ValueError(\"Purification only implemented for spin-2 fields\")",
"np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map(self.fl, imap, int(self.fl.npix)) else:",
"maps, which should be 1 for a spin-0 field and 2 otherwise. \\",
"np.ndarray)): beam_use = beam else: if beam is None: beam_use = np.array([[-1.], [-1.]])",
"the number of \\ maps, which should be 1 for a spin-0 field",
"corresponding to the observed \\ harmonic coefficients of this field. :return: 2D array",
"if beam is None: beam_use = np.ones(lmax+1) else: raise ValueError(\"Input beam can only",
"= lib.get_map(self.fl, imap, int(self.fl.npix)) else: mps = maps return mps def get_alms(self): \"\"\"",
"The \\ best-fit contribution from each contaminant is automatically removed \\ from the",
"if wt.flip_ph: templates = templates[:, :, :, ::-1] templates = templates.reshape([ntemp, len(maps), wt.npix])",
"masked_on_input: masked_input = 1 if (lx < 0) or (ly < 0): raise",
"ValueError(\"Must supply 1 or 2 maps per field\") if spin is None: if",
"of contaminant templates for this field. This array should have \\ shape [ntemp][nmap][nx][ny],",
"NmtWCSTranslator class NmtField(object): \"\"\" An NmtField object contains all the information describing the",
"directions (in \\ radians) :param mask: 2D array (nx,ny) containing a HEALPix map",
"the pseudo-inverse of the contaminant \\ covariance matrix, all eigenvalues below tol_pinv *",
":param purify_b: use pure B-modes? :param n_iter_mask_purify: number of iterations used to compute",
"as lib import numpy as np from pymaster.utils import NmtWCSTranslator class NmtField(object): \"\"\"",
"Note that this is not advisable if you're using purification. :param lite: set",
"if masked_on_input: masked_input = 1 if (lx < 0) or (ly < 0):",
"maps.reshape([self.fl.nmaps, self.ny, self.nx]) return mps def get_templates(self): \"\"\" Returns a 4D array ([ntemp][nmap][ny][nx])",
"wt = NmtWCSTranslator(wcs, mask.shape) if wt.is_healpix == 0: if wt.flip_th: mask = mask[::-1,",
"ValueError(\"Input maps unavailable for lightweight fields\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp",
"self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map(self.fl, imap, int(self.fl.npix)) else: mps",
"x grows with declination). In this case, the sign of the \\ e2/gamma2",
"array should \\ have at least as many elements as the maximum multipole",
"tol_pinv, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx, ly, spin, msk, mps,",
"(i.e. with the x-coordinate \\ growing with increasing colatitude theta). It is however",
"maps must have the same resolution\") else: if templates is not None: raise",
"where \\ ntemp is the number of templates, nmap should be 1 for",
"common \\ for galaxy ellipticities to be provided using the IAU convention \\",
"\\ (assumed to be rotationally symmetric). beam[0] should contain \\ the values of",
"= lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx]) return msk def get_maps(self): \"\"\" Returns a 3D array",
"wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, beam_use, pure_e, pure_b, n_iter_mask_purify) else: if",
"if purify_e: pure_e = 1 pure_b = 0 if purify_b: pure_b = 1",
"\\ have at least as many elements as the maximum multipole sampled by",
"if maps is None: mask_only = True if spin is None: raise ValueError(\"Please",
"NmtWCSTranslator(wcs, mask.shape) if wt.is_healpix == 0: if wt.flip_th: mask = mask[::-1, :] if",
"- 1 for HEALPix maps). :param masked_on_input: set to `True` if input maps",
"treated as singular values, where max_eval is the largest \\ eigenvalue. Only relevant",
"field's spin. If `None` it will be set to 0 if there is",
"function have their best-fit \\ contribution from these contaminants removed. :return: 3D array",
"len(t) != nmaps: raise ValueError(\"Maps and templates should have the \" \"same number",
"contribution \\ from each contaminant is automatically removed from the maps \\ unless",
"if there is a single map on input, and will default to 2",
"in range(self.fl.nmaps): maps[imap, :] = lib.get_map_flat(self.fl, imap, int(self.fl.npix)) mps = maps.reshape([self.fl.nmaps, self.ny, self.nx])",
"to be \\ highly correlated. :param wcs: a WCS object if using rectangular",
"([nmap][npix]) corresponding to the observed maps \\ for this field. If the field",
"shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps = np.array(tmps) else: if templates is not None: raise",
"True if spin is None: raise ValueError(\"Please supply field spin\") lite = True",
"== 0: if wt.flip_th: mask = mask[::-1, :] if wt.flip_ph: mask = mask[:,",
"spin is None: if len(maps) == 1: spin = 0 else: spin =",
"temp[itemp, imap, :] = lib.get_temp_flat( self.fl, itemp, imap, int(self.fl.npix) ) tmps = temp.reshape([self.fl.ntemp,",
"corresponding to the observed maps \\ for this field. If the field was",
"[ny,nx] for maps with rectangular pixels. For a spin>0 field, the two \\",
"removed. :return: 3D array of flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input maps",
"and (wt.is_healpix == 0): try: maps = np.array(maps) if wt.flip_th: maps = maps[:,",
"[ntemp][nmap][nx][ny], where ntemp is the number of \\ templates, nmap should be 1",
"!= 1)): raise ValueError(\"Spin-zero fields are \" \"associated with a single map\") if",
"containing a set \\ of contaminant templates for this field. This array should",
"temp return tmps class NmtFieldFlat(object): \"\"\" An NmtFieldFlat object contains all the information",
"contribution from each contaminant is automatically removed \\ from the maps unless templates=None.",
"0] + 1j * alms[:, :, 1] return alms def get_templates(self): \"\"\" Returns",
"be corrected \\ for. :param purify_e: use pure E-modes? :param purify_b: use pure",
"Returns a 3D array ([ntemp][nmap][npix]) corresponding to the \\ contaminant templates passed when",
"::-1, :] if wt.flip_ph: templates = templates[:, :, :, ::-1] templates = templates.reshape([ntemp,",
"their observed maps, masks and contaminant templates. :param mask: array containing a map",
"NaMaster uses the same \\ polarization convention as HEALPix (i.e. with the x-coordinate",
"at least as many elements as the maximum multipole sampled by \\ the",
"is the largest eigenvalue. \\ Only relevant if passing contaminant templates that are",
"the contaminant \\ covariance matrix, all eigenvalues below tol_pinv * max_eval will be",
"\"\"\" Returns a 2D array ([nmap][npix]) corresponding to the observed maps \\ for",
"pseudo-Cl with deprojection and \\ purification, but you don't care about deprojection bias.",
"contain \\ the values of l for which de beam is defined, with",
"nmtlib as lib import numpy as np from pymaster.utils import NmtWCSTranslator class NmtField(object):",
"\\ for this field. If the field was initialized with contaminant \\ templates,",
"and templates should have the \" \"same number of maps\") for m in",
"= NmtWCSTranslator(wcs, mask.shape) if wt.is_healpix == 0: if wt.flip_th: mask = mask[::-1, :]",
"2 2D arrays (nmaps,nx,ny) containing the observed maps \\ for this field. The",
"instrumental beam \\ (assumed to be rotationally symmetric). beam[0] should contain \\ the",
"ValueError(\"All maps must have the same resolution\") else: if templates is not None:",
"get_alms(self): \"\"\" Returns a 2D array ([nmap][nlm]) corresponding to the observed \\ harmonic",
"It is important to note that NaMaster uses the same \\ polarization convention",
"to compute an \\ accurate SHT of the mask when using E/B purification.",
"ValueError(\"Input templates can only be an array \" \"or None\") # Form beam",
"field's mask. \\ Should be 1-dimensional for a HEALPix map or 2-dimensional for",
"for a map \\ with rectangular pixelization. :param maps: array containing the observed",
"all eigenvalues below tol_pinv * max_eval will \\ be treated as singular values,",
"of the instrumental beam \\ (assumed to be rotationally symmetric - i.e. no",
"2: raise ValueError(\"Purification only implemented for spin-2 fields\") # Flatten mask msk =",
"can only be an array or None\\n\") if mask_only: self.fl = lib.field_alloc_empty(wt.is_healpix, wt.nside,",
"if np.shape(m) != shape_2D: raise ValueError(\"Mask and templates don't have \" \"the same",
"else: self.fl = lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx, ly, spin, msk, mps, beam_use, pure_e, pure_b,",
"For a spin>0 field, the two \\ maps to pass should be the",
"raise ValueError(\"Input maps unavailable for lightweight fields\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap",
"x-coordinate \\ growing with increasing colatitude theta). It is however more common \\",
"contaminant templates passed when initializing this field. :return: 4D array of flat-sky maps",
"define the patch. The best-fit contribution \\ from each contaminant is automatically removed",
"polarization, or e1/e2 (gamma1/gamma2 etc.) in the case of cosmic \\ shear. It",
"mask, maps, beam_use, pure_e, pure_b, n_iter_mask_purify, n_iter, masked_input, int(lite)) self.lite = lite def",
"1) or ((spin == 0) and nmaps != 1)): raise ValueError(\"Spin-zero fields are",
"each contaminant is automatically removed from the maps \\ unless templates=None :param beam:",
"2 otherwise. \\ The other dimensions should be [npix] for HEALPix maps or",
"should be [npix] for HEALPix maps or \\ [ny,nx] for maps with rectangular",
"an array or \" \"None\") if mask_only: self.fl = lib.field_alloc_empty_flat(self.nx, self.ny, lx, ly,",
"for which de beam is defined, with beam[1] \\ containing the beam values.",
"= shape_2D[0] self.nx = shape_2D[1] if maps is None: mask_only = True if",
"supply 1 or 2 maps per field\") if wt.is_healpix == 0: # Flatten",
"http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter: number of iterations when computing a_lms. :param lmax_sht: maximum multipole",
"msk, beam_use, pure_e, pure_b) else: # Generate field if isinstance(templates, (list, tuple, np.ndarray)):",
"not None: raise ValueError(\"Input templates can only be an array \" \"or None\\n\")",
"np.shape(m) != shape_2D: raise ValueError(\"Mask and maps don't have the same shape\") mps.append((m.astype(np.float64)).flatten())",
"nmap should be 1 for spin-0 fields \\ and 2 otherwise. The other",
"lib.get_mask(self.fl, int(self.fl.npix)) def get_maps(self): \"\"\" Returns a 2D array ([nmap][npix]) corresponding to the",
"for HEALPix maps). :param masked_on_input: set to `True` if input maps and templates",
"mask_only: self.fl = lib.field_alloc_empty_flat(self.nx, self.ny, lx, ly, spin, msk, beam_use, pure_e, pure_b) else:",
"1 for spin-0 fields \\ and 2 otherwise. The other dimensions should be",
"iterations used to compute an \\ accurate SHT of the mask when using",
"necessary to run a standard pseudo-Cl with deprojection and \\ purification, but you",
"Otherwise, this array should \\ have at least as many elements as the",
"lmax: raise ValueError(\"Input beam must have at least %d elements \" \"given the",
"mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None, n_iter=3, lmax_sht=-1, masked_on_input=False,",
"check dimensions shape_2D = np.shape(mask) self.ny = shape_2D[0] self.nx = shape_2D[1] if maps",
"nmaps != 1)): raise ValueError(\"Spin-zero fields are \" \"associated with a single map\")",
"array or \" \"None\") if mask_only: self.fl = lib.field_alloc_empty_flat(self.nx, self.ny, lx, ly, spin,",
"\"\"\" return lib.get_mask(self.fl, int(self.fl.npix)) def get_maps(self): \"\"\" Returns a 2D array ([nmap][npix]) corresponding",
"to correlate, including their observed maps, masks \\ and contaminant templates. :param float",
"when using E/B purification. :param tol_pinv: when computing the pseudo-inverse of the contaminant",
"# Form beam if isinstance(beam, (list, tuple, np.ndarray)): beam_use = beam else: if",
"not advisable if you're using purification. :param lite: set to `True` if you",
"as a 2D array ([ny][nx]). :return: 2D mask. \"\"\" msk = lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny,",
"as the maximum multipole sampled by \\ the maps + 1 (e.g. if",
"(assumed to be rotationally symmetric - i.e. no m dependence). If \\ None,",
"([ny][nx]). :return: 2D mask. \"\"\" msk = lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx]) return msk def",
"mask: array containing a map corresponding to the field's mask. \\ Should be",
"of the \\ e2/gamma2 map should be swapped before using it to create",
"deprojection and \\ purification, but you don't care about deprojection bias. This \\",
"lightweight fields\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp): for imap",
"If `None` it will be set to 0 if there is a single",
"None pure_e = 0 if purify_e: pure_e = 1 pure_b = 0 if",
"with rectangular pixels. For a spin>0 field, the two \\ maps to pass",
"templates = templates.reshape([ntemp, len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input templates have the",
"(((spin != 0) and len(maps) == 1) or ((spin == 0) and len(maps)",
"maps). :param masked_on_input: set to `True` if input maps and templates are \\",
"1 wt = NmtWCSTranslator(wcs, mask.shape) if wt.is_healpix == 0: if wt.flip_th: mask =",
"np.ndarray)): self.fl = lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin,",
"= 0 else: spin = 2 else: if (((spin != 0) and len(maps)",
"\"\"\" An NmtFieldFlat object contains all the information describing the \\ flat-sky fields",
"an array or None\\n\") if mask_only: self.fl = lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny,",
"all the information describing the \\ flat-sky fields to correlate, including their observed",
"and y directions (in \\ radians) :param mask: 2D array (nx,ny) containing a",
"compute a mode-coupling matrix, for instance, \\ but not actual power spectra. :param",
"templates that \\ are likely to be highly correlated. :param masked_on_input: set to",
"be swapped before using it to create an \\ NmtField. See more \\",
"have the same resolution\") if (pure_e or pure_b) and spin != 2: raise",
"where ntemp is the number of \\ templates, nmap should be 1 for",
"purify_b: use pure B-modes? :param n_iter_mask_purify: number of iterations used to compute an",
"for spin-0 fields and 2 for spin-2 \\ fields, and nx,ny define the",
"array ([nmap][ny][nx]) corresponding to the observed \\ maps for this field. If the",
"to note that NaMaster uses the same \\ polarization convention as HEALPix (i.e.",
"theta). It is however more common \\ for galaxy ellipticities to be provided",
"# Flatten if 2D maps if (not mask_only) and (wt.is_healpix == 0): try:",
"self.fl, itemp, imap, int(self.fl.npix) ) tmps = temp.reshape([self.fl.ntemp, self.fl.nmaps, self.ny, self.nx]) return tmps",
"0) and nmaps == 1) or ((spin == 0) and nmaps != 1)):",
"\\ contribution from these contaminants removed. :return: 2D array of maps \"\"\" if",
"NmtField(object): \"\"\" An NmtField object contains all the information describing the fields to",
"a mode-coupling matrix, for instance, \\ but not actual power spectra. :param spin:",
"care about deprojection bias. This \\ will reduce the memory taken up by",
"int(lite)) self.lite = lite def __del__(self): if self.fl is not None: if lib.field_free",
"ValueError(\"Input beam must have at least %d elements \" \"given the input map",
"the contaminant \\ covariance matrix, all eigenvalues below tol_pinv * max_eval will \\",
":return: 2D array of alms \"\"\" if self.lite: raise ValueError(\"Alms unavailable for lightweight",
"array ([ntemp][nmap][ny][nx]) corresponding to the \\ contaminant templates passed when initializing this field.",
"If None, no beam will be corrected \\ for. :param purify_e: use pure",
"unavailable for lightweight fields\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap,",
"are likely to be \\ highly correlated. :param wcs: a WCS object if",
"power spectra will be \\ computed. If negative or zero, the maximum multipole",
"advisable if you're using purification. :param lite: set to `True` if you want",
"beam if isinstance(beam, (list, tuple, np.ndarray)): beam_use = beam else: if beam is",
"the \\ contaminant templates passed when initializing this field. :return: 4D array of",
"be 1 for a spin-0 field and 2 otherwise. \\ If `None`, this",
"patch in the x and y directions (in \\ radians) :param mask: 2D",
"Returns a 4D array ([ntemp][nmap][ny][nx]) corresponding to the \\ contaminant templates passed when",
"isinstance(templates, (list, tuple, np.ndarray)): ntemp = len(templates) if (len(templates[0]) != 1) and (len(templates[0])",
"temp[itemp, imap, :] = lib.get_temp( self.fl, itemp, imap, int(self.fl.npix) ) else: tmps =",
"with declination). In this case, the sign of the \\ e2/gamma2 map should",
"pure_b = 0 if purify_b: pure_b = 1 masked_input = 0 if masked_on_input:",
"correlate, including their observed maps, masks and contaminant templates. :param mask: array containing",
"self.fl.nalms, 2]) alms = alms[:, :, 0] + 1j * alms[:, :, 1]",
"It is however more common \\ for galaxy ellipticities to be provided using",
"have \\ shape [ntemp][nmap][nx][ny], where ntemp is the number of \\ templates, nmap",
"and (nmaps != 2): raise ValueError(\"Must supply 1 or 2 maps per field\")",
"2-dimensional for a map \\ with rectangular pixelization. :param maps: array containing the",
"< 0): raise ValueError(\"Must supply sensible dimensions for \" \"flat-sky field\") # Flatten",
"1) and (len(maps) != 2): raise ValueError(\"Must supply 1 or 2 maps per",
"lite def __del__(self): if self.fl is not None: if lib.field_flat_free is not None:",
"dimensions for \" \"flat-sky field\") # Flatten arrays and check dimensions shape_2D =",
"map \\ resolution will be used (e.g. 3 * nside - 1 for",
":param masked_on_input: set to `True` if input maps and templates are already multiplied",
"fields\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp): for imap in",
"`lite=False`.\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp): for imap in",
"ValueError(\"Spin-zero fields are \" \"associated with a single map\") if (pure_e or pure_b)",
"is not None: lib.field_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns this field's",
"zero, the maximum multipole given the map \\ resolution will be used (e.g.",
"an array \" \"or None\\n\") if lmax_sht > 0: lmax = lmax_sht else:",
"rectangular pixels (see \\ http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter: number of iterations when computing a_lms.",
"convention \\ (i.e. x grows with declination). In this case, the sign of",
"2): raise ValueError(\"Must supply 1 or 2 maps per field\") if wt.is_healpix ==",
"\\ contaminant templates passed when initializing this field. :return: 3D array of maps",
"(lx < 0) or (ly < 0): raise ValueError(\"Must supply sensible dimensions for",
"if (((spin != 0) and len(maps) == 1) or ((spin == 0) and",
"array \" \"or None\\n\") if lmax_sht > 0: lmax = lmax_sht else: lmax",
"for HEALPix maps or \\ [ny,nx] for maps with rectangular pixels. For a",
"this field will only contain a mask but no maps. The field \\",
"containing a set of contaminant templates for \\ this field. This array should",
"beam can only be an array or \" \"None\") if mask_only: self.fl =",
"lmax = lmax_sht else: lmax = wt.get_lmax() if isinstance(beam, (list, tuple, np.ndarray)): if",
"\"\"\" Returns a 3D array ([ntemp][nmap][npix]) corresponding to the \\ contaminant templates passed",
"self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for",
"maps \\ for this field. The first dimension corresponds to the number of",
"if wt.flip_th: templates = templates[:, :, ::-1, :] if wt.flip_ph: templates = templates[:,",
"to correlate, including their observed maps, masks and contaminant templates. :param mask: array",
"return msk def get_maps(self): \"\"\" Returns a 3D array ([nmap][ny][nx]) corresponding to the",
"lite: set to `True` if you want to only store the bare minimum",
"beam=None, purify_e=False, purify_b=False, tol_pinv=1E-10, masked_on_input=False, lite=False): self.fl = None pure_e = 0 if",
"to the observed maps \\ for this field. If the field was initialized",
"can only be an array or \" \"None\") if mask_only: self.fl = lib.field_alloc_empty_flat(self.nx,",
"mask as a 2D array ([ny][nx]). :return: 2D mask. \"\"\" msk = lib.get_mask_flat(self.fl,",
"maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields. \" \"To",
"reduce the memory taken up by the resulting object. \"\"\" def __init__(self, mask,",
"and templates don't have \" \"the same shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps = np.array(tmps)",
"int(self.fl.npix)) mps = maps.reshape([self.fl.nmaps, self.ny, self.nx]) return mps def get_templates(self): \"\"\" Returns a",
"templates.reshape([ntemp, len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input templates have the wrong shape\")",
"Returns a 2D array ([nmap][npix]) corresponding to the observed maps \\ for this",
"mask. \"\"\" msk = lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx]) return msk def get_maps(self): \"\"\" Returns",
"\\ flat-sky fields to correlate, including their observed maps, masks \\ and contaminant",
"purify_b: pure_b = 1 masked_input = 0 if masked_on_input: masked_input = 1 if",
"multipole up to which map power spectra will be \\ computed. If negative",
"def __del__(self): if self.fl is not None: if lib.field_free is not None: lib.field_free(self.fl)",
"array (2,nl) defining the FT of the instrumental beam \\ (assumed to be",
"to `True` if you want to only store the bare minimum \\ necessary",
"lite = True else: mask_only = False nmaps = len(maps) if (nmaps !=",
"if there are 2 maps. :param templates: array of maps (ntemp,nmaps,nx,ny) containing a",
"should be 1 for spin-0 fields \\ and 2 otherwise. The other dimensions",
"is automatically removed from the maps \\ unless templates=None :param beam: 2D array",
"int(lite)) self.lite = lite def __del__(self): if self.fl is not None: if lib.field_flat_free",
"float lx,ly: size of the patch in the x and y directions (in",
"lmax_sht else: lmax = wt.get_lmax() if isinstance(beam, (list, tuple, np.ndarray)): if len(beam) <=",
"tmps = np.array(tmps) else: if templates is not None: raise ValueError(\"Input templates can",
"about deprojection bias. This \\ will reduce the memory taken up by the",
"def __init__(self, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None, n_iter=3,",
"self.fl.npix]) for itemp in range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap, :] =",
"= np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map(self.fl, imap, int(self.fl.npix))",
"if (nmaps != 1) and (nmaps != 2): raise ValueError(\"Must supply 1 or",
"and len(maps) != 1)): raise ValueError(\"Spin-zero fields are \" \"associated with a single",
"iterations when computing a_lms. :param lmax_sht: maximum multipole up to which map power",
"and contaminant templates. :param float lx,ly: size of the patch in the x",
"case, the sign of the \\ e2/gamma2 map should be swapped before using",
"except (IndexError, ValueError): raise ValueError(\"Input templates have the wrong shape\") if len(templates[0][0]) !=",
"\\ contaminant templates passed when initializing this field. :return: 4D array of flat-sky",
"to pass should be the usual Q/U Stokes parameters for \\ polarization, or",
"is the largest \\ eigenvalue. Only relevant if passing contaminant templates that \\",
"have the same shape\") mps.append((m.astype(np.float64)).flatten()) mps = np.array(mps) # Flatten templates if isinstance(templates,",
"numpy as np from pymaster.utils import NmtWCSTranslator class NmtField(object): \"\"\" An NmtField object",
"supply field spin\") lite = True else: mask_only = False if (len(maps) !=",
"([nmap][ny][nx]) corresponding to the observed \\ maps for this field. If the field",
"(e.g. if a HEALPix map, it should contain 3*nside \\ elements, corresponding to",
"convention as HEALPix (i.e. with the x-coordinate \\ growing with increasing colatitude theta).",
"pure_e, pure_b, n_iter_mask_purify, n_iter, masked_input, int(lite)) self.lite = lite def __del__(self): if self.fl",
"grows with declination). In this case, the sign of the \\ e2/gamma2 map",
"the memory taken up by the resulting object. \"\"\" def __init__(self, lx, ly,",
"map corresponding to the field's mask. \\ Should be 1-dimensional for a HEALPix",
"no beam will be corrected \\ for. :param purify_e: use pure E-modes? :param",
"this field. If the field was initialized with contaminant \\ templates, the maps",
"the sign of the \\ e2/gamma2 map should be swapped before using it",
"\\ be treated as singular values, where max_eval is the largest \\ eigenvalue.",
"object. \"\"\" def __init__(self, lx, ly, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False,",
"for imap in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms))) alms = np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2]) alms",
"of \\ maps, which should be 1 for a spin-0 field and 2",
"maps and templates are already multiplied by the masks. Note that this is",
"maps, templates, beam_use, pure_e, pure_b, n_iter_mask_purify, tol_pinv, n_iter, masked_input, int(lite)) else: self.fl =",
"masked_input = 1 if (lx < 0) or (ly < 0): raise ValueError(\"Must",
"NmtField. See more \\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\ If `None`, this field will",
"= temp return tmps class NmtFieldFlat(object): \"\"\" An NmtFieldFlat object contains all the",
"Only relevant if passing contaminant templates that \\ are likely to be highly",
"alms def get_templates(self): \"\"\" Returns a 3D array ([ntemp][nmap][npix]) corresponding to the \\",
"Stokes parameters for \\ polarization, or e1/e2 (gamma1/gamma2 etc.) in the case of",
"compute an \\ accurate SHT of the mask when using E/B purification. :param",
"using rectangular pixels (see \\ http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter: number of iterations when computing",
"a mask but no maps. The field \\ can then be used to",
"templates can only be an array \" \"or None\") # Form beam if",
"the field was initialized with contaminant \\ templates, the maps returned by this",
"NmtField object contains all the information describing the fields to correlate, including their",
"have at least as many elements as the maximum multipole sampled by \\",
"the patch. The best-fit contribution \\ from each contaminant is automatically removed from",
"\"same number of maps\") for m in t: if np.shape(m) != shape_2D: raise",
"contaminant templates. :param mask: array containing a map corresponding to the field's mask.",
"wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input maps have the wrong shape\") if isinstance(templates,",
"information describing the fields to correlate, including their observed maps, masks and contaminant",
"maps if (not mask_only) and (wt.is_healpix == 0): try: maps = np.array(maps) if",
"max_eval will be \\ treated as singular values, where max_eval is the largest",
"if using rectangular pixels (see \\ http://docs.astropy.org/en/stable/wcs/index.html). :param n_iter: number of iterations when",
"to multipoles from 0 to 3*nside-1). :param purify_e: use pure E-modes? :param purify_b:",
"masked_on_input: masked_input = 1 wt = NmtWCSTranslator(wcs, mask.shape) if wt.is_healpix == 0: if",
"correlated. :param masked_on_input: set to `True` if input maps and templates are already",
"the \" \"same number of maps\") for m in t: if np.shape(m) !=",
"this is not advisable \\ if you're using purification. :param lite: set to",
"ntemp is the number of templates, nmap should be 1 for spin-0 fields",
"wt.flip_ph: templates = templates[:, :, :, ::-1] templates = templates.reshape([ntemp, len(maps), wt.npix]) except",
"if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi,",
"HEALPix maps or \\ [ny,nx] for maps with rectangular pixels. For a spin>0",
"eigenvalues below tol_pinv * max_eval will be \\ treated as singular values, where",
"and \\ purification, but you don't care about deprojection bias. This \\ will",
"len(mask): raise ValueError(\"All maps must have the same resolution\") else: if templates is",
"temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp): for imap in range(self.fl.nmaps):",
"including their observed maps, masks and contaminant templates. :param mask: array containing a",
"raise ValueError(\"All maps must have the same resolution\") else: if templates is not",
"maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\") maps =",
"if 2D maps if (not mask_only) and (wt.is_healpix == 0): try: maps =",
"\\ with rectangular pixelization. :param maps: array containing the observed maps for this",
"array should have shape [ntemp][nmap]..., where \\ ntemp is the number of templates,",
"from each contaminant is automatically removed \\ from the maps unless templates=None. :param",
"resolution will be used (e.g. 3 * nside - 1 for HEALPix maps).",
"array or None\\n\") if mask_only: self.fl = lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi,",
"- i.e. no m dependence). If \\ None, no beam will be corrected",
"where max_eval is the largest eigenvalue. \\ Only relevant if passing contaminant templates",
"n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None, n_iter=3, lmax_sht=-1, masked_on_input=False, lite=False): self.fl = None pure_e = 0",
"largest \\ eigenvalue. Only relevant if passing contaminant templates that \\ are likely",
"and (len(maps[0]) != len(mask)): raise ValueError(\"All maps must have the same resolution\") if",
"(wt.is_healpix == 0): try: maps = np.array(maps) if wt.flip_th: maps = maps[:, ::-1,",
"maps to pass should be the usual Q/U Stokes parameters for \\ polarization,",
"use this function, create an `NmtFieldFlat` \" \"object with `lite=False`.\") maps = np.zeros([self.fl.nmaps,",
"!= nmaps: raise ValueError(\"Maps and templates should have the \" \"same number of",
":, :, ::-1] templates = templates.reshape([ntemp, len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input",
"\\ NmtField. See more \\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_ . \\ If `None`, this field",
"already multiplied by the masks. Note that this is not advisable \\ if",
"\"\"\" if self.lite: raise ValueError(\"Alms unavailable for lightweight fields\") alms = [] for",
"wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, beam_use, pure_e, pure_b,",
"maps\") for m in t: if np.shape(m) != shape_2D: raise ValueError(\"Mask and templates",
"the FT of the instrumental beam \\ (assumed to be rotationally symmetric). beam[0]",
"a map corresponding to the field's mask. \\ Should be 1-dimensional for a",
"= 1 if (lx < 0) or (ly < 0): raise ValueError(\"Must supply",
"else: # Generate field if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new_flat(self.nx, self.ny,",
"from the maps unless templates=None. :param beam: spherical harmonic transform of the instrumental",
"spin, mask, beam_use, pure_e, pure_b, n_iter_mask_purify) else: if isinstance(templates, (list, tuple, np.ndarray)): self.fl",
"`lite=False`.\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map_flat(self.fl,",
"templates, beam_use, pure_e, pure_b, n_iter_mask_purify, tol_pinv, n_iter, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp(",
"supply 1 or 2 maps per field\") if spin is None: if nmaps",
"Generate field if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new_flat(self.nx, self.ny, lx, ly,",
"beam_use, pure_e, pure_b, n_iter_mask_purify) else: if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new(wt.is_healpix,",
"int(lite)) else: self.fl = lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx, ly, spin, msk, mps, beam_use, pure_e,",
"more common \\ for galaxy ellipticities to be provided using the IAU convention",
"beam must have at least %d elements \" \"given the input map resolution\"",
"mask_only): # Flatten maps mps = [] for m in maps: if np.shape(m)",
"\\ covariance matrix, all eigenvalues below tol_pinv * max_eval will \\ be treated",
"2 maps per field\") if spin is None: if len(maps) == 1: spin",
"([ntemp][nmap][ny][nx]) corresponding to the \\ contaminant templates passed when initializing this field. :return:",
"up by the resulting object. \"\"\" def __init__(self, mask, maps, spin=None, templates=None, beam=None,",
"itemp in range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp( self.fl,",
"> 0: lmax = lmax_sht else: lmax = wt.get_lmax() if isinstance(beam, (list, tuple,",
"0 if purify_b: pure_b = 1 masked_input = 0 if masked_on_input: masked_input =",
"\\ highly correlated. :param wcs: a WCS object if using rectangular pixels (see",
"is the number of templates, nmap should be 1 for spin-0 fields \\",
"2 for spin-2 \\ fields, and nx,ny define the patch. The best-fit contribution",
"have the \" \"same number of maps\") for m in t: if np.shape(m)",
"%d elements \" \"given the input map resolution\" % (lmax)) beam_use = beam",
"purify_b: pure_b = 1 masked_input = 0 if masked_on_input: masked_input = 1 wt",
"array ([nmap][npix]) corresponding to the observed maps \\ for this field. If the",
"maps[imap, :] = lib.get_map(self.fl, imap, int(self.fl.npix)) else: mps = maps return mps def",
"imap, :] = lib.get_temp( self.fl, itemp, imap, int(self.fl.npix) ) else: tmps = temp",
"= [] for t in templates: tmp = [] if len(t) != nmaps:",
"the field's mask. \\ Should be 1-dimensional for a HEALPix map or 2-dimensional",
"for lightweight fields\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :]",
"ValueError(\"Input beam can only be an array or None\\n\") if mask_only: self.fl =",
"field, the two \\ maps to pass should be the usual Q/U Stokes",
"templates should have the \" \"same number of maps\") for m in t:",
"beam will be corrected for. Otherwise, this array should \\ have at least",
"!= len(mask)): raise ValueError(\"All maps must have the same resolution\") if (pure_e or",
"parameters for \\ polarization, or e1/e2 (gamma1/gamma2 etc.) in the case of cosmic",
"np.shape(m) != shape_2D: raise ValueError(\"Mask and templates don't have \" \"the same shape\")",
"= True else: mask_only = False if (len(maps) != 1) and (len(maps) !=",
"[ntemp][nmap]..., where \\ ntemp is the number of templates, nmap should be 1",
"= 1 masked_input = 0 if masked_on_input: masked_input = 1 wt = NmtWCSTranslator(wcs,",
"same resolution\") else: if templates is not None: raise ValueError(\"Input templates can only",
"the observed \\ harmonic coefficients of this field. :return: 2D array of alms",
"= False nmaps = len(maps) if (nmaps != 1) and (nmaps != 2):",
"if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields. \" \"To use this",
"self.fl = None pure_e = 0 if purify_e: pure_e = 1 pure_b =",
"for this field. The first dimension corresponds to the number of \\ maps,",
"lib.field_alloc_new_flat(self.nx, self.ny, lx, ly, spin, msk, mps, tmps, beam_use, pure_e, pure_b, tol_pinv, masked_input,",
"(nmaps != 2): raise ValueError(\"Must supply 1 or 2 maps per field\") if",
"3D array ([nmap][ny][nx]) corresponding to the observed \\ maps for this field. If",
"= True else: mask_only = False nmaps = len(maps) if (nmaps != 1)",
"2-dimensional. The first dimension corresponds to the number \\ of maps, which should",
"int(lite)) else: self.fl = lib.field_alloc_new_notemp( wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0,",
"\"or None\") # Form beam if isinstance(beam, (list, tuple, np.ndarray)): beam_use = beam",
"masked_input = 1 wt = NmtWCSTranslator(wcs, mask.shape) if wt.is_healpix == 0: if wt.flip_th:",
"field. The first dimension corresponds to the number of \\ maps, which should",
"if wt.flip_th: maps = maps[:, ::-1, :] if wt.flip_ph: maps = maps[:, :,",
"wt.theta_max, spin, mask, beam_use, pure_e, pure_b, n_iter_mask_purify) else: if isinstance(templates, (list, tuple, np.ndarray)):",
"if isinstance(templates, (list, tuple, np.ndarray)): tmps = [] for t in templates: tmp",
"if self.lite: raise ValueError(\"Alms unavailable for lightweight fields\") alms = [] for imap",
"a spin-0 field and 2 otherwise. \\ The other dimensions should be [npix]",
"matrix, all eigenvalues below tol_pinv * max_eval will \\ be treated as singular",
"shape_2D: raise ValueError(\"Mask and maps don't have the same shape\") mps.append((m.astype(np.float64)).flatten()) mps =",
"a spin>0 field, the two \\ maps to pass should be the usual",
"self.fl is not None: if lib.field_flat_free is not None: lib.field_flat_free(self.fl) self.fl = None",
"have shape [ntemp][nmap]..., where \\ ntemp is the number of templates, nmap should",
"for \\ polarization, or e1/e2 (gamma1/gamma2 etc.) in the case of cosmic \\",
"ValueError(\"Input templates have the wrong shape\") if len(templates[0][0]) != len(mask): raise ValueError(\"All maps",
"(2,nl) defining the FT of the instrumental beam \\ (assumed to be rotationally",
"coefficients of this field. :return: 2D array of alms \"\"\" if self.lite: raise",
"cosmic \\ shear. It is important to note that NaMaster uses the same",
"purify_b: use pure B-modes? :param tol_pinv: when computing the pseudo-inverse of the contaminant",
"!= 1) and (len(maps) != 2): raise ValueError(\"Must supply 1 or 2 maps",
"purify_e=False, purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10, wcs=None, n_iter=3, lmax_sht=-1, masked_on_input=False, lite=False): self.fl = None pure_e",
"0): raise ValueError(\"Must supply sensible dimensions for \" \"flat-sky field\") # Flatten arrays",
"two \\ maps to pass should be the usual Q/U Stokes parameters for",
"there is a single map on input, and will default to 2 if",
"the values of l for which de beam is defined, with beam[1] \\",
"[-1.]]) else: raise ValueError(\"Input beam can only be an array or \" \"None\")",
"\"or None\\n\") if lmax_sht > 0: lmax = lmax_sht else: lmax = wt.get_lmax()",
"\\ covariance matrix, all eigenvalues below tol_pinv * max_eval will be \\ treated",
"mask as a 1D array. :return: mask \"\"\" return lib.get_mask(self.fl, int(self.fl.npix)) def get_maps(self):",
"else: mask_only = False nmaps = len(maps) if (nmaps != 1) and (nmaps",
"shape\") mps.append((m.astype(np.float64)).flatten()) mps = np.array(mps) # Flatten templates if isinstance(templates, (list, tuple, np.ndarray)):",
"\\ for this field. The first dimension corresponds to the number of \\",
"else: raise ValueError(\"Input beam can only be an array or \" \"None\") if",
"only store the bare minimum \\ necessary to run a standard pseudo-Cl with",
"spin-2 \\ fields, and nx,ny define the patch. The best-fit contribution \\ from",
"if passing contaminant templates that \\ are likely to be highly correlated. :param",
"False if (len(maps) != 1) and (len(maps) != 2): raise ValueError(\"Must supply 1",
"tol_pinv * max_eval will \\ be treated as singular values, where max_eval is",
"for t in templates: tmp = [] if len(t) != nmaps: raise ValueError(\"Maps",
"msk = lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx]) return msk def get_maps(self): \"\"\" Returns a 3D",
"if beam is None: beam_use = np.array([[-1.], [-1.]]) else: raise ValueError(\"Input beam can",
"isinstance(beam, (list, tuple, np.ndarray)): if len(beam) <= lmax: raise ValueError(\"Input beam must have",
"np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for itemp in range(self.fl.ntemp): for imap in range(self.fl.nmaps): temp[itemp, imap,",
"the largest eigenvalue. \\ Only relevant if passing contaminant templates that are likely",
"= [] if len(t) != nmaps: raise ValueError(\"Maps and templates should have the",
"a set of contaminant templates for \\ this field. This array should have",
"to which map power spectra will be \\ computed. If negative or zero,",
"if wt.flip_ph: maps = maps[:, :, ::-1] maps = maps.reshape([len(maps), wt.npix]) except (IndexError,",
"below tol_pinv * max_eval will be \\ treated as singular values, where max_eval",
"the maps + 1 (e.g. if a HEALPix map, it should contain 3*nside",
"array of maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\")",
"from these contaminants removed. :return: 2D array of maps \"\"\" if self.lite: raise",
"tmps = temp return tmps class NmtFieldFlat(object): \"\"\" An NmtFieldFlat object contains all",
"memory taken up by the resulting object. \"\"\" def __init__(self, mask, maps, spin=None,",
"corrected \\ for. :param purify_e: use pure E-modes? :param purify_b: use pure B-modes?",
"nmaps == 1: spin = 0 else: spin = 2 else: if (((spin",
"raise ValueError(\"Must supply sensible dimensions for \" \"flat-sky field\") # Flatten arrays and",
"fields. \" \"To use this function, create an `NmtFieldFlat` \" \"object with `lite=False`.\")",
"tol_pinv, n_iter, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp( wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny,",
"or ((spin == 0) and nmaps != 1)): raise ValueError(\"Spin-zero fields are \"",
"have their best-fit \\ contribution from these contaminants removed. :return: 2D array of",
"1 pure_b = 0 if purify_b: pure_b = 1 masked_input = 0 if",
"spin-2 fields\") # Flatten if 2D maps if (not mask_only) and (wt.is_healpix ==",
"else: self.fl = lib.field_alloc_new_notemp( wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max,",
"be 1 for spin-0 fields and 2 for spin-2 \\ fields, and nx,ny",
"= 2 else: if (((spin != 0) and len(maps) == 1) or ((spin",
"will be corrected \\ for. :param purify_e: use pure E-modes? :param purify_b: use",
"then be used to compute a mode-coupling matrix, for instance, \\ but not",
"of the contaminant \\ covariance matrix, all eigenvalues below tol_pinv * max_eval will",
"if (not mask_only) and (wt.is_healpix == 0): try: maps = np.array(maps) if wt.flip_th:",
"best-fit contribution \\ from each contaminant is automatically removed from the maps \\",
"describing the fields to correlate, including their observed maps, masks and contaminant templates.",
"only be an array \" \"or None\\n\") if lmax_sht > 0: lmax =",
"range(self.fl.nmaps): maps[imap, :] = lib.get_map(self.fl, imap, int(self.fl.npix)) else: mps = maps return mps",
"if (lx < 0) or (ly < 0): raise ValueError(\"Must supply sensible dimensions",
"self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix])",
"% (lmax)) beam_use = beam else: if beam is None: beam_use = np.ones(lmax+1)",
"beam[1] \\ containing the beam values. If None, no beam will be corrected",
"nmaps = len(maps) if (nmaps != 1) and (nmaps != 2): raise ValueError(\"Must",
"is not None: if lib.field_flat_free is not None: lib.field_flat_free(self.fl) self.fl = None def",
"a single map on input, and will default to 2 if there are",
"have the same resolution\") else: if templates is not None: raise ValueError(\"Input templates",
"beam_use = beam else: if beam is None: beam_use = np.ones(lmax+1) else: raise",
"be \\ computed. If negative or zero, the maximum multipole given the map",
"beam_use, pure_e, pure_b, n_iter_mask_purify, tol_pinv, n_iter, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp( wt.is_healpix,",
"corresponds to the number of \\ maps, which should be 1 for a",
"ly, spin, msk, mps, beam_use, pure_e, pure_b, masked_input, int(lite)) self.lite = lite def",
"the two \\ maps to pass should be the usual Q/U Stokes parameters",
"fields \\ and 2 otherwise. The other dimensions should be [npix] for \\",
"dependence). If \\ None, no beam will be corrected for. Otherwise, this array",
"(len(templates[0]) != 2): raise ValueError(\"Must supply 1 or 2 maps per field\") if",
"want to only store the bare minimum \\ necessary to run a standard",
"= alms[:, :, 0] + 1j * alms[:, :, 1] return alms def",
"wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, beam_use,",
"if lib.field_flat_free is not None: lib.field_flat_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns",
"default to 2 if there are 2 maps. :param templates: array of maps",
"raise ValueError(\"Please supply field spin\") lite = True else: mask_only = False nmaps",
"should be 1 for spin-0 fields and 2 for spin-2 \\ fields, and",
"!= shape_2D: raise ValueError(\"Mask and templates don't have \" \"the same shape\") tmp.append((m.astype(np.float64)).flatten())",
"relevant if passing contaminant templates that \\ are likely to be highly correlated.",
"None: lib.field_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns this field's mask as",
"the patch in the x and y directions (in \\ radians) :param mask:",
"swapped before using it to create an \\ NmtField. See more \\ `here",
"else: spin = 2 else: if (((spin != 0) and len(maps) == 1)",
"ValueError(\"All maps must have the same resolution\") if (pure_e or pure_b) and spin",
"maps = maps.reshape([len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input maps have the wrong",
"set to `True` if input maps and templates are \\ already multiplied by",
"raise ValueError(\"Please supply field spin\") lite = True else: mask_only = False if",
"lib import numpy as np from pymaster.utils import NmtWCSTranslator class NmtField(object): \"\"\" An",
"the case of cosmic \\ shear. It is important to note that NaMaster",
":param wcs: a WCS object if using rectangular pixels (see \\ http://docs.astropy.org/en/stable/wcs/index.html). :param",
":param templates: array of maps (ntemp,nmaps,nx,ny) containing a set \\ of contaminant templates",
"spin-0 fields \\ and 2 otherwise. The other dimensions should be [npix] for",
"it will be set to 0 if there is a single map on",
"map on input, and will default to 2 if there are 2 maps.",
"if isinstance(templates, (list, tuple, np.ndarray)): ntemp = len(templates) if (len(templates[0]) != 1) and",
"to `True` if input maps and templates are already multiplied by the masks.",
"by the masks. Note that this is not advisable if you're using purification.",
":param beam: 2D array (2,nl) defining the FT of the instrumental beam \\",
"taken up by the resulting object. \"\"\" def __init__(self, mask, maps, spin=None, templates=None,",
"spin, mask, maps, templates, beam_use, pure_e, pure_b, n_iter_mask_purify, tol_pinv, n_iter, masked_input, int(lite)) else:",
"wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, beam_use, pure_e, pure_b, n_iter_mask_purify, n_iter, masked_input, int(lite))",
"int(self.fl.npix)) else: mps = maps return mps def get_alms(self): \"\"\" Returns a 2D",
"of maps, which should be 1 for a spin-0 field and 2 otherwise.",
"is the number of \\ templates, nmap should be 1 for spin-0 fields",
"\\ radians) :param mask: 2D array (nx,ny) containing a HEALPix map corresponding \\",
"\" \"given the input map resolution\" % (lmax)) beam_use = beam else: if",
"field. :return: 2D array of alms \"\"\" if self.lite: raise ValueError(\"Alms unavailable for",
"in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms))) alms = np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2]) alms = alms[:,",
"first dimension corresponds to the number \\ of maps, which should be 1",
"== 0) and nmaps != 1)): raise ValueError(\"Spin-zero fields are \" \"associated with",
"Flatten if 2D maps try: templates = np.array(templates) if wt.flip_th: templates = templates[:,",
"maps or [ny,nx] for maps with rectangular pixels. The \\ best-fit contribution from",
"0: # Flatten if 2D maps try: templates = np.array(templates) if wt.flip_th: templates",
"to 2 if there are 2 maps. :param templates: array containing a set",
"lx, ly, spin, msk, beam_use, pure_e, pure_b) else: # Generate field if isinstance(templates,",
"should contain \\ the values of l for which de beam is defined,",
"set to `True` if you want to only store the bare minimum \\",
"a 2D array ([nmap][nlm]) corresponding to the observed \\ harmonic coefficients of this",
"a 2D array ([ny][nx]). :return: 2D mask. \"\"\" msk = lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx])",
"else: mask_only = False if (len(maps) != 1) and (len(maps) != 2): raise",
"to only store the bare minimum \\ necessary to run a standard pseudo-Cl",
"wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, templates, beam_use, pure_e, pure_b,",
"= (mask.astype(np.float64)).flatten() if (not mask_only): # Flatten maps mps = [] for m",
"wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, templates, beam_use, pure_e, pure_b, n_iter_mask_purify, tol_pinv,",
"to run a standard pseudo-Cl with deprojection and \\ purification, but you don't",
":param lmax_sht: maximum multipole up to which map power spectra will be \\",
"will reduce the memory taken up by the resulting object. \"\"\" def __init__(self,",
"(pure_e or pure_b) and spin != 2: raise ValueError(\"Purification only implemented for spin-2",
"\\ for. :param purify_e: use pure E-modes? :param purify_b: use pure B-modes? :param",
"ValueError(\"Please supply field spin\") lite = True else: mask_only = False nmaps =",
"are 2 maps. :param templates: array containing a set of contaminant templates for",
"pure E-modes? :param purify_b: use pure B-modes? :param n_iter_mask_purify: number of iterations used",
"templates is not None: raise ValueError(\"Input templates can only be an array \"",
"self.nx]) return mps def get_templates(self): \"\"\" Returns a 4D array ([ntemp][nmap][ny][nx]) corresponding to",
"are \" \"associated with a single map\") if wt.is_healpix and (len(maps[0]) != len(mask)):",
"at least %d elements \" \"given the input map resolution\" % (lmax)) beam_use",
"lib.field_free is not None: lib.field_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns this",
"array \" \"or None\") # Form beam if isinstance(beam, (list, tuple, np.ndarray)): beam_use",
"\" \"same number of maps\") for m in t: if np.shape(m) != shape_2D:",
"matrix, all eigenvalues below tol_pinv * max_eval will be \\ treated as singular",
"with `lite=False`.\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] =",
"field\") if spin is None: if len(maps) == 1: spin = 0 else:",
"will be \\ treated as singular values, where max_eval is the largest eigenvalue.",
"spin, msk, mps, beam_use, pure_e, pure_b, masked_input, int(lite)) self.lite = lite def __del__(self):",
":return: 2D array of maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for",
"class NmtFieldFlat(object): \"\"\" An NmtFieldFlat object contains all the information describing the \\",
"import numpy as np from pymaster.utils import NmtWCSTranslator class NmtField(object): \"\"\" An NmtField",
"* alms[:, :, 1] return alms def get_templates(self): \"\"\" Returns a 3D array",
"ValueError(\"Please supply field spin\") lite = True else: mask_only = False if (len(maps)",
"wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, beam_use, pure_e, pure_b, n_iter_mask_purify) else:",
"(list, tuple, np.ndarray)): tmps = [] for t in templates: tmp = []",
"run a standard pseudo-Cl with deprojection and \\ purification, but you don't care",
"or [ny,nx] for maps with rectangular pixels. The \\ best-fit contribution from each",
"wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, templates, beam_use,",
"masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx, ly, spin, msk, mps, beam_use,",
"is not advisable \\ if you're using purification. :param lite: set to `True`",
"::-1, :] if wt.flip_ph: maps = maps[:, :, ::-1] maps = maps.reshape([len(maps), wt.npix])",
"Should be \\ at least 2-dimensional. The first dimension corresponds to the number",
"this is not advisable if you're using purification. :param lite: set to `True`",
"the bare minimum \\ necessary to run a standard pseudo-Cl with deprojection and",
"e2/gamma2 map should be swapped before using it to create an \\ NmtField.",
"unless templates=None :param beam: 2D array (2,nl) defining the FT of the instrumental",
":param float lx,ly: size of the patch in the x and y directions",
"not None: lib.field_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns this field's mask",
":param spin: field's spin. If `None` it will be set to 0 if",
"if there are 2 maps. :param templates: array containing a set of contaminant",
"for a spin-0 field and 2 otherwise. \\ If `None`, this field will",
"contaminant templates that are likely to be \\ highly correlated. :param wcs: a",
"set \\ of contaminant templates for this field. This array should have \\",
"spin is None: if nmaps == 1: spin = 0 else: spin =",
"# Flatten mask msk = (mask.astype(np.float64)).flatten() if (not mask_only): # Flatten maps mps",
"to the \\ contaminant templates passed when initializing this field. :return: 4D array",
"np.ndarray)): tmps = [] for t in templates: tmp = [] if len(t)",
"pure_b = 1 masked_input = 0 if masked_on_input: masked_input = 1 if (lx",
"\\ already multiplied by the masks. Note that this is not advisable \\",
"if self.fl is not None: if lib.field_free is not None: lib.field_free(self.fl) self.fl =",
"object contains all the information describing the fields to correlate, including their observed",
"n_iter: number of iterations when computing a_lms. :param lmax_sht: maximum multipole up to",
"tol_pinv=1E-10, masked_on_input=False, lite=False): self.fl = None pure_e = 0 if purify_e: pure_e =",
"\" \"flat-sky field\") # Flatten arrays and check dimensions shape_2D = np.shape(mask) self.ny",
"bare minimum \\ necessary to run a standard pseudo-Cl with deprojection and \\",
"!= 0) and len(maps) == 1) or ((spin == 0) and len(maps) !=",
"`NmtFieldFlat` \" \"object with `lite=False`.\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps):",
"the information describing the \\ flat-sky fields to correlate, including their observed maps,",
"when initializing this field. :return: 4D array of flat-sky maps \"\"\" if self.lite:",
"\\ purification, but you don't care about deprojection bias. This \\ will reduce",
"is automatically removed \\ from the maps unless templates=None. :param beam: spherical harmonic",
"get_maps(self): \"\"\" Returns a 3D array ([nmap][ny][nx]) corresponding to the observed \\ maps",
"and spin != 2: raise ValueError(\"Purification only implemented for spin-2 fields\") # Flatten",
"::-1] mask = mask.reshape(wt.npix) if maps is None: mask_only = True if spin",
"== 0) and len(maps) != 1)): raise ValueError(\"Spin-zero fields are \" \"associated with",
"if purify_b: pure_b = 1 masked_input = 0 if masked_on_input: masked_input = 1",
"maps + 1 (e.g. if a HEALPix map, it should contain 3*nside \\",
"not None: raise ValueError(\"Input templates can only be an array \" \"or None\")",
"power spectra. :param spin: field's spin. If `None` it will be set to",
"to the number \\ of maps, which should be 1 for a spin-0",
"if (not mask_only): # Flatten maps mps = [] for m in maps:",
"object. \"\"\" def __init__(self, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, n_iter_mask_purify=3, tol_pinv=1E-10,",
"is None: beam_use = np.ones(lmax+1) else: raise ValueError(\"Input beam can only be an",
"Only relevant if passing contaminant templates that are likely to be \\ highly",
"(e.g. 3 * nside - 1 for HEALPix maps). :param masked_on_input: set to",
"3D array ([ntemp][nmap][npix]) corresponding to the \\ contaminant templates passed when initializing this",
"len(templates[0][0]) != len(mask): raise ValueError(\"All maps must have the same resolution\") else: if",
"len(maps) == 1) or ((spin == 0) and len(maps) != 1)): raise ValueError(\"Spin-zero",
"is however more common \\ for galaxy ellipticities to be provided using the",
"of maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight fields\") maps",
"rotationally symmetric). beam[0] should contain \\ the values of l for which de",
"= np.array(templates) if wt.flip_th: templates = templates[:, :, ::-1, :] if wt.flip_ph: templates",
"= lib.field_alloc_empty(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, beam_use,",
"ValueError(\"Input templates can only be an array \" \"or None\\n\") if lmax_sht >",
":param n_iter_mask_purify: number of iterations used to compute an \\ accurate SHT of",
"1)): raise ValueError(\"Spin-zero fields are \" \"associated with a single map\") if (pure_e",
"maps[imap, :] = lib.get_map_flat(self.fl, imap, int(self.fl.npix)) mps = maps.reshape([self.fl.nmaps, self.ny, self.nx]) return mps",
"mask, maps, templates, beam_use, pure_e, pure_b, n_iter_mask_purify, tol_pinv, n_iter, masked_input, int(lite)) else: self.fl",
"= lib.field_alloc_new_notemp( wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask,",
"if wt.is_healpix == 0: # Flatten if 2D maps try: templates = np.array(templates)",
"None: beam_use = np.array([[-1.], [-1.]]) else: raise ValueError(\"Input beam can only be an",
"3D array of flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for",
"None def get_mask(self): \"\"\" Returns this field's mask as a 2D array ([ny][nx]).",
"observed maps, masks and contaminant templates. :param mask: array containing a map corresponding",
"mask.shape) if wt.is_healpix == 0: if wt.flip_th: mask = mask[::-1, :] if wt.flip_ph:",
"reduce the memory taken up by the resulting object. \"\"\" def __init__(self, lx,",
"maps = maps[:, ::-1, :] if wt.flip_ph: maps = maps[:, :, ::-1] maps",
"\\ None, no beam will be corrected for. Otherwise, this array should \\",
"def __del__(self): if self.fl is not None: if lib.field_flat_free is not None: lib.field_flat_free(self.fl)",
"note that NaMaster uses the same \\ polarization convention as HEALPix (i.e. with",
"raise ValueError(\"Purification only implemented for spin-2 fields\") # Flatten mask msk = (mask.astype(np.float64)).flatten()",
"and templates are already multiplied by the masks. Note that this is not",
"imap, int(2*self.fl.nalms))) alms = np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2]) alms = alms[:, :, 0] +",
"mps def get_templates(self): \"\"\" Returns a 4D array ([ntemp][nmap][ny][nx]) corresponding to the \\",
"\\ elements, corresponding to multipoles from 0 to 3*nside-1). :param purify_e: use pure",
"4D array ([ntemp][nmap][ny][nx]) corresponding to the \\ contaminant templates passed when initializing this",
"only implemented for spin-2 fields\") # Flatten if 2D maps if (not mask_only)",
"ValueError(\"Input maps unavailable for lightweight fields. \" \"To use this function, create an",
"to the observed \\ maps for this field. If the field was initialized",
"advisable \\ if you're using purification. :param lite: set to `True` if you",
"lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta, wt.phi0, wt.theta_max, spin, mask, maps, templates,",
"largest eigenvalue. \\ Only relevant if passing contaminant templates that are likely to",
"tuple, np.ndarray)): tmps = [] for t in templates: tmp = [] if",
"passed when initializing this field. :return: 3D array of maps \"\"\" if self.lite:",
"ValueError): raise ValueError(\"Input maps have the wrong shape\") if isinstance(templates, (list, tuple, np.ndarray)):",
"lightweight fields. \" \"To use this function, create an `NmtFieldFlat` \" \"object with",
"dimensions should be [npix] for \\ HEALPix maps or [ny,nx] for maps with",
"spin-0 fields and 2 for spin-2 \\ fields, and nx,ny define the patch.",
"returned by this function have their best-fit \\ contribution from these contaminants removed.",
"by this function have their best-fit \\ contribution from these contaminants removed. :return:",
"field spin\") lite = True else: mask_only = False nmaps = len(maps) if",
"True else: mask_only = False if (len(maps) != 1) and (len(maps) != 2):",
"0) or (ly < 0): raise ValueError(\"Must supply sensible dimensions for \" \"flat-sky",
"In this case, the sign of the \\ e2/gamma2 map should be swapped",
"pymaster import nmtlib as lib import numpy as np from pymaster.utils import NmtWCSTranslator",
") else: tmps = temp return tmps class NmtFieldFlat(object): \"\"\" An NmtFieldFlat object",
"this field. This array should have \\ shape [ntemp][nmap][nx][ny], where ntemp is the",
"maps unavailable for lightweight fields\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps):",
"maps = np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map_flat(self.fl, imap,",
"1 for a spin-0 field and 2 otherwise. \\ The other dimensions should",
"= lib.get_temp( self.fl, itemp, imap, int(self.fl.npix) ) else: tmps = temp return tmps",
"n_iter_mask_purify, n_iter, masked_input, int(lite)) self.lite = lite def __del__(self): if self.fl is not",
"An NmtFieldFlat object contains all the information describing the \\ flat-sky fields to",
"if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new_flat(self.nx, self.ny, lx, ly, spin, msk,",
"used (e.g. 3 * nside - 1 for HEALPix maps). :param masked_on_input: set",
"else: if (((spin != 0) and len(maps) == 1) or ((spin == 0)",
"a_lms. :param lmax_sht: maximum multipole up to which map power spectra will be",
"don't care about deprojection bias. This \\ will reduce the memory taken up",
"= lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx, ly, spin, msk, mps, beam_use, pure_e, pure_b, masked_input, int(lite))",
"self.ny, lx, ly, spin, msk, mps, beam_use, pure_e, pure_b, masked_input, int(lite)) self.lite =",
"can then be used to compute a mode-coupling matrix, for instance, \\ but",
"lite = True else: mask_only = False if (len(maps) != 1) and (len(maps)",
"This array should have shape [ntemp][nmap]..., where \\ ntemp is the number of",
"pure_b, n_iter_mask_purify) else: if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht,",
"otherwise. \\ The other dimensions should be [npix] for HEALPix maps or \\",
"B-modes? :param n_iter_mask_purify: number of iterations used to compute an \\ accurate SHT",
"or 2 maps per field\") if wt.is_healpix == 0: # Flatten if 2D",
"2D mask. \"\"\" msk = lib.get_mask_flat(self.fl, int(self.fl.npix)).reshape([self.ny, self.nx]) return msk def get_maps(self): \"\"\"",
"alms = np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2]) alms = alms[:, :, 0] + 1j *",
"2D arrays (nmaps,nx,ny) containing the observed maps \\ for this field. The first",
"alms[:, :, 0] + 1j * alms[:, :, 1] return alms def get_templates(self):",
"or 2 maps per field\") if spin is None: if len(maps) == 1:",
"pure_b) and spin != 2: raise ValueError(\"Purification only implemented for spin-2 fields\") #",
"maps: if np.shape(m) != shape_2D: raise ValueError(\"Mask and maps don't have the same",
"ValueError(\"Must supply sensible dimensions for \" \"flat-sky field\") # Flatten arrays and check",
"the instrumental beam \\ (assumed to be rotationally symmetric). beam[0] should contain \\",
"pure_b, masked_input, int(lite)) self.lite = lite def __del__(self): if self.fl is not None:",
"in range(self.fl.nmaps): temp[itemp, imap, :] = lib.get_temp( self.fl, itemp, imap, int(self.fl.npix) ) else:",
"if len(maps) == 1: spin = 0 else: spin = 2 else: if",
"contaminant templates passed when initializing this field. :return: 3D array of maps \"\"\"",
"in the case of cosmic \\ shear. It is important to note that",
"imap, int(self.fl.npix)) else: mps = maps return mps def get_alms(self): \"\"\" Returns a",
"\\ accurate SHT of the mask when using E/B purification. :param tol_pinv: when",
"len(beam) <= lmax: raise ValueError(\"Input beam must have at least %d elements \"",
"matrix, for instance, \\ but not actual power spectra. :param spin: field's spin.",
"lx, ly, spin, msk, mps, beam_use, pure_e, pure_b, masked_input, int(lite)) self.lite = lite",
"import nmtlib as lib import numpy as np from pymaster.utils import NmtWCSTranslator class",
"input map resolution\" % (lmax)) beam_use = beam else: if beam is None:",
"should be 1 for a spin-0 field and 2 otherwise. \\ The other",
"the resulting object. \"\"\" def __init__(self, lx, ly, mask, maps, spin=None, templates=None, beam=None,",
"uses the same \\ polarization convention as HEALPix (i.e. with the x-coordinate \\",
"maps per field\") if spin is None: if len(maps) == 1: spin =",
"single map\") if wt.is_healpix and (len(maps[0]) != len(mask)): raise ValueError(\"All maps must have",
"\\ from each contaminant is automatically removed from the maps \\ unless templates=None",
"np.zeros([self.fl.nmaps, self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map_flat(self.fl, imap, int(self.fl.npix)) mps",
"should have \\ shape [ntemp][nmap][nx][ny], where ntemp is the number of \\ templates,",
"be corrected for. Otherwise, this array should \\ have at least as many",
"pure_e, pure_b) else: # Generate field if isinstance(templates, (list, tuple, np.ndarray)): self.fl =",
"tol_pinv: when computing the pseudo-inverse of the contaminant \\ covariance matrix, all eigenvalues",
"with a single map\") if (pure_e or pure_b) and spin != 2: raise",
"of iterations used to compute an \\ accurate SHT of the mask when",
"1 (e.g. if a HEALPix map, it should contain 3*nside \\ elements, corresponding",
"1 for a spin-0 field and 2 otherwise. \\ If `None`, this field",
"itemp, imap, int(self.fl.npix) ) else: tmps = temp return tmps class NmtFieldFlat(object): \"\"\"",
"+ 1 (e.g. if a HEALPix map, it should contain 3*nside \\ elements,",
"shape_2D: raise ValueError(\"Mask and templates don't have \" \"the same shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp)",
"flat-sky fields to correlate, including their observed maps, masks \\ and contaminant templates.",
"HEALPix map or 2-dimensional for a map \\ with rectangular pixelization. :param maps:",
"= np.array(tmps) else: if templates is not None: raise ValueError(\"Input templates can only",
"bias. This \\ will reduce the memory taken up by the resulting object.",
"be an array \" \"or None\") # Form beam if isinstance(beam, (list, tuple,",
"wt.phi0, wt.theta_max, spin, mask, beam_use, pure_e, pure_b, n_iter_mask_purify) else: if isinstance(templates, (list, tuple,",
"self.fl.npix]) for imap in range(self.fl.nmaps): maps[imap, :] = lib.get_map_flat(self.fl, imap, int(self.fl.npix)) mps =",
"contaminant \\ templates, the maps returned by this function have their best-fit \\",
"can only be an array \" \"or None\") # Form beam if isinstance(beam,",
"at least 2-dimensional. The first dimension corresponds to the number \\ of maps,",
"1] return alms def get_templates(self): \"\"\" Returns a 3D array ([ntemp][nmap][npix]) corresponding to",
"before using it to create an \\ NmtField. See more \\ `here <https://healpix.jpl.nasa.gov/html/intronode12.htm>`_",
"self.ny = shape_2D[0] self.nx = shape_2D[1] if maps is None: mask_only = True",
":, ::-1, :] if wt.flip_ph: templates = templates[:, :, :, ::-1] templates =",
"Should be 1-dimensional for a HEALPix map or 2-dimensional for a map \\",
"observed maps for this field. Should be \\ at least 2-dimensional. The first",
"ValueError(\"Spin-zero fields are \" \"associated with a single map\") if wt.is_healpix and (len(maps[0])",
"!= len(mask): raise ValueError(\"All maps must have the same resolution\") else: if templates",
"this case, the sign of the \\ e2/gamma2 map should be swapped before",
"all eigenvalues below tol_pinv * max_eval will be \\ treated as singular values,",
"templates have the wrong shape\") if len(templates[0][0]) != len(mask): raise ValueError(\"All maps must",
"the beam values. If None, no beam will be corrected \\ for. :param",
"spin = 2 else: if (((spin != 0) and len(maps) == 1) or",
"alms \"\"\" if self.lite: raise ValueError(\"Alms unavailable for lightweight fields\") alms = []",
"or (ly < 0): raise ValueError(\"Must supply sensible dimensions for \" \"flat-sky field\")",
"spin-2 fields\") # Flatten mask msk = (mask.astype(np.float64)).flatten() if (not mask_only): # Flatten",
":] = lib.get_temp_flat( self.fl, itemp, imap, int(self.fl.npix) ) tmps = temp.reshape([self.fl.ntemp, self.fl.nmaps, self.ny,",
"None: if lib.field_flat_free is not None: lib.field_flat_free(self.fl) self.fl = None def get_mask(self): \"\"\"",
"tmps, beam_use, pure_e, pure_b, tol_pinv, masked_input, int(lite)) else: self.fl = lib.field_alloc_new_notemp_flat(self.nx, self.ny, lx,",
"contain a mask but no maps. The field \\ can then be used",
"ntemp = len(templates) if (len(templates[0]) != 1) and (len(templates[0]) != 2): raise ValueError(\"Must",
"will be used (e.g. 3 * nside - 1 for HEALPix maps). :param",
"the fields to correlate, including their observed maps, masks and contaminant templates. :param",
"masks. Note that this is not advisable if you're using purification. :param lite:",
"n_iter_mask_purify) else: if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht, wt.nx,",
"containing the beam values. If None, no beam will be corrected \\ for.",
"as singular values, where max_eval is the largest \\ eigenvalue. Only relevant if",
"an \\ accurate SHT of the mask when using E/B purification. :param tol_pinv:",
"this field. :return: 4D array of flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input",
"= maps[:, :, ::-1] maps = maps.reshape([len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input",
"except (IndexError, ValueError): raise ValueError(\"Input maps have the wrong shape\") if isinstance(templates, (list,",
"np.ndarray)): self.fl = lib.field_alloc_new_flat(self.nx, self.ny, lx, ly, spin, msk, mps, tmps, beam_use, pure_e,",
"0: lmax = lmax_sht else: lmax = wt.get_lmax() if isinstance(beam, (list, tuple, np.ndarray)):",
"beam \\ (assumed to be rotationally symmetric). beam[0] should contain \\ the values",
"None: raise ValueError(\"Please supply field spin\") lite = True else: mask_only = False",
"lightweight fields\") alms = [] for imap in range(self.fl.nmaps): alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms))) alms",
"else: if isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny,",
"don't have \" \"the same shape\") tmp.append((m.astype(np.float64)).flatten()) tmps.append(tmp) tmps = np.array(tmps) else: if",
":param mask: 2D array (nx,ny) containing a HEALPix map corresponding \\ to the",
"None: lib.field_flat_free(self.fl) self.fl = None def get_mask(self): \"\"\" Returns this field's mask as",
"= maps[:, ::-1, :] if wt.flip_ph: maps = maps[:, :, ::-1] maps =",
"map or 2-dimensional for a map \\ with rectangular pixelization. :param maps: array",
"or 2-dimensional for a map \\ with rectangular pixelization. :param maps: array containing",
"to `True` if input maps and templates are \\ already multiplied by the",
"resulting object. \"\"\" def __init__(self, mask, maps, spin=None, templates=None, beam=None, purify_e=False, purify_b=False, n_iter_mask_purify=3,",
"nside - 1 for HEALPix maps). :param masked_on_input: set to `True` if input",
"as singular values, where max_eval is the largest eigenvalue. \\ Only relevant if",
"alms.append(lib.get_alms(self.fl, imap, int(2*self.fl.nalms))) alms = np.array(alms).reshape([self.fl.nmaps, self.fl.nalms, 2]) alms = alms[:, :, 0]",
"\\ and 2 otherwise. The other dimensions should be [npix] for \\ HEALPix",
"to the \\ contaminant templates passed when initializing this field. :return: 3D array",
"if (((spin != 0) and nmaps == 1) or ((spin == 0) and",
"\\ maps, which should be 1 for a spin-0 field and 2 otherwise.",
"self.ny, self.nx]) return mps def get_templates(self): \"\"\" Returns a 4D array ([ntemp][nmap][ny][nx]) corresponding",
"len(maps) == 1: spin = 0 else: spin = 2 else: if (((spin",
"up to which map power spectra will be \\ computed. If negative or",
"the field's mask. :param maps: 2 2D arrays (nmaps,nx,ny) containing the observed maps",
"will be set to 0 if there is a single map on input,",
"raise ValueError(\"Input maps unavailable for lightweight fields\") temp = np.zeros([self.fl.ntemp, self.fl.nmaps, self.fl.npix]) for",
"purification. :param lite: set to `True` if you want to only store the",
"computing a_lms. :param lmax_sht: maximum multipole up to which map power spectra will",
"pixels. For a spin>0 field, the two \\ maps to pass should be",
"Q/U Stokes parameters for \\ polarization, or e1/e2 (gamma1/gamma2 etc.) in the case",
"\"\"\" Returns a 2D array ([nmap][nlm]) corresponding to the observed \\ harmonic coefficients",
"for \\ HEALPix maps or [ny,nx] for maps with rectangular pixels. The \\",
"\\ maps to pass should be the usual Q/U Stokes parameters for \\",
"\\ polarization convention as HEALPix (i.e. with the x-coordinate \\ growing with increasing",
"to the field's mask. \\ Should be 1-dimensional for a HEALPix map or",
":param maps: 2 2D arrays (nmaps,nx,ny) containing the observed maps \\ for this",
"maps with rectangular pixels. For a spin>0 field, the two \\ maps to",
"already multiplied by the masks. Note that this is not advisable if you're",
"spin, msk, mps, tmps, beam_use, pure_e, pure_b, tol_pinv, masked_input, int(lite)) else: self.fl =",
"should have the \" \"same number of maps\") for m in t: if",
"beam else: if beam is None: beam_use = np.array([[-1.], [-1.]]) else: raise ValueError(\"Input",
"you're using purification. :param lite: set to `True` if you want to only",
"beam_use = beam else: if beam is None: beam_use = np.array([[-1.], [-1.]]) else:",
"contaminant templates that \\ are likely to be highly correlated. :param masked_on_input: set",
"\" \"associated with a single map\") if wt.is_healpix and (len(maps[0]) != len(mask)): raise",
"array of flat-sky maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight",
"can only be an array \" \"or None\\n\") if lmax_sht > 0: lmax",
"the observed maps \\ for this field. If the field was initialized with",
"covariance matrix, all eigenvalues below tol_pinv * max_eval will \\ be treated as",
":] = lib.get_temp( self.fl, itemp, imap, int(self.fl.npix) ) else: tmps = temp return",
"spin-0 field and 2 otherwise. \\ If `None`, this field will only contain",
"maps have the wrong shape\") if isinstance(templates, (list, tuple, np.ndarray)): ntemp = len(templates)",
"pass should be the usual Q/U Stokes parameters for \\ polarization, or e1/e2",
":, ::-1] templates = templates.reshape([ntemp, len(maps), wt.npix]) except (IndexError, ValueError): raise ValueError(\"Input templates",
"purify_e: pure_e = 1 pure_b = 0 if purify_b: pure_b = 1 masked_input",
"2 else: if (((spin != 0) and nmaps == 1) or ((spin ==",
"sensible dimensions for \" \"flat-sky field\") # Flatten arrays and check dimensions shape_2D",
"function, create an `NmtFieldFlat` \" \"object with `lite=False`.\") maps = np.zeros([self.fl.nmaps, self.fl.npix]) for",
"else: tmps = temp return tmps class NmtFieldFlat(object): \"\"\" An NmtFieldFlat object contains",
"= wt.get_lmax() if isinstance(beam, (list, tuple, np.ndarray)): if len(beam) <= lmax: raise ValueError(\"Input",
"a HEALPix map corresponding \\ to the field's mask. :param maps: 2 2D",
"HEALPix (i.e. with the x-coordinate \\ growing with increasing colatitude theta). It is",
"maps unavailable for lightweight fields. \" \"To use this function, create an `NmtFieldFlat`",
"spin\") lite = True else: mask_only = False nmaps = len(maps) if (nmaps",
"of maps (ntemp,nmaps,nx,ny) containing a set \\ of contaminant templates for this field.",
"only be an array or \" \"None\") if mask_only: self.fl = lib.field_alloc_empty_flat(self.nx, self.ny,",
"least %d elements \" \"given the input map resolution\" % (lmax)) beam_use =",
"rectangular pixelization. :param maps: array containing the observed maps for this field. Should",
"\\ If `None`, this field will only contain a mask but no maps.",
"to 0 if there is a single map on input, and will default",
"lite=False): self.fl = None pure_e = 0 if purify_e: pure_e = 1 pure_b",
"is not None: raise ValueError(\"Input templates can only be an array \" \"or",
"The other dimensions should be [npix] for \\ HEALPix maps or [ny,nx] for",
":param purify_b: use pure B-modes? :param tol_pinv: when computing the pseudo-inverse of the",
"to the number of \\ maps, which should be 1 for a spin-0",
"templates can only be an array \" \"or None\\n\") if lmax_sht > 0:",
"if wt.is_healpix and (len(maps[0]) != len(mask)): raise ValueError(\"All maps must have the same",
"2D array of maps \"\"\" if self.lite: raise ValueError(\"Input maps unavailable for lightweight",
"templates passed when initializing this field. :return: 3D array of maps \"\"\" if",
"return tmps class NmtFieldFlat(object): \"\"\" An NmtFieldFlat object contains all the information describing",
"2 if there are 2 maps. :param templates: array containing a set of",
"radians) :param mask: 2D array (nx,ny) containing a HEALPix map corresponding \\ to",
"spin != 2: raise ValueError(\"Purification only implemented for spin-2 fields\") # Flatten mask",
"shape_2D = np.shape(mask) self.ny = shape_2D[0] self.nx = shape_2D[1] if maps is None:",
"field was initialized with contaminant \\ templates, the maps returned by this function",
"and nmaps != 1)): raise ValueError(\"Spin-zero fields are \" \"associated with a single",
"\\ necessary to run a standard pseudo-Cl with deprojection and \\ purification, but",
"for m in t: if np.shape(m) != shape_2D: raise ValueError(\"Mask and templates don't",
"< 0) or (ly < 0): raise ValueError(\"Must supply sensible dimensions for \"",
"and contaminant templates. :param mask: array containing a map corresponding to the field's",
". \\ If `None`, this field will only contain a mask but no",
"isinstance(templates, (list, tuple, np.ndarray)): self.fl = lib.field_alloc_new(wt.is_healpix, wt.nside, lmax_sht, wt.nx, wt.ny, wt.d_phi, wt.d_theta,",
"pure_b, n_iter_mask_purify, n_iter, masked_input, int(lite)) self.lite = lite def __del__(self): if self.fl is",
"to the observed \\ harmonic coefficients of this field. :return: 2D array of"
] |
[
"* len(perms) for j in range(len(perms)): out[perms[j]-1] = str(nums[j]) print(linesep.join(out)) if i !=",
"i in range(num_tests): input() perms = list(map(int, input().split())) nums = list(map(str, input().split())) out",
"perms = list(map(int, input().split())) nums = list(map(str, input().split())) out = [0] * len(perms)",
"= int(input()) for i in range(num_tests): input() perms = list(map(int, input().split())) nums =",
"input() perms = list(map(int, input().split())) nums = list(map(str, input().split())) out = [0] *",
"for j in range(len(perms)): out[perms[j]-1] = str(nums[j]) print(linesep.join(out)) if i != num_tests -",
"= list(map(str, input().split())) out = [0] * len(perms) for j in range(len(perms)): out[perms[j]-1]",
"in range(num_tests): input() perms = list(map(int, input().split())) nums = list(map(str, input().split())) out =",
"list(map(str, input().split())) out = [0] * len(perms) for j in range(len(perms)): out[perms[j]-1] =",
"nums = list(map(str, input().split())) out = [0] * len(perms) for j in range(len(perms)):",
"int(input()) for i in range(num_tests): input() perms = list(map(int, input().split())) nums = list(map(str,",
"from os import linesep num_tests = int(input()) for i in range(num_tests): input() perms",
"for i in range(num_tests): input() perms = list(map(int, input().split())) nums = list(map(str, input().split()))",
"<filename>data-structures/p482.py from os import linesep num_tests = int(input()) for i in range(num_tests): input()",
"list(map(int, input().split())) nums = list(map(str, input().split())) out = [0] * len(perms) for j",
"len(perms) for j in range(len(perms)): out[perms[j]-1] = str(nums[j]) print(linesep.join(out)) if i != num_tests",
"= list(map(int, input().split())) nums = list(map(str, input().split())) out = [0] * len(perms) for",
"[0] * len(perms) for j in range(len(perms)): out[perms[j]-1] = str(nums[j]) print(linesep.join(out)) if i",
"linesep num_tests = int(input()) for i in range(num_tests): input() perms = list(map(int, input().split()))",
"= [0] * len(perms) for j in range(len(perms)): out[perms[j]-1] = str(nums[j]) print(linesep.join(out)) if",
"range(num_tests): input() perms = list(map(int, input().split())) nums = list(map(str, input().split())) out = [0]",
"input().split())) out = [0] * len(perms) for j in range(len(perms)): out[perms[j]-1] = str(nums[j])",
"j in range(len(perms)): out[perms[j]-1] = str(nums[j]) print(linesep.join(out)) if i != num_tests - 1:",
"import linesep num_tests = int(input()) for i in range(num_tests): input() perms = list(map(int,",
"os import linesep num_tests = int(input()) for i in range(num_tests): input() perms =",
"input().split())) nums = list(map(str, input().split())) out = [0] * len(perms) for j in",
"num_tests = int(input()) for i in range(num_tests): input() perms = list(map(int, input().split())) nums",
"in range(len(perms)): out[perms[j]-1] = str(nums[j]) print(linesep.join(out)) if i != num_tests - 1: print()",
"out = [0] * len(perms) for j in range(len(perms)): out[perms[j]-1] = str(nums[j]) print(linesep.join(out))"
] |
[
"= \"m\" FEMALE = \"f\" UNSPECIFIED = \"-\" GENDERS = {(MALE, _(\"male\")), (FEMALE,",
"= \"-\" GENDERS = {(MALE, _(\"male\")), (FEMALE, _(\"female\")), (UNSPECIFIED, _(\"don't want to answer\"))}",
"django.utils.translation import ugettext_lazy as _ MALE = \"m\" FEMALE = \"f\" UNSPECIFIED =",
"from django.utils.translation import ugettext_lazy as _ MALE = \"m\" FEMALE = \"f\" UNSPECIFIED",
"ugettext_lazy as _ MALE = \"m\" FEMALE = \"f\" UNSPECIFIED = \"-\" GENDERS",
"\"m\" FEMALE = \"f\" UNSPECIFIED = \"-\" GENDERS = {(MALE, _(\"male\")), (FEMALE, _(\"female\")),",
"FEMALE = \"f\" UNSPECIFIED = \"-\" GENDERS = {(MALE, _(\"male\")), (FEMALE, _(\"female\")), (UNSPECIFIED,",
"_ MALE = \"m\" FEMALE = \"f\" UNSPECIFIED = \"-\" GENDERS = {(MALE,",
"\"f\" UNSPECIFIED = \"-\" GENDERS = {(MALE, _(\"male\")), (FEMALE, _(\"female\")), (UNSPECIFIED, _(\"don't want",
"MALE = \"m\" FEMALE = \"f\" UNSPECIFIED = \"-\" GENDERS = {(MALE, _(\"male\")),",
"UNSPECIFIED = \"-\" GENDERS = {(MALE, _(\"male\")), (FEMALE, _(\"female\")), (UNSPECIFIED, _(\"don't want to",
"as _ MALE = \"m\" FEMALE = \"f\" UNSPECIFIED = \"-\" GENDERS =",
"import ugettext_lazy as _ MALE = \"m\" FEMALE = \"f\" UNSPECIFIED = \"-\"",
"= \"f\" UNSPECIFIED = \"-\" GENDERS = {(MALE, _(\"male\")), (FEMALE, _(\"female\")), (UNSPECIFIED, _(\"don't"
] |
[
"\"win10\") self.assertEqual(o.Arch, \"X64\") def test_arm_arch(self): o = CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch, \"ARM\") def test_arm64_arch(self):",
"\"10\") def test_win10Server_OS(self): o = CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\") def test_invalid_OS(self): with self.assertRaises(ValueError):",
"o = CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_aarch64_arch(self): o = CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch,",
"\"win10\") def test_invalid_pathtotool(self): o = CatGenerator(\"amd64\", \"10\") with self.assertRaises(Exception) as cm: o.MakeCat(\"garbage\", os.path.join(\"c:\",",
"CatGenerator(\"x64\", \"Invalid Junk\") def test_x64_arch(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_amd64_arch(self):",
"\"ARM\") def test_arm64_arch(self): o = CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_aarch64_arch(self): o =",
"= CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\") def test_invalid_OS(self): with self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid Junk\") def",
"def test_aarch64_arch(self): o = CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_invalid_arch(self): with self.assertRaises(ValueError): CatGenerator(\"Invalid",
"\"win10\") self.assertEqual(o.Arch, \"ARM\") def test_arm64_arch(self): o = CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_aarch64_arch(self):",
"with self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\", \"win10\") def test_invalid_pathtotool(self): o = CatGenerator(\"amd64\", \"10\") with self.assertRaises(Exception)",
"\"10\") with self.assertRaises(Exception) as cm: o.MakeCat(\"garbage\", os.path.join(\"c:\", \"test\", \"badpath\", \"inf2cat.exe\")) self.assertTrue(str(cm.exception).startswith(\"Can't find Inf2Cat",
"from build env or set PYTHONPATH env variable to point to the PythonLibrary",
"\"win10\") self.assertEqual(o.OperatingSystem, \"10\") def test_10_OS(self): o = CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem, \"10\") def test_win10Server_OS(self):",
"CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\") def test_invalid_OS(self): with self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid Junk\") def test_x64_arch(self):",
"o = CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\") def test_invalid_OS(self): with self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid Junk\")",
"\"win10\") self.assertEqual(o.Arch, \"X64\") def test_amd64_arch(self): o = CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_arm_arch(self):",
"test_invalid_arch(self): with self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\", \"win10\") def test_invalid_pathtotool(self): o = CatGenerator(\"amd64\", \"10\") with",
"Uefi.Capsule.CatGenerator import * #must run from build env or set PYTHONPATH env variable",
"as cm: o.MakeCat(\"garbage\", os.path.join(\"c:\", \"test\", \"badpath\", \"inf2cat.exe\")) self.assertTrue(str(cm.exception).startswith(\"Can't find Inf2Cat on this machine.\"))",
"test_x64_arch(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_amd64_arch(self): o = CatGenerator(\"amd64\", \"win10\")",
"with self.assertRaises(Exception) as cm: o.MakeCat(\"garbage\", os.path.join(\"c:\", \"test\", \"badpath\", \"inf2cat.exe\")) self.assertTrue(str(cm.exception).startswith(\"Can't find Inf2Cat on",
"Arch\", \"win10\") def test_invalid_pathtotool(self): o = CatGenerator(\"amd64\", \"10\") with self.assertRaises(Exception) as cm: o.MakeCat(\"garbage\",",
"def test_arm_arch(self): o = CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch, \"ARM\") def test_arm64_arch(self): o = CatGenerator(\"arm64\",",
"def test_amd64_arch(self): o = CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_arm_arch(self): o = CatGenerator(\"arm\",",
"\"Server10\") def test_invalid_OS(self): with self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid Junk\") def test_x64_arch(self): o = CatGenerator(\"x64\",",
"def test_win10_OS(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem, \"10\") def test_10_OS(self): o = CatGenerator(\"x64\",",
"\"ARM64\") def test_aarch64_arch(self): o = CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_invalid_arch(self): with self.assertRaises(ValueError):",
"test_invalid_pathtotool(self): o = CatGenerator(\"amd64\", \"10\") with self.assertRaises(Exception) as cm: o.MakeCat(\"garbage\", os.path.join(\"c:\", \"test\", \"badpath\",",
"or set PYTHONPATH env variable to point to the PythonLibrary folder class CatGeneratorTest(unittest.TestCase):",
"env variable to point to the PythonLibrary folder class CatGeneratorTest(unittest.TestCase): def test_win10_OS(self): o",
"self.assertEqual(o.OperatingSystem, \"Server10\") def test_invalid_OS(self): with self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid Junk\") def test_x64_arch(self): o =",
"self.assertRaises(Exception) as cm: o.MakeCat(\"garbage\", os.path.join(\"c:\", \"test\", \"badpath\", \"inf2cat.exe\")) self.assertTrue(str(cm.exception).startswith(\"Can't find Inf2Cat on this",
"to point to the PythonLibrary folder class CatGeneratorTest(unittest.TestCase): def test_win10_OS(self): o = CatGenerator(\"x64\",",
"CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_amd64_arch(self): o = CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def",
"run from build env or set PYTHONPATH env variable to point to the",
"env or set PYTHONPATH env variable to point to the PythonLibrary folder class",
"o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem, \"10\") def test_10_OS(self): o = CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem,",
"= CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem, \"10\") def test_10_OS(self): o = CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem, \"10\")",
"def test_x64_arch(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_amd64_arch(self): o = CatGenerator(\"amd64\",",
"CatGenerator(\"Invalid Arch\", \"win10\") def test_invalid_pathtotool(self): o = CatGenerator(\"amd64\", \"10\") with self.assertRaises(Exception) as cm:",
"test_arm64_arch(self): o = CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_aarch64_arch(self): o = CatGenerator(\"aarch64\", \"win10\")",
"import logging import unittest from Uefi.Capsule.CatGenerator import * #must run from build env",
"the PythonLibrary folder class CatGeneratorTest(unittest.TestCase): def test_win10_OS(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem, \"10\")",
"def test_10_OS(self): o = CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem, \"10\") def test_win10Server_OS(self): o = CatGenerator(\"x64\",",
"variable to point to the PythonLibrary folder class CatGeneratorTest(unittest.TestCase): def test_win10_OS(self): o =",
"= CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_invalid_arch(self): with self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\", \"win10\") def",
"= CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch, \"ARM\") def test_arm64_arch(self): o = CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\")",
"to the PythonLibrary folder class CatGeneratorTest(unittest.TestCase): def test_win10_OS(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem,",
"o = CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem, \"10\") def test_win10Server_OS(self): o = CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem,",
"self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid Junk\") def test_x64_arch(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def",
"self.assertEqual(o.OperatingSystem, \"10\") def test_10_OS(self): o = CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem, \"10\") def test_win10Server_OS(self): o",
"test_win10_OS(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem, \"10\") def test_10_OS(self): o = CatGenerator(\"x64\", \"10\")",
"\"10\") self.assertEqual(o.OperatingSystem, \"10\") def test_win10Server_OS(self): o = CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\") def test_invalid_OS(self):",
"CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_aarch64_arch(self): o = CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def",
"set PYTHONPATH env variable to point to the PythonLibrary folder class CatGeneratorTest(unittest.TestCase): def",
"self.assertEqual(o.OperatingSystem, \"10\") def test_win10Server_OS(self): o = CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\") def test_invalid_OS(self): with",
"CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem, \"10\") def test_10_OS(self): o = CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem, \"10\") def",
"class CatGeneratorTest(unittest.TestCase): def test_win10_OS(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem, \"10\") def test_10_OS(self): o",
"\"X64\") def test_arm_arch(self): o = CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch, \"ARM\") def test_arm64_arch(self): o =",
"\"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_aarch64_arch(self): o = CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_invalid_arch(self):",
"def test_win10Server_OS(self): o = CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\") def test_invalid_OS(self): with self.assertRaises(ValueError): CatGenerator(\"x64\",",
"self.assertEqual(o.Arch, \"ARM64\") def test_aarch64_arch(self): o = CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_invalid_arch(self): with",
"PythonLibrary folder class CatGeneratorTest(unittest.TestCase): def test_win10_OS(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem, \"10\") def",
"#must run from build env or set PYTHONPATH env variable to point to",
"\"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\") def test_invalid_OS(self): with self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid Junk\") def test_x64_arch(self): o",
"= CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_arm_arch(self): o = CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch, \"ARM\")",
"unittest from Uefi.Capsule.CatGenerator import * #must run from build env or set PYTHONPATH",
"from Uefi.Capsule.CatGenerator import * #must run from build env or set PYTHONPATH env",
"self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\", \"win10\") def test_invalid_pathtotool(self): o = CatGenerator(\"amd64\", \"10\") with self.assertRaises(Exception) as",
"def test_invalid_arch(self): with self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\", \"win10\") def test_invalid_pathtotool(self): o = CatGenerator(\"amd64\", \"10\")",
"CatGeneratorTest(unittest.TestCase): def test_win10_OS(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem, \"10\") def test_10_OS(self): o =",
"os import logging import unittest from Uefi.Capsule.CatGenerator import * #must run from build",
"def test_invalid_OS(self): with self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid Junk\") def test_x64_arch(self): o = CatGenerator(\"x64\", \"win10\")",
"PYTHONPATH env variable to point to the PythonLibrary folder class CatGeneratorTest(unittest.TestCase): def test_win10_OS(self):",
"folder class CatGeneratorTest(unittest.TestCase): def test_win10_OS(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.OperatingSystem, \"10\") def test_10_OS(self):",
"* #must run from build env or set PYTHONPATH env variable to point",
"def test_arm64_arch(self): o = CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_aarch64_arch(self): o = CatGenerator(\"aarch64\",",
"test_10_OS(self): o = CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem, \"10\") def test_win10Server_OS(self): o = CatGenerator(\"x64\", \"Server10\")",
"CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem, \"10\") def test_win10Server_OS(self): o = CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\") def",
"build env or set PYTHONPATH env variable to point to the PythonLibrary folder",
"CatGenerator(\"amd64\", \"10\") with self.assertRaises(Exception) as cm: o.MakeCat(\"garbage\", os.path.join(\"c:\", \"test\", \"badpath\", \"inf2cat.exe\")) self.assertTrue(str(cm.exception).startswith(\"Can't find",
"o = CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch, \"ARM\") def test_arm64_arch(self): o = CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch,",
"self.assertEqual(o.Arch, \"X64\") def test_arm_arch(self): o = CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch, \"ARM\") def test_arm64_arch(self): o",
"\"Invalid Junk\") def test_x64_arch(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_amd64_arch(self): o",
"self.assertEqual(o.Arch, \"X64\") def test_amd64_arch(self): o = CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_arm_arch(self): o",
"o = CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_invalid_arch(self): with self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\", \"win10\")",
"test_invalid_OS(self): with self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid Junk\") def test_x64_arch(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch,",
"point to the PythonLibrary folder class CatGeneratorTest(unittest.TestCase): def test_win10_OS(self): o = CatGenerator(\"x64\", \"win10\")",
"\"X64\") def test_amd64_arch(self): o = CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_arm_arch(self): o =",
"test_aarch64_arch(self): o = CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_invalid_arch(self): with self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\",",
"= CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_aarch64_arch(self): o = CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\")",
"import unittest from Uefi.Capsule.CatGenerator import * #must run from build env or set",
"\"ARM64\") def test_invalid_arch(self): with self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\", \"win10\") def test_invalid_pathtotool(self): o = CatGenerator(\"amd64\",",
"def test_invalid_pathtotool(self): o = CatGenerator(\"amd64\", \"10\") with self.assertRaises(Exception) as cm: o.MakeCat(\"garbage\", os.path.join(\"c:\", \"test\",",
"self.assertEqual(o.Arch, \"ARM\") def test_arm64_arch(self): o = CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_aarch64_arch(self): o",
"= CatGenerator(\"amd64\", \"10\") with self.assertRaises(Exception) as cm: o.MakeCat(\"garbage\", os.path.join(\"c:\", \"test\", \"badpath\", \"inf2cat.exe\")) self.assertTrue(str(cm.exception).startswith(\"Can't",
"import * #must run from build env or set PYTHONPATH env variable to",
"\"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_invalid_arch(self): with self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\", \"win10\") def test_invalid_pathtotool(self): o",
"test_win10Server_OS(self): o = CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\") def test_invalid_OS(self): with self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid",
"o = CatGenerator(\"amd64\", \"10\") with self.assertRaises(Exception) as cm: o.MakeCat(\"garbage\", os.path.join(\"c:\", \"test\", \"badpath\", \"inf2cat.exe\"))",
"self.assertEqual(o.Arch, \"ARM64\") def test_invalid_arch(self): with self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\", \"win10\") def test_invalid_pathtotool(self): o =",
"logging import unittest from Uefi.Capsule.CatGenerator import * #must run from build env or",
"= CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_amd64_arch(self): o = CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch, \"X64\")",
"import os import logging import unittest from Uefi.Capsule.CatGenerator import * #must run from",
"\"10\") def test_10_OS(self): o = CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem, \"10\") def test_win10Server_OS(self): o =",
"CatGenerator(\"aarch64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def test_invalid_arch(self): with self.assertRaises(ValueError): CatGenerator(\"Invalid Arch\", \"win10\") def test_invalid_pathtotool(self):",
"o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_amd64_arch(self): o = CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch,",
"with self.assertRaises(ValueError): CatGenerator(\"x64\", \"Invalid Junk\") def test_x64_arch(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch, \"X64\")",
"CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch, \"ARM\") def test_arm64_arch(self): o = CatGenerator(\"arm64\", \"win10\") self.assertEqual(o.Arch, \"ARM64\") def",
"= CatGenerator(\"x64\", \"10\") self.assertEqual(o.OperatingSystem, \"10\") def test_win10Server_OS(self): o = CatGenerator(\"x64\", \"Server10\") self.assertEqual(o.OperatingSystem, \"Server10\")",
"Junk\") def test_x64_arch(self): o = CatGenerator(\"x64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_amd64_arch(self): o =",
"CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_arm_arch(self): o = CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch, \"ARM\") def",
"test_amd64_arch(self): o = CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_arm_arch(self): o = CatGenerator(\"arm\", \"win10\")",
"test_arm_arch(self): o = CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch, \"ARM\") def test_arm64_arch(self): o = CatGenerator(\"arm64\", \"win10\")",
"o = CatGenerator(\"amd64\", \"win10\") self.assertEqual(o.Arch, \"X64\") def test_arm_arch(self): o = CatGenerator(\"arm\", \"win10\") self.assertEqual(o.Arch,"
] |
[
"if X.shape == (2,): X = [X] for x, y in X: ax.plot(",
"float = 15 ) -> Tuple[float, float]: return a - np.cos(y) * b,",
"**knobs ) return ax def root_mean_squared_error( x: Union[float, np.ndarray], y: Union[float, np.ndarray] )",
"linestyle=linestyle, marker=marker, markersize=markersize, markevery=markevery, antialiased=antialiased, **knobs ) return ax def root_mean_squared_error( x: Union[float,",
"str = \"X\", markersize: int = 6, markevery: int = 2, antialiased: bool",
"== (2,): X = [X] for x, y in X: ax.plot( [x, x],",
"markersize: int = 6, markevery: int = 2, antialiased: bool = True, figsize:",
"6, markevery: int = 2, antialiased: bool = True, figsize: Tuple[float, float] =",
"ax.plot( [x, x], [y, y], [problem(np.asarray([x, y])), 0], c=c, linestyle=linestyle, marker=marker, markersize=markersize, markevery=markevery,",
"= 15 ) -> Tuple[float, float]: return a - np.cos(y) * b, x",
"bool = True, figsize: Tuple[float, float] = (12, 8), kwargs: Dict = None,",
"y: Union[float, np.ndarray] ) -> float: return np.sqrt(np.mean(np.power(np.subtract(x, y), 2))) def custom_init_view_function( y:",
"Union, TypeVar, Iterable, Dict from goa import problems T = TypeVar(\"T\") def plot_population(",
"TypeVar, Iterable, Dict from goa import problems T = TypeVar(\"T\") def plot_population( problem:",
"\"X\", markersize: int = 6, markevery: int = 2, antialiased: bool = True,",
"= \"darkblue\", linestyle: str = \":\", marker: str = \"X\", markersize: int =",
"y], [problem(np.asarray([x, y])), 0], c=c, linestyle=linestyle, marker=marker, markersize=markersize, markevery=markevery, antialiased=antialiased, **knobs ) return",
"30, b: float = 15 ) -> Tuple[float, float]: return a - np.cos(y)",
"= 30, b: float = 15 ) -> Tuple[float, float]: return a -",
"markersize=markersize, markevery=markevery, antialiased=antialiased, **knobs ) return ax def root_mean_squared_error( x: Union[float, np.ndarray], y:",
"import Tuple, Union, TypeVar, Iterable, Dict from goa import problems T = TypeVar(\"T\")",
"numpy as np import matplotlib.pyplot as plt from typing import Tuple, Union, TypeVar,",
"str = \"darkblue\", linestyle: str = \":\", marker: str = \"X\", markersize: int",
"np import matplotlib.pyplot as plt from typing import Tuple, Union, TypeVar, Iterable, Dict",
"antialiased=antialiased, **knobs ) return ax def root_mean_squared_error( x: Union[float, np.ndarray], y: Union[float, np.ndarray]",
"= \":\", marker: str = \"X\", markersize: int = 6, markevery: int =",
"= (12, 8), kwargs: Dict = None, ) -> plt.Axes: knobs = dict()",
"knobs.update(kwargs) if not ax: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(projection=\"3d\") if X.shape ==",
"X.shape == (2,): X = [X] for x, y in X: ax.plot( [x,",
") return ax def root_mean_squared_error( x: Union[float, np.ndarray], y: Union[float, np.ndarray] ) ->",
"root_mean_squared_error( x: Union[float, np.ndarray], y: Union[float, np.ndarray] ) -> float: return np.sqrt(np.mean(np.power(np.subtract(x, y),",
"ax: plt.Axes = None, c: str = \"darkblue\", linestyle: str = \":\", marker:",
"plt.figure(figsize=figsize) ax = fig.add_subplot(projection=\"3d\") if X.shape == (2,): X = [X] for x,",
"Dict from goa import problems T = TypeVar(\"T\") def plot_population( problem: problems.BaseProblem, X:",
"Dict = None, ) -> plt.Axes: knobs = dict() if kwargs is not",
"[X] for x, y in X: ax.plot( [x, x], [y, y], [problem(np.asarray([x, y])),",
"plt.Axes: knobs = dict() if kwargs is not None: knobs.update(kwargs) if not ax:",
"(12, 8), kwargs: Dict = None, ) -> plt.Axes: knobs = dict() if",
"plt from typing import Tuple, Union, TypeVar, Iterable, Dict from goa import problems",
"x], [y, y], [problem(np.asarray([x, y])), 0], c=c, linestyle=linestyle, marker=marker, markersize=markersize, markevery=markevery, antialiased=antialiased, **knobs",
"as np import matplotlib.pyplot as plt from typing import Tuple, Union, TypeVar, Iterable,",
"8), kwargs: Dict = None, ) -> plt.Axes: knobs = dict() if kwargs",
"in X: ax.plot( [x, x], [y, y], [problem(np.asarray([x, y])), 0], c=c, linestyle=linestyle, marker=marker,",
"linestyle: str = \":\", marker: str = \"X\", markersize: int = 6, markevery:",
"kwargs: Dict = None, ) -> plt.Axes: knobs = dict() if kwargs is",
"= 120, a: float = 30, b: float = 15 ) -> Tuple[float,",
"return np.sqrt(np.mean(np.power(np.subtract(x, y), 2))) def custom_init_view_function( y: float = 20, x: float =",
"goa import problems T = TypeVar(\"T\") def plot_population( problem: problems.BaseProblem, X: Union[T, Iterable[T]],",
"X = [X] for x, y in X: ax.plot( [x, x], [y, y],",
"float = 120, a: float = 30, b: float = 15 ) ->",
"y: float = 20, x: float = 120, a: float = 30, b:",
"None: knobs.update(kwargs) if not ax: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(projection=\"3d\") if X.shape",
"if not ax: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(projection=\"3d\") if X.shape == (2,):",
"int = 2, antialiased: bool = True, figsize: Tuple[float, float] = (12, 8),",
"Union[float, np.ndarray] ) -> float: return np.sqrt(np.mean(np.power(np.subtract(x, y), 2))) def custom_init_view_function( y: float",
") -> float: return np.sqrt(np.mean(np.power(np.subtract(x, y), 2))) def custom_init_view_function( y: float = 20,",
"\"darkblue\", linestyle: str = \":\", marker: str = \"X\", markersize: int = 6,",
"= [X] for x, y in X: ax.plot( [x, x], [y, y], [problem(np.asarray([x,",
"marker: str = \"X\", markersize: int = 6, markevery: int = 2, antialiased:",
"(2,): X = [X] for x, y in X: ax.plot( [x, x], [y,",
"X: Union[T, Iterable[T]], ax: plt.Axes = None, c: str = \"darkblue\", linestyle: str",
"dict() if kwargs is not None: knobs.update(kwargs) if not ax: fig = plt.figure(figsize=figsize)",
"if kwargs is not None: knobs.update(kwargs) if not ax: fig = plt.figure(figsize=figsize) ax",
"str = \":\", marker: str = \"X\", markersize: int = 6, markevery: int",
"b: float = 15 ) -> Tuple[float, float]: return a - np.cos(y) *",
"Tuple, Union, TypeVar, Iterable, Dict from goa import problems T = TypeVar(\"T\") def",
"as plt from typing import Tuple, Union, TypeVar, Iterable, Dict from goa import",
"Tuple[float, float] = (12, 8), kwargs: Dict = None, ) -> plt.Axes: knobs",
"kwargs is not None: knobs.update(kwargs) if not ax: fig = plt.figure(figsize=figsize) ax =",
"not ax: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(projection=\"3d\") if X.shape == (2,): X",
"120, a: float = 30, b: float = 15 ) -> Tuple[float, float]:",
"not None: knobs.update(kwargs) if not ax: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(projection=\"3d\") if",
"[problem(np.asarray([x, y])), 0], c=c, linestyle=linestyle, marker=marker, markersize=markersize, markevery=markevery, antialiased=antialiased, **knobs ) return ax",
"Iterable[T]], ax: plt.Axes = None, c: str = \"darkblue\", linestyle: str = \":\",",
"for x, y in X: ax.plot( [x, x], [y, y], [problem(np.asarray([x, y])), 0],",
"y])), 0], c=c, linestyle=linestyle, marker=marker, markersize=markersize, markevery=markevery, antialiased=antialiased, **knobs ) return ax def",
"custom_init_view_function( y: float = 20, x: float = 120, a: float = 30,",
"[y, y], [problem(np.asarray([x, y])), 0], c=c, linestyle=linestyle, marker=marker, markersize=markersize, markevery=markevery, antialiased=antialiased, **knobs )",
"antialiased: bool = True, figsize: Tuple[float, float] = (12, 8), kwargs: Dict =",
"= 6, markevery: int = 2, antialiased: bool = True, figsize: Tuple[float, float]",
"problems.BaseProblem, X: Union[T, Iterable[T]], ax: plt.Axes = None, c: str = \"darkblue\", linestyle:",
"\":\", marker: str = \"X\", markersize: int = 6, markevery: int = 2,",
"= plt.figure(figsize=figsize) ax = fig.add_subplot(projection=\"3d\") if X.shape == (2,): X = [X] for",
"TypeVar(\"T\") def plot_population( problem: problems.BaseProblem, X: Union[T, Iterable[T]], ax: plt.Axes = None, c:",
"= fig.add_subplot(projection=\"3d\") if X.shape == (2,): X = [X] for x, y in",
"import numpy as np import matplotlib.pyplot as plt from typing import Tuple, Union,",
"markevery: int = 2, antialiased: bool = True, figsize: Tuple[float, float] = (12,",
"a: float = 30, b: float = 15 ) -> Tuple[float, float]: return",
"int = 6, markevery: int = 2, antialiased: bool = True, figsize: Tuple[float,",
"np.sqrt(np.mean(np.power(np.subtract(x, y), 2))) def custom_init_view_function( y: float = 20, x: float = 120,",
"float = 20, x: float = 120, a: float = 30, b: float",
"float: return np.sqrt(np.mean(np.power(np.subtract(x, y), 2))) def custom_init_view_function( y: float = 20, x: float",
"2))) def custom_init_view_function( y: float = 20, x: float = 120, a: float",
"= True, figsize: Tuple[float, float] = (12, 8), kwargs: Dict = None, )",
"problems T = TypeVar(\"T\") def plot_population( problem: problems.BaseProblem, X: Union[T, Iterable[T]], ax: plt.Axes",
"is not None: knobs.update(kwargs) if not ax: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(projection=\"3d\")",
"typing import Tuple, Union, TypeVar, Iterable, Dict from goa import problems T =",
"problem: problems.BaseProblem, X: Union[T, Iterable[T]], ax: plt.Axes = None, c: str = \"darkblue\",",
"np.ndarray] ) -> float: return np.sqrt(np.mean(np.power(np.subtract(x, y), 2))) def custom_init_view_function( y: float =",
"def custom_init_view_function( y: float = 20, x: float = 120, a: float =",
"return ax def root_mean_squared_error( x: Union[float, np.ndarray], y: Union[float, np.ndarray] ) -> float:",
"True, figsize: Tuple[float, float] = (12, 8), kwargs: Dict = None, ) ->",
"c: str = \"darkblue\", linestyle: str = \":\", marker: str = \"X\", markersize:",
"None, ) -> plt.Axes: knobs = dict() if kwargs is not None: knobs.update(kwargs)",
"c=c, linestyle=linestyle, marker=marker, markersize=markersize, markevery=markevery, antialiased=antialiased, **knobs ) return ax def root_mean_squared_error( x:",
"= None, ) -> plt.Axes: knobs = dict() if kwargs is not None:",
"import problems T = TypeVar(\"T\") def plot_population( problem: problems.BaseProblem, X: Union[T, Iterable[T]], ax:",
"Union[T, Iterable[T]], ax: plt.Axes = None, c: str = \"darkblue\", linestyle: str =",
"fig = plt.figure(figsize=figsize) ax = fig.add_subplot(projection=\"3d\") if X.shape == (2,): X = [X]",
"def plot_population( problem: problems.BaseProblem, X: Union[T, Iterable[T]], ax: plt.Axes = None, c: str",
"def root_mean_squared_error( x: Union[float, np.ndarray], y: Union[float, np.ndarray] ) -> float: return np.sqrt(np.mean(np.power(np.subtract(x,",
"-> plt.Axes: knobs = dict() if kwargs is not None: knobs.update(kwargs) if not",
"y in X: ax.plot( [x, x], [y, y], [problem(np.asarray([x, y])), 0], c=c, linestyle=linestyle,",
"= \"X\", markersize: int = 6, markevery: int = 2, antialiased: bool =",
"0], c=c, linestyle=linestyle, marker=marker, markersize=markersize, markevery=markevery, antialiased=antialiased, **knobs ) return ax def root_mean_squared_error(",
"marker=marker, markersize=markersize, markevery=markevery, antialiased=antialiased, **knobs ) return ax def root_mean_squared_error( x: Union[float, np.ndarray],",
"np.ndarray], y: Union[float, np.ndarray] ) -> float: return np.sqrt(np.mean(np.power(np.subtract(x, y), 2))) def custom_init_view_function(",
"= 2, antialiased: bool = True, figsize: Tuple[float, float] = (12, 8), kwargs:",
"ax def root_mean_squared_error( x: Union[float, np.ndarray], y: Union[float, np.ndarray] ) -> float: return",
"= 20, x: float = 120, a: float = 30, b: float =",
"x: float = 120, a: float = 30, b: float = 15 )",
"figsize: Tuple[float, float] = (12, 8), kwargs: Dict = None, ) -> plt.Axes:",
"ax = fig.add_subplot(projection=\"3d\") if X.shape == (2,): X = [X] for x, y",
"[x, x], [y, y], [problem(np.asarray([x, y])), 0], c=c, linestyle=linestyle, marker=marker, markersize=markersize, markevery=markevery, antialiased=antialiased,",
"plot_population( problem: problems.BaseProblem, X: Union[T, Iterable[T]], ax: plt.Axes = None, c: str =",
"y), 2))) def custom_init_view_function( y: float = 20, x: float = 120, a:",
"20, x: float = 120, a: float = 30, b: float = 15",
"ax: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(projection=\"3d\") if X.shape == (2,): X =",
"Iterable, Dict from goa import problems T = TypeVar(\"T\") def plot_population( problem: problems.BaseProblem,",
"import matplotlib.pyplot as plt from typing import Tuple, Union, TypeVar, Iterable, Dict from",
"float] = (12, 8), kwargs: Dict = None, ) -> plt.Axes: knobs =",
"= TypeVar(\"T\") def plot_population( problem: problems.BaseProblem, X: Union[T, Iterable[T]], ax: plt.Axes = None,",
"from typing import Tuple, Union, TypeVar, Iterable, Dict from goa import problems T",
"matplotlib.pyplot as plt from typing import Tuple, Union, TypeVar, Iterable, Dict from goa",
"plt.Axes = None, c: str = \"darkblue\", linestyle: str = \":\", marker: str",
"= dict() if kwargs is not None: knobs.update(kwargs) if not ax: fig =",
"2, antialiased: bool = True, figsize: Tuple[float, float] = (12, 8), kwargs: Dict",
"fig.add_subplot(projection=\"3d\") if X.shape == (2,): X = [X] for x, y in X:",
"-> float: return np.sqrt(np.mean(np.power(np.subtract(x, y), 2))) def custom_init_view_function( y: float = 20, x:",
"X: ax.plot( [x, x], [y, y], [problem(np.asarray([x, y])), 0], c=c, linestyle=linestyle, marker=marker, markersize=markersize,",
"x: Union[float, np.ndarray], y: Union[float, np.ndarray] ) -> float: return np.sqrt(np.mean(np.power(np.subtract(x, y), 2)))",
"float = 30, b: float = 15 ) -> Tuple[float, float]: return a",
"None, c: str = \"darkblue\", linestyle: str = \":\", marker: str = \"X\",",
") -> plt.Axes: knobs = dict() if kwargs is not None: knobs.update(kwargs) if",
"from goa import problems T = TypeVar(\"T\") def plot_population( problem: problems.BaseProblem, X: Union[T,",
"T = TypeVar(\"T\") def plot_population( problem: problems.BaseProblem, X: Union[T, Iterable[T]], ax: plt.Axes =",
"knobs = dict() if kwargs is not None: knobs.update(kwargs) if not ax: fig",
"markevery=markevery, antialiased=antialiased, **knobs ) return ax def root_mean_squared_error( x: Union[float, np.ndarray], y: Union[float,",
"Union[float, np.ndarray], y: Union[float, np.ndarray] ) -> float: return np.sqrt(np.mean(np.power(np.subtract(x, y), 2))) def",
"x, y in X: ax.plot( [x, x], [y, y], [problem(np.asarray([x, y])), 0], c=c,",
"= None, c: str = \"darkblue\", linestyle: str = \":\", marker: str ="
] |
[
"environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key(): return Fernet.generate_key() def write_key_env_var(crypto_key):",
"import Path # Third party from cryptography.fernet import Fernet from dotenv import load_dotenv",
"crypto key may still be in use.' ENV_VAR_PATH = Path.home() / '.my_python_env' #",
"'CRYPTO_KEY' ENV_VAR_EXIST = f'The {CRYPTO_KEY_ENV_VAR} environment variable already exist. Cannot continue as the",
"in use.' ENV_VAR_PATH = Path.home() / '.my_python_env' # Load virtual environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH)",
"may still be in use.' ENV_VAR_PATH = Path.home() / '.my_python_env' # Load virtual",
"party from cryptography.fernet import Fernet from dotenv import load_dotenv # Constants CRYPTO_KEY_ENV_VAR =",
"write_key_env_var(crypto_key): # Only write if environmental variable does not exist. # Otherwise raise",
"os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key(): return Fernet.generate_key() def write_key_env_var(crypto_key): # Only write if environmental variable",
"exist. Cannot continue as the crypto key may still be in use.' ENV_VAR_PATH",
"def write_key_env_var(crypto_key): # Only write if environmental variable does not exist. # Otherwise",
"not environment_var_exist(): with ENV_VAR_PATH.open(mode='w') as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else: raise Exception(ENV_VAR_EXIST) if __name__ ==",
"Fernet from dotenv import load_dotenv # Constants CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY' ENV_VAR_EXIST = f'The",
"cryptography.fernet import Fernet from dotenv import load_dotenv # Constants CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY' ENV_VAR_EXIST",
"still be in use.' ENV_VAR_PATH = Path.home() / '.my_python_env' # Load virtual environmental",
"load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key(): return Fernet.generate_key() def write_key_env_var(crypto_key): # Only",
"= 'CRYPTO_KEY' ENV_VAR_EXIST = f'The {CRYPTO_KEY_ENV_VAR} environment variable already exist. Cannot continue as",
"# Third party from cryptography.fernet import Fernet from dotenv import load_dotenv # Constants",
"an exception - environment variable already exists. if not environment_var_exist(): with ENV_VAR_PATH.open(mode='w') as",
"exception - environment variable already exists. if not environment_var_exist(): with ENV_VAR_PATH.open(mode='w') as file:",
"exist. # Otherwise raise an exception - environment variable already exists. if not",
"continue as the crypto key may still be in use.' ENV_VAR_PATH = Path.home()",
"- environment variable already exists. if not environment_var_exist(): with ENV_VAR_PATH.open(mode='w') as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}')",
"Path.home() / '.my_python_env' # Load virtual environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR)",
"already exist. Cannot continue as the crypto key may still be in use.'",
"the crypto key may still be in use.' ENV_VAR_PATH = Path.home() / '.my_python_env'",
"import load_dotenv # Constants CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY' ENV_VAR_EXIST = f'The {CRYPTO_KEY_ENV_VAR} environment variable",
"Standard library import os from pathlib import Path # Third party from cryptography.fernet",
"ENV_VAR_PATH.open(mode='w') as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else: raise Exception(ENV_VAR_EXIST) if __name__ == '__main__': crypto_key =",
"variable already exist. Cannot continue as the crypto key may still be in",
"Otherwise raise an exception - environment variable already exists. if not environment_var_exist(): with",
"environment_var_exist(): with ENV_VAR_PATH.open(mode='w') as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else: raise Exception(ENV_VAR_EXIST) if __name__ == '__main__':",
"Fernet.generate_key() def write_key_env_var(crypto_key): # Only write if environmental variable does not exist. #",
"variables load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key(): return Fernet.generate_key() def write_key_env_var(crypto_key): #",
"# Standard library import os from pathlib import Path # Third party from",
"# Only write if environmental variable does not exist. # Otherwise raise an",
"key may still be in use.' ENV_VAR_PATH = Path.home() / '.my_python_env' # Load",
"use.' ENV_VAR_PATH = Path.home() / '.my_python_env' # Load virtual environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH) def",
"return os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key(): return Fernet.generate_key() def write_key_env_var(crypto_key): # Only write if environmental",
"environment variable already exist. Cannot continue as the crypto key may still be",
"Load virtual environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key(): return Fernet.generate_key()",
"raise an exception - environment variable already exists. if not environment_var_exist(): with ENV_VAR_PATH.open(mode='w')",
"does not exist. # Otherwise raise an exception - environment variable already exists.",
"already exists. if not environment_var_exist(): with ENV_VAR_PATH.open(mode='w') as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else: raise Exception(ENV_VAR_EXIST)",
"Constants CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY' ENV_VAR_EXIST = f'The {CRYPTO_KEY_ENV_VAR} environment variable already exist. Cannot",
"ENV_VAR_PATH = Path.home() / '.my_python_env' # Load virtual environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist():",
"variable does not exist. # Otherwise raise an exception - environment variable already",
"def generate_key(): return Fernet.generate_key() def write_key_env_var(crypto_key): # Only write if environmental variable does",
"Path # Third party from cryptography.fernet import Fernet from dotenv import load_dotenv #",
"with ENV_VAR_PATH.open(mode='w') as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else: raise Exception(ENV_VAR_EXIST) if __name__ == '__main__': crypto_key",
"file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else: raise Exception(ENV_VAR_EXIST) if __name__ == '__main__': crypto_key = generate_key().decode() write_key_env_var(crypto_key)",
"CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY' ENV_VAR_EXIST = f'The {CRYPTO_KEY_ENV_VAR} environment variable already exist. Cannot continue",
"f'The {CRYPTO_KEY_ENV_VAR} environment variable already exist. Cannot continue as the crypto key may",
"dotenv import load_dotenv # Constants CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY' ENV_VAR_EXIST = f'The {CRYPTO_KEY_ENV_VAR} environment",
"from pathlib import Path # Third party from cryptography.fernet import Fernet from dotenv",
"Third party from cryptography.fernet import Fernet from dotenv import load_dotenv # Constants CRYPTO_KEY_ENV_VAR",
"variable already exists. if not environment_var_exist(): with ENV_VAR_PATH.open(mode='w') as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else: raise",
"as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else: raise Exception(ENV_VAR_EXIST) if __name__ == '__main__': crypto_key = generate_key().decode()",
"Cannot continue as the crypto key may still be in use.' ENV_VAR_PATH =",
"load_dotenv # Constants CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY' ENV_VAR_EXIST = f'The {CRYPTO_KEY_ENV_VAR} environment variable already",
"if not environment_var_exist(): with ENV_VAR_PATH.open(mode='w') as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else: raise Exception(ENV_VAR_EXIST) if __name__",
"be in use.' ENV_VAR_PATH = Path.home() / '.my_python_env' # Load virtual environmental variables",
"generate_key(): return Fernet.generate_key() def write_key_env_var(crypto_key): # Only write if environmental variable does not",
"virtual environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key(): return Fernet.generate_key() def",
"Only write if environmental variable does not exist. # Otherwise raise an exception",
"os from pathlib import Path # Third party from cryptography.fernet import Fernet from",
"= Path.home() / '.my_python_env' # Load virtual environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist(): return",
"as the crypto key may still be in use.' ENV_VAR_PATH = Path.home() /",
"def environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key(): return Fernet.generate_key() def write_key_env_var(crypto_key): # Only write",
"pathlib import Path # Third party from cryptography.fernet import Fernet from dotenv import",
"write if environmental variable does not exist. # Otherwise raise an exception -",
"import Fernet from dotenv import load_dotenv # Constants CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY' ENV_VAR_EXIST =",
"not exist. # Otherwise raise an exception - environment variable already exists. if",
"ENV_VAR_EXIST = f'The {CRYPTO_KEY_ENV_VAR} environment variable already exist. Cannot continue as the crypto",
"/ '.my_python_env' # Load virtual environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR) def",
"# Load virtual environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key(): return",
"library import os from pathlib import Path # Third party from cryptography.fernet import",
"if environmental variable does not exist. # Otherwise raise an exception - environment",
"environment variable already exists. if not environment_var_exist(): with ENV_VAR_PATH.open(mode='w') as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else:",
"environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key(): return Fernet.generate_key() def write_key_env_var(crypto_key): # Only write if",
"= f'The {CRYPTO_KEY_ENV_VAR} environment variable already exist. Cannot continue as the crypto key",
"# Otherwise raise an exception - environment variable already exists. if not environment_var_exist():",
"exists. if not environment_var_exist(): with ENV_VAR_PATH.open(mode='w') as file: file.write(f'{CRYPTO_KEY_ENV_VAR}={crypto_key}') else: raise Exception(ENV_VAR_EXIST) if",
"import os from pathlib import Path # Third party from cryptography.fernet import Fernet",
"{CRYPTO_KEY_ENV_VAR} environment variable already exist. Cannot continue as the crypto key may still",
"# Constants CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY' ENV_VAR_EXIST = f'The {CRYPTO_KEY_ENV_VAR} environment variable already exist.",
"from dotenv import load_dotenv # Constants CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY' ENV_VAR_EXIST = f'The {CRYPTO_KEY_ENV_VAR}",
"return Fernet.generate_key() def write_key_env_var(crypto_key): # Only write if environmental variable does not exist.",
"from cryptography.fernet import Fernet from dotenv import load_dotenv # Constants CRYPTO_KEY_ENV_VAR = 'CRYPTO_KEY'",
"'.my_python_env' # Load virtual environmental variables load_dotenv(dotenv_path=ENV_VAR_PATH) def environment_var_exist(): return os.environ.get(CRYPTO_KEY_ENV_VAR) def generate_key():",
"environmental variable does not exist. # Otherwise raise an exception - environment variable"
] |
[
"#Q19: Elhuyar #positem = \"Q8\" # Q7: substantibo, Q8: aditza with open(infilename, encoding=\"utf-8\")",
"\"Q8\" # Q7: substantibo, Q8: aditza with open(infilename, encoding=\"utf-8\") as csvfile: sourcedict =",
"csvfile: sourcedict = csv.DictReader(csvfile) lex_elh = {} for row in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] =",
"awb.wdmappings: wdid = awb.wdmappings[awbid] if awbid.startswith('L') and wdid in lex_elh: wdstatement = awb.updateclaim(awbid,",
"in awb.wdmappings: wdid = awb.wdmappings[awbid] if awbid.startswith('L') and wdid in lex_elh: wdstatement =",
"wdstatement = awb.updateclaim(awbid, \"P1\", wdid, \"string\") quali = awb.setqualifier(awbid, \"P1\", wdstatement, \"P7\", lex_elh[wdid],",
"config.datafolder+'wikidata/wdlid_ElhId.csv' resourceitem = \"Q19\" #Q19: Elhuyar #positem = \"Q8\" # Q7: substantibo, Q8:",
"Q8: aditza with open(infilename, encoding=\"utf-8\") as csvfile: sourcedict = csv.DictReader(csvfile) lex_elh = {}",
"import config import awb infilename = config.datafolder+'wikidata/wdlid_ElhId.csv' resourceitem = \"Q19\" #Q19: Elhuyar #positem",
"{} for row in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId'] for awbid in awb.wdmappings: wdid",
"if awbid.startswith('L') and wdid in lex_elh: wdstatement = awb.updateclaim(awbid, \"P1\", wdid, \"string\") quali",
"= \"Q19\" #Q19: Elhuyar #positem = \"Q8\" # Q7: substantibo, Q8: aditza with",
"awbid.startswith('L') and wdid in lex_elh: wdstatement = awb.updateclaim(awbid, \"P1\", wdid, \"string\") quali =",
"csv.DictReader(csvfile) lex_elh = {} for row in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId'] for awbid",
"csv import config import awb infilename = config.datafolder+'wikidata/wdlid_ElhId.csv' resourceitem = \"Q19\" #Q19: Elhuyar",
"with open(infilename, encoding=\"utf-8\") as csvfile: sourcedict = csv.DictReader(csvfile) lex_elh = {} for row",
"sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId'] for awbid in awb.wdmappings: wdid = awb.wdmappings[awbid] if awbid.startswith('L')",
"for row in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId'] for awbid in awb.wdmappings: wdid =",
"awb.wdmappings[awbid] if awbid.startswith('L') and wdid in lex_elh: wdstatement = awb.updateclaim(awbid, \"P1\", wdid, \"string\")",
"lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId'] for awbid in awb.wdmappings: wdid = awb.wdmappings[awbid] if awbid.startswith('L') and",
"substantibo, Q8: aditza with open(infilename, encoding=\"utf-8\") as csvfile: sourcedict = csv.DictReader(csvfile) lex_elh =",
"in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId'] for awbid in awb.wdmappings: wdid = awb.wdmappings[awbid] if",
"# Q7: substantibo, Q8: aditza with open(infilename, encoding=\"utf-8\") as csvfile: sourcedict = csv.DictReader(csvfile)",
"= {} for row in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId'] for awbid in awb.wdmappings:",
"Q7: substantibo, Q8: aditza with open(infilename, encoding=\"utf-8\") as csvfile: sourcedict = csv.DictReader(csvfile) lex_elh",
"lex_elh = {} for row in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId'] for awbid in",
"awb infilename = config.datafolder+'wikidata/wdlid_ElhId.csv' resourceitem = \"Q19\" #Q19: Elhuyar #positem = \"Q8\" #",
"= awb.wdmappings[awbid] if awbid.startswith('L') and wdid in lex_elh: wdstatement = awb.updateclaim(awbid, \"P1\", wdid,",
"and wdid in lex_elh: wdstatement = awb.updateclaim(awbid, \"P1\", wdid, \"string\") quali = awb.setqualifier(awbid,",
"= config.datafolder+'wikidata/wdlid_ElhId.csv' resourceitem = \"Q19\" #Q19: Elhuyar #positem = \"Q8\" # Q7: substantibo,",
"row in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId'] for awbid in awb.wdmappings: wdid = awb.wdmappings[awbid]",
"= awb.updateclaim(awbid, \"P1\", wdid, \"string\") quali = awb.setqualifier(awbid, \"P1\", wdstatement, \"P7\", lex_elh[wdid], \"string\")",
"Elhuyar #positem = \"Q8\" # Q7: substantibo, Q8: aditza with open(infilename, encoding=\"utf-8\") as",
"#positem = \"Q8\" # Q7: substantibo, Q8: aditza with open(infilename, encoding=\"utf-8\") as csvfile:",
"sourcedict = csv.DictReader(csvfile) lex_elh = {} for row in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId']",
"= csv.DictReader(csvfile) lex_elh = {} for row in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")] = row['ElhId'] for",
"= row['ElhId'] for awbid in awb.wdmappings: wdid = awb.wdmappings[awbid] if awbid.startswith('L') and wdid",
"lex_elh: wdstatement = awb.updateclaim(awbid, \"P1\", wdid, \"string\") quali = awb.setqualifier(awbid, \"P1\", wdstatement, \"P7\",",
"\"Q19\" #Q19: Elhuyar #positem = \"Q8\" # Q7: substantibo, Q8: aditza with open(infilename,",
"config import awb infilename = config.datafolder+'wikidata/wdlid_ElhId.csv' resourceitem = \"Q19\" #Q19: Elhuyar #positem =",
"wdid = awb.wdmappings[awbid] if awbid.startswith('L') and wdid in lex_elh: wdstatement = awb.updateclaim(awbid, \"P1\",",
"import csv import config import awb infilename = config.datafolder+'wikidata/wdlid_ElhId.csv' resourceitem = \"Q19\" #Q19:",
"resourceitem = \"Q19\" #Q19: Elhuyar #positem = \"Q8\" # Q7: substantibo, Q8: aditza",
"in lex_elh: wdstatement = awb.updateclaim(awbid, \"P1\", wdid, \"string\") quali = awb.setqualifier(awbid, \"P1\", wdstatement,",
"row['ElhId'] for awbid in awb.wdmappings: wdid = awb.wdmappings[awbid] if awbid.startswith('L') and wdid in",
"infilename = config.datafolder+'wikidata/wdlid_ElhId.csv' resourceitem = \"Q19\" #Q19: Elhuyar #positem = \"Q8\" # Q7:",
"= \"Q8\" # Q7: substantibo, Q8: aditza with open(infilename, encoding=\"utf-8\") as csvfile: sourcedict",
"encoding=\"utf-8\") as csvfile: sourcedict = csv.DictReader(csvfile) lex_elh = {} for row in sourcedict:",
"awbid in awb.wdmappings: wdid = awb.wdmappings[awbid] if awbid.startswith('L') and wdid in lex_elh: wdstatement",
"for awbid in awb.wdmappings: wdid = awb.wdmappings[awbid] if awbid.startswith('L') and wdid in lex_elh:",
"import awb infilename = config.datafolder+'wikidata/wdlid_ElhId.csv' resourceitem = \"Q19\" #Q19: Elhuyar #positem = \"Q8\"",
"as csvfile: sourcedict = csv.DictReader(csvfile) lex_elh = {} for row in sourcedict: lex_elh[row['lexemeId'].replace(\"http://www.wikidata.org/entity/\",\"\")]",
"aditza with open(infilename, encoding=\"utf-8\") as csvfile: sourcedict = csv.DictReader(csvfile) lex_elh = {} for",
"open(infilename, encoding=\"utf-8\") as csvfile: sourcedict = csv.DictReader(csvfile) lex_elh = {} for row in",
"wdid in lex_elh: wdstatement = awb.updateclaim(awbid, \"P1\", wdid, \"string\") quali = awb.setqualifier(awbid, \"P1\","
] |
[
"casim.calculations import word_entropy def test_word_entropy(): test_arr = np.array([1, 0, 0, 1, 1, 0,",
"numpy as np from casim.calculations import word_entropy def test_word_entropy(): test_arr = np.array([1, 0,",
"def test_word_entropy(): test_arr = np.array([1, 0, 0, 1, 1, 0, 1, 0]) assert",
"test_word_entropy(): test_arr = np.array([1, 0, 0, 1, 1, 0, 1, 0]) assert np.round(word_entropy(test_arr,",
"= np.array([1, 0, 0, 1, 1, 0, 1, 0]) assert np.round(word_entropy(test_arr, 3), decimals=1)",
"np from casim.calculations import word_entropy def test_word_entropy(): test_arr = np.array([1, 0, 0, 1,",
"import word_entropy def test_word_entropy(): test_arr = np.array([1, 0, 0, 1, 1, 0, 1,",
"0, 0, 1, 1, 0, 1, 0]) assert np.round(word_entropy(test_arr, 3), decimals=1) == 2.5",
"import numpy as np from casim.calculations import word_entropy def test_word_entropy(): test_arr = np.array([1,",
"test_arr = np.array([1, 0, 0, 1, 1, 0, 1, 0]) assert np.round(word_entropy(test_arr, 3),",
"word_entropy def test_word_entropy(): test_arr = np.array([1, 0, 0, 1, 1, 0, 1, 0])",
"np.array([1, 0, 0, 1, 1, 0, 1, 0]) assert np.round(word_entropy(test_arr, 3), decimals=1) ==",
"as np from casim.calculations import word_entropy def test_word_entropy(): test_arr = np.array([1, 0, 0,",
"from casim.calculations import word_entropy def test_word_entropy(): test_arr = np.array([1, 0, 0, 1, 1,"
] |
[
"), migrations.AddField( model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ), migrations.AddField(",
"), migrations.AddField( model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ), migrations.AddField( model_name='recipientprofile', name='prisons', field=models.ManyToManyField(related_name='recipients', to='prison.Prison'), ),",
"10:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('prison', '0016_auto_20171121_1110'),",
"<reponame>ministryofjustice/mtp-api # Generated by Django 2.0.8 on 2018-10-03 10:17 from django.db import migrations,",
"Migration(migrations.Migration): dependencies = [ ('prison', '0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'), ] operations = [ migrations.AddField(",
"= [ ('prison', '0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'), ] operations = [ migrations.AddField( model_name='prisonerprofile', name='disbursement_count',",
"operations = [ migrations.AddField( model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0), ),",
"name='disbursement_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'),",
"field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ),",
"2018-10-03 10:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('prison',",
"Generated by Django 2.0.8 on 2018-10-03 10:17 from django.db import migrations, models class",
"model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ), migrations.AddField( model_name='recipientprofile', name='prisons',",
"field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ), migrations.AddField( model_name='recipientprofile', name='prisons', field=models.ManyToManyField(related_name='recipients', to='prison.Prison'), ), migrations.AlterField( model_name='prisonerprofile', name='prisoner_dob', field=models.DateField(blank=True,",
"'0017_auto_20180914_1613'), ] operations = [ migrations.AddField( model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='disbursement_total',",
"model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners',",
"migrations.AddField( model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ), migrations.AddField( model_name='recipientprofile', name='prisons', field=models.ManyToManyField(related_name='recipients', to='prison.Prison'), ), migrations.AlterField(",
"model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ), migrations.AddField( model_name='recipientprofile', name='prisons', field=models.ManyToManyField(related_name='recipients', to='prison.Prison'), ), migrations.AlterField( model_name='prisonerprofile',",
"[ migrations.AddField( model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile',",
"migrations.AddField( model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ), migrations.AddField( model_name='recipientprofile',",
"('prison', '0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'), ] operations = [ migrations.AddField( model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0), ),",
"on 2018-10-03 10:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('prison', '0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'), ] operations",
"[ ('prison', '0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'), ] operations = [ migrations.AddField( model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0),",
"name='disbursement_total', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ), migrations.AddField( model_name='recipientprofile', name='prisons', field=models.ManyToManyField(related_name='recipients',",
"] operations = [ migrations.AddField( model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0),",
"= [ migrations.AddField( model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0), ), migrations.AddField(",
"dependencies = [ ('prison', '0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'), ] operations = [ migrations.AddField( model_name='prisonerprofile',",
"('security', '0017_auto_20180914_1613'), ] operations = [ migrations.AddField( model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile',",
"name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ), migrations.AddField( model_name='recipientprofile', name='prisons', field=models.ManyToManyField(related_name='recipients', to='prison.Prison'), ), migrations.AlterField( model_name='prisonerprofile', name='prisoner_dob',",
"migrations.AddField( model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='disbursement_total', field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='recipients',",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('prison', '0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'),",
"migrations.AddField( model_name='recipientprofile', name='prisons', field=models.ManyToManyField(related_name='recipients', to='prison.Prison'), ), migrations.AlterField( model_name='prisonerprofile', name='prisoner_dob', field=models.DateField(blank=True, null=True), ), ]",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('prison', '0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'), ]",
"# Generated by Django 2.0.8 on 2018-10-03 10:17 from django.db import migrations, models",
"Django 2.0.8 on 2018-10-03 10:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"class Migration(migrations.Migration): dependencies = [ ('prison', '0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'), ] operations = [",
"), migrations.AddField( model_name='recipientprofile', name='prisons', field=models.ManyToManyField(related_name='recipients', to='prison.Prison'), ), migrations.AlterField( model_name='prisonerprofile', name='prisoner_dob', field=models.DateField(blank=True, null=True), ),",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('prison', '0016_auto_20171121_1110'), ('security',",
"to='security.RecipientProfile'), ), migrations.AddField( model_name='recipientprofile', name='prisons', field=models.ManyToManyField(related_name='recipients', to='prison.Prison'), ), migrations.AlterField( model_name='prisonerprofile', name='prisoner_dob', field=models.DateField(blank=True, null=True),",
"models class Migration(migrations.Migration): dependencies = [ ('prison', '0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'), ] operations =",
"field=models.IntegerField(default=0), ), migrations.AddField( model_name='prisonerprofile', name='recipients', field=models.ManyToManyField(related_name='prisoners', to='security.RecipientProfile'), ), migrations.AddField( model_name='recipientprofile', name='prisons', field=models.ManyToManyField(related_name='recipients', to='prison.Prison'),",
"by Django 2.0.8 on 2018-10-03 10:17 from django.db import migrations, models class Migration(migrations.Migration):",
"2.0.8 on 2018-10-03 10:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"'0016_auto_20171121_1110'), ('security', '0017_auto_20180914_1613'), ] operations = [ migrations.AddField( model_name='prisonerprofile', name='disbursement_count', field=models.IntegerField(default=0), ), migrations.AddField("
] |
[
"BACKGROUND = (33, 47, 60) #initial game setup def get_events(): global running for",
"pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() game_window = Game_window(window, 150, 180)",
"pygame.event.get(): if event.type == pygame.QUIT: running = False def update(): game_window.update() def draw():",
"HEIGHT)) clock = pygame.time.Clock() game_window = Game_window(window, 150, 180) running = True while",
"window.fill(BACKGROUND) game_window.draw() pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() game_window = Game_window(window,",
"(33, 47, 60) #initial game setup def get_events(): global running for event in",
"game_window_class import * WIDTH, HEIGHT = 800, 800 BACKGROUND = (33, 47, 60)",
"window = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() game_window = Game_window(window, 150, 180) running",
"= pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() game_window = Game_window(window, 150, 180) running =",
"game_window.update() def draw(): window.fill(BACKGROUND) game_window.draw() pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock()",
"= pygame.time.Clock() game_window = Game_window(window, 150, 180) running = True while running: get_events()",
"import pygame import sys from game_window_class import * WIDTH, HEIGHT = 800, 800",
"clock = pygame.time.Clock() game_window = Game_window(window, 150, 180) running = True while running:",
"60) #initial game setup def get_events(): global running for event in pygame.event.get(): if",
"= False def update(): game_window.update() def draw(): window.fill(BACKGROUND) game_window.draw() pygame.init() window = pygame.display.set_mode((WIDTH,",
"Game_window(window, 150, 180) running = True while running: get_events() update() draw() pygame.display.update() clock.tick()",
"pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() game_window = Game_window(window, 150, 180) running = True",
"150, 180) running = True while running: get_events() update() draw() pygame.display.update() clock.tick() pygame.quit()",
"<filename>main.py import pygame import sys from game_window_class import * WIDTH, HEIGHT = 800,",
"game setup def get_events(): global running for event in pygame.event.get(): if event.type ==",
"False def update(): game_window.update() def draw(): window.fill(BACKGROUND) game_window.draw() pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT))",
"800 BACKGROUND = (33, 47, 60) #initial game setup def get_events(): global running",
"for event in pygame.event.get(): if event.type == pygame.QUIT: running = False def update():",
"800, 800 BACKGROUND = (33, 47, 60) #initial game setup def get_events(): global",
"event.type == pygame.QUIT: running = False def update(): game_window.update() def draw(): window.fill(BACKGROUND) game_window.draw()",
"pygame.QUIT: running = False def update(): game_window.update() def draw(): window.fill(BACKGROUND) game_window.draw() pygame.init() window",
"event in pygame.event.get(): if event.type == pygame.QUIT: running = False def update(): game_window.update()",
"#initial game setup def get_events(): global running for event in pygame.event.get(): if event.type",
"import sys from game_window_class import * WIDTH, HEIGHT = 800, 800 BACKGROUND =",
"= (33, 47, 60) #initial game setup def get_events(): global running for event",
"from game_window_class import * WIDTH, HEIGHT = 800, 800 BACKGROUND = (33, 47,",
"= Game_window(window, 150, 180) running = True while running: get_events() update() draw() pygame.display.update()",
"180) running = True while running: get_events() update() draw() pygame.display.update() clock.tick() pygame.quit() sys.exit()",
"def get_events(): global running for event in pygame.event.get(): if event.type == pygame.QUIT: running",
"global running for event in pygame.event.get(): if event.type == pygame.QUIT: running = False",
"pygame.time.Clock() game_window = Game_window(window, 150, 180) running = True while running: get_events() update()",
"game_window = Game_window(window, 150, 180) running = True while running: get_events() update() draw()",
"draw(): window.fill(BACKGROUND) game_window.draw() pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() game_window =",
"in pygame.event.get(): if event.type == pygame.QUIT: running = False def update(): game_window.update() def",
"== pygame.QUIT: running = False def update(): game_window.update() def draw(): window.fill(BACKGROUND) game_window.draw() pygame.init()",
"= 800, 800 BACKGROUND = (33, 47, 60) #initial game setup def get_events():",
"import * WIDTH, HEIGHT = 800, 800 BACKGROUND = (33, 47, 60) #initial",
"if event.type == pygame.QUIT: running = False def update(): game_window.update() def draw(): window.fill(BACKGROUND)",
"HEIGHT = 800, 800 BACKGROUND = (33, 47, 60) #initial game setup def",
"def update(): game_window.update() def draw(): window.fill(BACKGROUND) game_window.draw() pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) clock",
"sys from game_window_class import * WIDTH, HEIGHT = 800, 800 BACKGROUND = (33,",
"game_window.draw() pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() game_window = Game_window(window, 150,",
"get_events(): global running for event in pygame.event.get(): if event.type == pygame.QUIT: running =",
"update(): game_window.update() def draw(): window.fill(BACKGROUND) game_window.draw() pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) clock =",
"pygame import sys from game_window_class import * WIDTH, HEIGHT = 800, 800 BACKGROUND",
"WIDTH, HEIGHT = 800, 800 BACKGROUND = (33, 47, 60) #initial game setup",
"47, 60) #initial game setup def get_events(): global running for event in pygame.event.get():",
"running for event in pygame.event.get(): if event.type == pygame.QUIT: running = False def",
"setup def get_events(): global running for event in pygame.event.get(): if event.type == pygame.QUIT:",
"def draw(): window.fill(BACKGROUND) game_window.draw() pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() game_window",
"running = False def update(): game_window.update() def draw(): window.fill(BACKGROUND) game_window.draw() pygame.init() window =",
"* WIDTH, HEIGHT = 800, 800 BACKGROUND = (33, 47, 60) #initial game"
] |
[
"for char in new_expr: if char not in EvaluateExpression.valid_char: self.expr = \"\" return",
"char not in EvaluateExpression.valid_char: self.expr = \"\" return self.expr = new_expr def insert_space(self):",
"len(self._items) class EvaluateExpression: valid_char = '0123456789+-*/() ' valid_num = '0123456789' valid_operator = '+-*/()'",
"operator_stack = Stack() expression = self.insert_space() tokens = expression.split() for el in tokens:",
"== \"*\" or el == \"/\": while operator_stack.peek() in \"*/\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el)",
"== \"-\": ans = b - a elif operator == \"*\": ans =",
"self._items.append(item) def pop(self): if len(self._items): return self._items.pop() def peek(self): if len(self._items): return self._items[-1]",
"if char not in EvaluateExpression.valid_char: self.expr = \"\" return self.expr = new_expr def",
"def insert_space(self): s = \"\" for char in self.expr: if char in EvaluateExpression.valid_operator:",
"left[i] i += 1 k += 1 while j < len(right): array[k] =",
"+= 1 k += 1 # Remaining elements while i < len(left): array[k]",
"len(array) mid = len(array) // 2 left = array[start:mid] right = array[mid:end] i,",
"while i < len(left): array[k] = left[i] i += 1 k += 1",
"return len(self._items) class EvaluateExpression: valid_char = '0123456789+-*/() ' valid_num = '0123456789' valid_operator =",
"\"()\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"*\" or el == \"/\": while",
"while i < len(left) and j < len(right): if byfunc(left[i]) <= byfunc(right[j]): array[k]",
"item): self._items.append(item) def pop(self): if len(self._items): return self._items.pop() def peek(self): if len(self._items): return",
"s def process_operator(self, operand_stack, operator_stack): a = operand_stack.pop() operator = operator_stack.pop() b =",
"[] def push(self, item): self._items.append(item) def pop(self): if len(self._items): return self._items.pop() def peek(self):",
"else: s += char return s def process_operator(self, operand_stack, operator_stack): a = operand_stack.pop()",
"= challenge.records times = [r for r in records] mergesort(times, lambda x: x.elapsed_time)",
"or el == \"/\": while operator_stack.peek() in \"*/\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el",
"right[j] j += 1 k += 1 # Remaining elements while i <",
"> 1: start, end = 0, len(array) mid = len(array) // 2 left",
"1 k += 1 class Stack: def __init__(self): self._items = [] def push(self,",
"def pop(self): if len(self._items): return self._items.pop() def peek(self): if len(self._items): return self._items[-1] @property",
"__init__(self, string=\"\"): self.expr = string @property def expression(self): return self.expr @expression.setter def expression(self,",
"self.expr = \"\" return self.expr = new_expr def insert_space(self): s = \"\" for",
"i, j, k = 0, 0, 0 # Sort recursively (I.e. Starting from",
"Stack() operator_stack = Stack() expression = self.insert_space() tokens = expression.split() for el in",
"in EvaluateExpression.valid_operator: s += f\" {char} \" else: s += char return s",
"== \"-\": while not operator_stack.is_empty and operator_stack.peek() not in \"()\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el)",
"recursively (I.e. Starting from 2 elements) mergesort(left, byfunc=byfunc) mergesort(right, byfunc=byfunc) # Add to",
"tokens: try: # Note: \"10.5\" will NOT be able to be converted into",
"byfunc=byfunc) mergesort(right, byfunc=byfunc) # Add to array in-place while i < len(left) and",
"times = [r for r in records] mergesort(times, lambda x: x.elapsed_time) return times[:3]",
"left[i] i += 1 else: array[k] = right[j] j += 1 k +=",
"and j < len(right): if byfunc(left[i]) <= byfunc(right[j]): array[k] = left[i] i +=",
"j < len(right): if byfunc(left[i]) <= byfunc(right[j]): array[k] = left[i] i += 1",
"to be converted into an int my_int = int(el) operand_stack.push(my_int) except: if el",
"byfunc=byfunc) # Add to array in-place while i < len(left) and j <",
"\"(\": self.process_operator(operand_stack, operator_stack) while operator_stack.size > 0: if operator_stack.peek() in \"()\": operator_stack.pop() continue",
"b // a operand_stack.push(ans) def evaluate(self): operand_stack = Stack() operator_stack = Stack() expression",
"(I.e. Starting from 2 elements) mergesort(left, byfunc=byfunc) mergesort(right, byfunc=byfunc) # Add to array",
"0, 0 # Sort recursively (I.e. Starting from 2 elements) mergesort(left, byfunc=byfunc) mergesort(right,",
"char in self.expr: if char in EvaluateExpression.valid_operator: s += f\" {char} \" else:",
"@property def size(self): return len(self._items) class EvaluateExpression: valid_char = '0123456789+-*/() ' valid_num =",
"el == \")\": while operator_stack.peek() != \"(\": self.process_operator(operand_stack, operator_stack) while operator_stack.size > 0:",
"2 elements) mergesort(left, byfunc=byfunc) mergesort(right, byfunc=byfunc) # Add to array in-place while i",
"1 k += 1 while j < len(right): array[k] = right[j] j +=",
"+= 1 class Stack: def __init__(self): self._items = [] def push(self, item): self._items.append(item)",
"\"\" return self.expr = new_expr def insert_space(self): s = \"\" for char in",
"expression(self, new_expr): for char in new_expr: if char not in EvaluateExpression.valid_char: self.expr =",
"return s def process_operator(self, operand_stack, operator_stack): a = operand_stack.pop() operator = operator_stack.pop() b",
"Stack() expression = self.insert_space() tokens = expression.split() for el in tokens: try: #",
"len(right): if byfunc(left[i]) <= byfunc(right[j]): array[k] = left[i] i += 1 else: array[k]",
"# Note: \"10.5\" will NOT be able to be converted into an int",
"operand_stack = Stack() operator_stack = Stack() expression = self.insert_space() tokens = expression.split() for",
"ans = b + a elif operator == \"-\": ans = b -",
"len(left) and j < len(right): if byfunc(left[i]) <= byfunc(right[j]): array[k] = left[i] i",
"== \"/\": ans = b // a operand_stack.push(ans) def evaluate(self): operand_stack = Stack()",
"operator_stack.peek() not in \"()\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"*\" or el",
"operand_stack.push(ans) def evaluate(self): operand_stack = Stack() operator_stack = Stack() expression = self.insert_space() tokens",
"left = array[start:mid] right = array[mid:end] i, j, k = 0, 0, 0",
"if char in EvaluateExpression.valid_operator: s += f\" {char} \" else: s += char",
"expression.split() for el in tokens: try: # Note: \"10.5\" will NOT be able",
"a elif operator == \"-\": ans = b - a elif operator ==",
"k += 1 class Stack: def __init__(self): self._items = [] def push(self, item):",
"len(array) // 2 left = array[start:mid] right = array[mid:end] i, j, k =",
"# Add to array in-place while i < len(left) and j < len(right):",
"def expression(self, new_expr): for char in new_expr: if char not in EvaluateExpression.valid_char: self.expr",
"= self.insert_space() tokens = expression.split() for el in tokens: try: # Note: \"10.5\"",
"= right[j] j += 1 k += 1 # Remaining elements while i",
"if byfunc(left[i]) <= byfunc(right[j]): array[k] = left[i] i += 1 else: array[k] =",
"\"/\": while operator_stack.peek() in \"*/\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"(\": operator_stack.push(el)",
"return self._items[-1] @property def is_empty(self): return len(self._items) == 0 @property def size(self): return",
"= int(el) operand_stack.push(my_int) except: if el == \"+\" or el == \"-\": while",
"el == \"+\" or el == \"-\": while not operator_stack.is_empty and operator_stack.peek() not",
"array[mid:end] i, j, k = 0, 0, 0 # Sort recursively (I.e. Starting",
"f\" {char} \" else: s += char return s def process_operator(self, operand_stack, operator_stack):",
"+= 1 while j < len(right): array[k] = right[j] j += 1 k",
"'+-*/()' def __init__(self, string=\"\"): self.expr = string @property def expression(self): return self.expr @expression.setter",
"- a elif operator == \"*\": ans = b * a elif operator",
"def process_operator(self, operand_stack, operator_stack): a = operand_stack.pop() operator = operator_stack.pop() b = operand_stack.pop()",
"get_smallest_three(challenge): records = challenge.records times = [r for r in records] mergesort(times, lambda",
"def mergesort(array, byfunc=None): if len(array) > 1: start, end = 0, len(array) mid",
"from 2 elements) mergesort(left, byfunc=byfunc) mergesort(right, byfunc=byfunc) # Add to array in-place while",
"= '+-*/()' def __init__(self, string=\"\"): self.expr = string @property def expression(self): return self.expr",
"operator_stack.size > 0: if operator_stack.peek() in \"()\": operator_stack.pop() continue self.process_operator(operand_stack, operator_stack) return operand_stack.peek()",
"be able to be converted into an int my_int = int(el) operand_stack.push(my_int) except:",
"operator_stack.push(el) elif el == \")\": while operator_stack.peek() != \"(\": self.process_operator(operand_stack, operator_stack) while operator_stack.size",
"= 0, len(array) mid = len(array) // 2 left = array[start:mid] right =",
"self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"(\": operator_stack.push(el) elif el == \")\": while",
"len(array) > 1: start, end = 0, len(array) mid = len(array) // 2",
"class EvaluateExpression: valid_char = '0123456789+-*/() ' valid_num = '0123456789' valid_operator = '+-*/()' def",
"\" else: s += char return s def process_operator(self, operand_stack, operator_stack): a =",
"+ a elif operator == \"-\": ans = b - a elif operator",
"and operator_stack.peek() not in \"()\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"*\" or",
"in self.expr: if char in EvaluateExpression.valid_operator: s += f\" {char} \" else: s",
"not operator_stack.is_empty and operator_stack.peek() not in \"()\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el ==",
"= b + a elif operator == \"-\": ans = b - a",
"= left[i] i += 1 k += 1 while j < len(right): array[k]",
"my_int = int(el) operand_stack.push(my_int) except: if el == \"+\" or el == \"-\":",
"{char} \" else: s += char return s def process_operator(self, operand_stack, operator_stack): a",
"else: array[k] = right[j] j += 1 k += 1 # Remaining elements",
"+= char return s def process_operator(self, operand_stack, operator_stack): a = operand_stack.pop() operator =",
"el == \"-\": while not operator_stack.is_empty and operator_stack.peek() not in \"()\": self.process_operator(operand_stack, operator_stack)",
"elif el == \"(\": operator_stack.push(el) elif el == \")\": while operator_stack.peek() != \"(\":",
"operator_stack.peek() in \"()\": operator_stack.pop() continue self.process_operator(operand_stack, operator_stack) return operand_stack.peek() def get_smallest_three(challenge): records =",
"push(self, item): self._items.append(item) def pop(self): if len(self._items): return self._items.pop() def peek(self): if len(self._items):",
"!= \"(\": self.process_operator(operand_stack, operator_stack) while operator_stack.size > 0: if operator_stack.peek() in \"()\": operator_stack.pop()",
"while j < len(right): array[k] = right[j] j += 1 k += 1",
"continue self.process_operator(operand_stack, operator_stack) return operand_stack.peek() def get_smallest_three(challenge): records = challenge.records times = [r",
"in new_expr: if char not in EvaluateExpression.valid_char: self.expr = \"\" return self.expr =",
"== \")\": while operator_stack.peek() != \"(\": self.process_operator(operand_stack, operator_stack) while operator_stack.size > 0: if",
"operator == \"/\": ans = b // a operand_stack.push(ans) def evaluate(self): operand_stack =",
"operator_stack.pop() b = operand_stack.pop() if operator == \"+\": ans = b + a",
"+= 1 k += 1 while j < len(right): array[k] = right[j] j",
"1 class Stack: def __init__(self): self._items = [] def push(self, item): self._items.append(item) def",
"int my_int = int(el) operand_stack.push(my_int) except: if el == \"+\" or el ==",
"\")\": while operator_stack.peek() != \"(\": self.process_operator(operand_stack, operator_stack) while operator_stack.size > 0: if operator_stack.peek()",
"return len(self._items) == 0 @property def size(self): return len(self._items) class EvaluateExpression: valid_char =",
"operator == \"+\": ans = b + a elif operator == \"-\": ans",
"elif el == \"*\" or el == \"/\": while operator_stack.peek() in \"*/\": self.process_operator(operand_stack,",
"elif operator == \"/\": ans = b // a operand_stack.push(ans) def evaluate(self): operand_stack",
"+= f\" {char} \" else: s += char return s def process_operator(self, operand_stack,",
"operator_stack.peek() in \"*/\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"(\": operator_stack.push(el) elif el",
"s += char return s def process_operator(self, operand_stack, operator_stack): a = operand_stack.pop() operator",
"> 0: if operator_stack.peek() in \"()\": operator_stack.pop() continue self.process_operator(operand_stack, operator_stack) return operand_stack.peek() def",
"def __init__(self, string=\"\"): self.expr = string @property def expression(self): return self.expr @expression.setter def",
"new_expr def insert_space(self): s = \"\" for char in self.expr: if char in",
"def evaluate(self): operand_stack = Stack() operator_stack = Stack() expression = self.insert_space() tokens =",
"array[k] = right[j] j += 1 k += 1 # Remaining elements while",
"EvaluateExpression: valid_char = '0123456789+-*/() ' valid_num = '0123456789' valid_operator = '+-*/()' def __init__(self,",
"Remaining elements while i < len(left): array[k] = left[i] i += 1 k",
"b + a elif operator == \"-\": ans = b - a elif",
"b * a elif operator == \"/\": ans = b // a operand_stack.push(ans)",
"or el == \"-\": while not operator_stack.is_empty and operator_stack.peek() not in \"()\": self.process_operator(operand_stack,",
"'0123456789+-*/() ' valid_num = '0123456789' valid_operator = '+-*/()' def __init__(self, string=\"\"): self.expr =",
"= Stack() operator_stack = Stack() expression = self.insert_space() tokens = expression.split() for el",
"elif el == \")\": while operator_stack.peek() != \"(\": self.process_operator(operand_stack, operator_stack) while operator_stack.size >",
"while operator_stack.size > 0: if operator_stack.peek() in \"()\": operator_stack.pop() continue self.process_operator(operand_stack, operator_stack) return",
"' valid_num = '0123456789' valid_operator = '+-*/()' def __init__(self, string=\"\"): self.expr = string",
"i += 1 else: array[k] = right[j] j += 1 k += 1",
"a operand_stack.push(ans) def evaluate(self): operand_stack = Stack() operator_stack = Stack() expression = self.insert_space()",
"== \"/\": while operator_stack.peek() in \"*/\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"(\":",
"0, 0, 0 # Sort recursively (I.e. Starting from 2 elements) mergesort(left, byfunc=byfunc)",
"\"*\": ans = b * a elif operator == \"/\": ans = b",
"while operator_stack.peek() in \"*/\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"(\": operator_stack.push(el) elif",
"evaluate(self): operand_stack = Stack() operator_stack = Stack() expression = self.insert_space() tokens = expression.split()",
"= b * a elif operator == \"/\": ans = b // a",
"= 0, 0, 0 # Sort recursively (I.e. Starting from 2 elements) mergesort(left,",
"<= byfunc(right[j]): array[k] = left[i] i += 1 else: array[k] = right[j] j",
"'0123456789' valid_operator = '+-*/()' def __init__(self, string=\"\"): self.expr = string @property def expression(self):",
"if el == \"+\" or el == \"-\": while not operator_stack.is_empty and operator_stack.peek()",
"start, end = 0, len(array) mid = len(array) // 2 left = array[start:mid]",
"def expression(self): return self.expr @expression.setter def expression(self, new_expr): for char in new_expr: if",
"mergesort(right, byfunc=byfunc) # Add to array in-place while i < len(left) and j",
"+= 1 else: array[k] = right[j] j += 1 k += 1 #",
"an int my_int = int(el) operand_stack.push(my_int) except: if el == \"+\" or el",
"el == \"/\": while operator_stack.peek() in \"*/\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el ==",
"self.expr: if char in EvaluateExpression.valid_operator: s += f\" {char} \" else: s +=",
"a = operand_stack.pop() operator = operator_stack.pop() b = operand_stack.pop() if operator == \"+\":",
"\"+\": ans = b + a elif operator == \"-\": ans = b",
"def __init__(self): self._items = [] def push(self, item): self._items.append(item) def pop(self): if len(self._items):",
"b - a elif operator == \"*\": ans = b * a elif",
"ans = b // a operand_stack.push(ans) def evaluate(self): operand_stack = Stack() operator_stack =",
"j += 1 k += 1 # Remaining elements while i < len(left):",
"\"10.5\" will NOT be able to be converted into an int my_int =",
"k += 1 # Remaining elements while i < len(left): array[k] = left[i]",
"= Stack() expression = self.insert_space() tokens = expression.split() for el in tokens: try:",
"= array[mid:end] i, j, k = 0, 0, 0 # Sort recursively (I.e.",
"array in-place while i < len(left) and j < len(right): if byfunc(left[i]) <=",
"byfunc(right[j]): array[k] = left[i] i += 1 else: array[k] = right[j] j +=",
"elements while i < len(left): array[k] = left[i] i += 1 k +=",
"self.expr = string @property def expression(self): return self.expr @expression.setter def expression(self, new_expr): for",
"while operator_stack.peek() != \"(\": self.process_operator(operand_stack, operator_stack) while operator_stack.size > 0: if operator_stack.peek() in",
"self.process_operator(operand_stack, operator_stack) return operand_stack.peek() def get_smallest_three(challenge): records = challenge.records times = [r for",
"process_operator(self, operand_stack, operator_stack): a = operand_stack.pop() operator = operator_stack.pop() b = operand_stack.pop() if",
"j += 1 k += 1 class Stack: def __init__(self): self._items = []",
"= expression.split() for el in tokens: try: # Note: \"10.5\" will NOT be",
"0 @property def size(self): return len(self._items) class EvaluateExpression: valid_char = '0123456789+-*/() ' valid_num",
"self.expr @expression.setter def expression(self, new_expr): for char in new_expr: if char not in",
"is_empty(self): return len(self._items) == 0 @property def size(self): return len(self._items) class EvaluateExpression: valid_char",
"= operator_stack.pop() b = operand_stack.pop() if operator == \"+\": ans = b +",
"ans = b - a elif operator == \"*\": ans = b *",
"len(right): array[k] = right[j] j += 1 k += 1 class Stack: def",
"char in EvaluateExpression.valid_operator: s += f\" {char} \" else: s += char return",
"if operator == \"+\": ans = b + a elif operator == \"-\":",
"len(left): array[k] = left[i] i += 1 k += 1 while j <",
"char return s def process_operator(self, operand_stack, operator_stack): a = operand_stack.pop() operator = operator_stack.pop()",
"def is_empty(self): return len(self._items) == 0 @property def size(self): return len(self._items) class EvaluateExpression:",
"operator = operator_stack.pop() b = operand_stack.pop() if operator == \"+\": ans = b",
"\"-\": ans = b - a elif operator == \"*\": ans = b",
"return self._items.pop() def peek(self): if len(self._items): return self._items[-1] @property def is_empty(self): return len(self._items)",
"valid_num = '0123456789' valid_operator = '+-*/()' def __init__(self, string=\"\"): self.expr = string @property",
"byfunc=None): if len(array) > 1: start, end = 0, len(array) mid = len(array)",
"operator_stack): a = operand_stack.pop() operator = operator_stack.pop() b = operand_stack.pop() if operator ==",
"\"/\": ans = b // a operand_stack.push(ans) def evaluate(self): operand_stack = Stack() operator_stack",
"= string @property def expression(self): return self.expr @expression.setter def expression(self, new_expr): for char",
"expression(self): return self.expr @expression.setter def expression(self, new_expr): for char in new_expr: if char",
"self._items[-1] @property def is_empty(self): return len(self._items) == 0 @property def size(self): return len(self._items)",
"self.insert_space() tokens = expression.split() for el in tokens: try: # Note: \"10.5\" will",
"mid = len(array) // 2 left = array[start:mid] right = array[mid:end] i, j,",
"end = 0, len(array) mid = len(array) // 2 left = array[start:mid] right",
"will NOT be able to be converted into an int my_int = int(el)",
"el == \"(\": operator_stack.push(el) elif el == \")\": while operator_stack.peek() != \"(\": self.process_operator(operand_stack,",
"return operand_stack.peek() def get_smallest_three(challenge): records = challenge.records times = [r for r in",
"1 while j < len(right): array[k] = right[j] j += 1 k +=",
"Starting from 2 elements) mergesort(left, byfunc=byfunc) mergesort(right, byfunc=byfunc) # Add to array in-place",
"1 else: array[k] = right[j] j += 1 k += 1 # Remaining",
"= [] def push(self, item): self._items.append(item) def pop(self): if len(self._items): return self._items.pop() def",
"NOT be able to be converted into an int my_int = int(el) operand_stack.push(my_int)",
"EvaluateExpression.valid_char: self.expr = \"\" return self.expr = new_expr def insert_space(self): s = \"\"",
"== \"+\" or el == \"-\": while not operator_stack.is_empty and operator_stack.peek() not in",
"operator_stack.push(el) elif el == \"*\" or el == \"/\": while operator_stack.peek() in \"*/\":",
"in-place while i < len(left) and j < len(right): if byfunc(left[i]) <= byfunc(right[j]):",
"= b // a operand_stack.push(ans) def evaluate(self): operand_stack = Stack() operator_stack = Stack()",
"operator_stack.peek() != \"(\": self.process_operator(operand_stack, operator_stack) while operator_stack.size > 0: if operator_stack.peek() in \"()\":",
"elif operator == \"-\": ans = b - a elif operator == \"*\":",
"be converted into an int my_int = int(el) operand_stack.push(my_int) except: if el ==",
"self._items = [] def push(self, item): self._items.append(item) def pop(self): if len(self._items): return self._items.pop()",
"while not operator_stack.is_empty and operator_stack.peek() not in \"()\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el",
"// 2 left = array[start:mid] right = array[mid:end] i, j, k = 0,",
"operand_stack, operator_stack): a = operand_stack.pop() operator = operator_stack.pop() b = operand_stack.pop() if operator",
"// a operand_stack.push(ans) def evaluate(self): operand_stack = Stack() operator_stack = Stack() expression =",
"operand_stack.peek() def get_smallest_three(challenge): records = challenge.records times = [r for r in records]",
"pop(self): if len(self._items): return self._items.pop() def peek(self): if len(self._items): return self._items[-1] @property def",
"expression = self.insert_space() tokens = expression.split() for el in tokens: try: # Note:",
"1 k += 1 # Remaining elements while i < len(left): array[k] =",
"def push(self, item): self._items.append(item) def pop(self): if len(self._items): return self._items.pop() def peek(self): if",
"s = \"\" for char in self.expr: if char in EvaluateExpression.valid_operator: s +=",
"<gh_stars>0 def mergesort(array, byfunc=None): if len(array) > 1: start, end = 0, len(array)",
"= left[i] i += 1 else: array[k] = right[j] j += 1 k",
"< len(left) and j < len(right): if byfunc(left[i]) <= byfunc(right[j]): array[k] = left[i]",
"operator_stack.is_empty and operator_stack.peek() not in \"()\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"*\"",
"k = 0, 0, 0 # Sort recursively (I.e. Starting from 2 elements)",
"i < len(left): array[k] = left[i] i += 1 k += 1 while",
"\"(\": operator_stack.push(el) elif el == \")\": while operator_stack.peek() != \"(\": self.process_operator(operand_stack, operator_stack) while",
"i += 1 k += 1 while j < len(right): array[k] = right[j]",
"in \"*/\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"(\": operator_stack.push(el) elif el ==",
"b = operand_stack.pop() if operator == \"+\": ans = b + a elif",
"j < len(right): array[k] = right[j] j += 1 k += 1 class",
"< len(left): array[k] = left[i] i += 1 k += 1 while j",
"in tokens: try: # Note: \"10.5\" will NOT be able to be converted",
"ans = b * a elif operator == \"/\": ans = b //",
"= \"\" for char in self.expr: if char in EvaluateExpression.valid_operator: s += f\"",
"for el in tokens: try: # Note: \"10.5\" will NOT be able to",
"in EvaluateExpression.valid_char: self.expr = \"\" return self.expr = new_expr def insert_space(self): s =",
"elif operator == \"*\": ans = b * a elif operator == \"/\":",
"k += 1 while j < len(right): array[k] = right[j] j += 1",
"self.process_operator(operand_stack, operator_stack) while operator_stack.size > 0: if operator_stack.peek() in \"()\": operator_stack.pop() continue self.process_operator(operand_stack,",
"= '0123456789' valid_operator = '+-*/()' def __init__(self, string=\"\"): self.expr = string @property def",
"i < len(left) and j < len(right): if byfunc(left[i]) <= byfunc(right[j]): array[k] =",
"class Stack: def __init__(self): self._items = [] def push(self, item): self._items.append(item) def pop(self):",
"int(el) operand_stack.push(my_int) except: if el == \"+\" or el == \"-\": while not",
"1 # Remaining elements while i < len(left): array[k] = left[i] i +=",
"right = array[mid:end] i, j, k = 0, 0, 0 # Sort recursively",
"\"()\": operator_stack.pop() continue self.process_operator(operand_stack, operator_stack) return operand_stack.peek() def get_smallest_three(challenge): records = challenge.records times",
"array[k] = right[j] j += 1 k += 1 class Stack: def __init__(self):",
"string=\"\"): self.expr = string @property def expression(self): return self.expr @expression.setter def expression(self, new_expr):",
"not in EvaluateExpression.valid_char: self.expr = \"\" return self.expr = new_expr def insert_space(self): s",
"a elif operator == \"/\": ans = b // a operand_stack.push(ans) def evaluate(self):",
"self._items.pop() def peek(self): if len(self._items): return self._items[-1] @property def is_empty(self): return len(self._items) ==",
"= right[j] j += 1 k += 1 class Stack: def __init__(self): self._items",
"@expression.setter def expression(self, new_expr): for char in new_expr: if char not in EvaluateExpression.valid_char:",
"def get_smallest_three(challenge): records = challenge.records times = [r for r in records] mergesort(times,",
"* a elif operator == \"/\": ans = b // a operand_stack.push(ans) def",
"valid_char = '0123456789+-*/() ' valid_num = '0123456789' valid_operator = '+-*/()' def __init__(self, string=\"\"):",
"\"-\": while not operator_stack.is_empty and operator_stack.peek() not in \"()\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif",
"__init__(self): self._items = [] def push(self, item): self._items.append(item) def pop(self): if len(self._items): return",
"new_expr: if char not in EvaluateExpression.valid_char: self.expr = \"\" return self.expr = new_expr",
"operator_stack) operator_stack.push(el) elif el == \"*\" or el == \"/\": while operator_stack.peek() in",
"operator == \"*\": ans = b * a elif operator == \"/\": ans",
"mergesort(left, byfunc=byfunc) mergesort(right, byfunc=byfunc) # Add to array in-place while i < len(left)",
"operator_stack.push(el) elif el == \"(\": operator_stack.push(el) elif el == \")\": while operator_stack.peek() !=",
"len(self._items): return self._items[-1] @property def is_empty(self): return len(self._items) == 0 @property def size(self):",
"not in \"()\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"*\" or el ==",
"if operator_stack.peek() in \"()\": operator_stack.pop() continue self.process_operator(operand_stack, operator_stack) return operand_stack.peek() def get_smallest_three(challenge): records",
"insert_space(self): s = \"\" for char in self.expr: if char in EvaluateExpression.valid_operator: s",
"challenge.records times = [r for r in records] mergesort(times, lambda x: x.elapsed_time) return",
"operator_stack) operator_stack.push(el) elif el == \"(\": operator_stack.push(el) elif el == \")\": while operator_stack.peek()",
"operator_stack) while operator_stack.size > 0: if operator_stack.peek() in \"()\": operator_stack.pop() continue self.process_operator(operand_stack, operator_stack)",
"# Remaining elements while i < len(left): array[k] = left[i] i += 1",
"el in tokens: try: # Note: \"10.5\" will NOT be able to be",
"+= 1 # Remaining elements while i < len(left): array[k] = left[i] i",
"Sort recursively (I.e. Starting from 2 elements) mergesort(left, byfunc=byfunc) mergesort(right, byfunc=byfunc) # Add",
"= operand_stack.pop() if operator == \"+\": ans = b + a elif operator",
"== \"*\": ans = b * a elif operator == \"/\": ans =",
"except: if el == \"+\" or el == \"-\": while not operator_stack.is_empty and",
"EvaluateExpression.valid_operator: s += f\" {char} \" else: s += char return s def",
"0 # Sort recursively (I.e. Starting from 2 elements) mergesort(left, byfunc=byfunc) mergesort(right, byfunc=byfunc)",
"records = challenge.records times = [r for r in records] mergesort(times, lambda x:",
"if len(self._items): return self._items[-1] @property def is_empty(self): return len(self._items) == 0 @property def",
"Note: \"10.5\" will NOT be able to be converted into an int my_int",
"= len(array) // 2 left = array[start:mid] right = array[mid:end] i, j, k",
"def size(self): return len(self._items) class EvaluateExpression: valid_char = '0123456789+-*/() ' valid_num = '0123456789'",
"Stack: def __init__(self): self._items = [] def push(self, item): self._items.append(item) def pop(self): if",
"elements) mergesort(left, byfunc=byfunc) mergesort(right, byfunc=byfunc) # Add to array in-place while i <",
"array[start:mid] right = array[mid:end] i, j, k = 0, 0, 0 # Sort",
"@property def expression(self): return self.expr @expression.setter def expression(self, new_expr): for char in new_expr:",
"= array[start:mid] right = array[mid:end] i, j, k = 0, 0, 0 #",
"= operand_stack.pop() operator = operator_stack.pop() b = operand_stack.pop() if operator == \"+\": ans",
"a elif operator == \"*\": ans = b * a elif operator ==",
"in \"()\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"*\" or el == \"/\":",
"\"\" for char in self.expr: if char in EvaluateExpression.valid_operator: s += f\" {char}",
"= b - a elif operator == \"*\": ans = b * a",
"self.expr = new_expr def insert_space(self): s = \"\" for char in self.expr: if",
"< len(right): if byfunc(left[i]) <= byfunc(right[j]): array[k] = left[i] i += 1 else:",
"operator_stack.pop() continue self.process_operator(operand_stack, operator_stack) return operand_stack.peek() def get_smallest_three(challenge): records = challenge.records times =",
"converted into an int my_int = int(el) operand_stack.push(my_int) except: if el == \"+\"",
"j, k = 0, 0, 0 # Sort recursively (I.e. Starting from 2",
"def peek(self): if len(self._items): return self._items[-1] @property def is_empty(self): return len(self._items) == 0",
"array[k] = left[i] i += 1 else: array[k] = right[j] j += 1",
"peek(self): if len(self._items): return self._items[-1] @property def is_empty(self): return len(self._items) == 0 @property",
"valid_operator = '+-*/()' def __init__(self, string=\"\"): self.expr = string @property def expression(self): return",
"return self.expr = new_expr def insert_space(self): s = \"\" for char in self.expr:",
"to array in-place while i < len(left) and j < len(right): if byfunc(left[i])",
"\"*/\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"(\": operator_stack.push(el) elif el == \")\":",
"\"+\" or el == \"-\": while not operator_stack.is_empty and operator_stack.peek() not in \"()\":",
"byfunc(left[i]) <= byfunc(right[j]): array[k] = left[i] i += 1 else: array[k] = right[j]",
"array[k] = left[i] i += 1 k += 1 while j < len(right):",
"return self.expr @expression.setter def expression(self, new_expr): for char in new_expr: if char not",
"if len(self._items): return self._items.pop() def peek(self): if len(self._items): return self._items[-1] @property def is_empty(self):",
"= new_expr def insert_space(self): s = \"\" for char in self.expr: if char",
"== \"+\": ans = b + a elif operator == \"-\": ans =",
"operand_stack.push(my_int) except: if el == \"+\" or el == \"-\": while not operator_stack.is_empty",
"mergesort(array, byfunc=None): if len(array) > 1: start, end = 0, len(array) mid =",
"new_expr): for char in new_expr: if char not in EvaluateExpression.valid_char: self.expr = \"\"",
"len(self._items): return self._items.pop() def peek(self): if len(self._items): return self._items[-1] @property def is_empty(self): return",
"\"*\" or el == \"/\": while operator_stack.peek() in \"*/\": self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif",
"char in new_expr: if char not in EvaluateExpression.valid_char: self.expr = \"\" return self.expr",
"in \"()\": operator_stack.pop() continue self.process_operator(operand_stack, operator_stack) return operand_stack.peek() def get_smallest_three(challenge): records = challenge.records",
"operand_stack.pop() operator = operator_stack.pop() b = operand_stack.pop() if operator == \"+\": ans =",
"0, len(array) mid = len(array) // 2 left = array[start:mid] right = array[mid:end]",
"Add to array in-place while i < len(left) and j < len(right): if",
"self.process_operator(operand_stack, operator_stack) operator_stack.push(el) elif el == \"*\" or el == \"/\": while operator_stack.peek()",
"== 0 @property def size(self): return len(self._items) class EvaluateExpression: valid_char = '0123456789+-*/() '",
"= '0123456789+-*/() ' valid_num = '0123456789' valid_operator = '+-*/()' def __init__(self, string=\"\"): self.expr",
"< len(right): array[k] = right[j] j += 1 k += 1 class Stack:",
"if len(array) > 1: start, end = 0, len(array) mid = len(array) //",
"size(self): return len(self._items) class EvaluateExpression: valid_char = '0123456789+-*/() ' valid_num = '0123456789' valid_operator",
"string @property def expression(self): return self.expr @expression.setter def expression(self, new_expr): for char in",
"= \"\" return self.expr = new_expr def insert_space(self): s = \"\" for char",
"operator == \"-\": ans = b - a elif operator == \"*\": ans",
"# Sort recursively (I.e. Starting from 2 elements) mergesort(left, byfunc=byfunc) mergesort(right, byfunc=byfunc) #",
"operand_stack.pop() if operator == \"+\": ans = b + a elif operator ==",
"for char in self.expr: if char in EvaluateExpression.valid_operator: s += f\" {char} \"",
"== \"(\": operator_stack.push(el) elif el == \")\": while operator_stack.peek() != \"(\": self.process_operator(operand_stack, operator_stack)",
"s += f\" {char} \" else: s += char return s def process_operator(self,",
"el == \"*\" or el == \"/\": while operator_stack.peek() in \"*/\": self.process_operator(operand_stack, operator_stack)",
"operator_stack) return operand_stack.peek() def get_smallest_three(challenge): records = challenge.records times = [r for r",
"able to be converted into an int my_int = int(el) operand_stack.push(my_int) except: if",
"into an int my_int = int(el) operand_stack.push(my_int) except: if el == \"+\" or",
"0: if operator_stack.peek() in \"()\": operator_stack.pop() continue self.process_operator(operand_stack, operator_stack) return operand_stack.peek() def get_smallest_three(challenge):",
"try: # Note: \"10.5\" will NOT be able to be converted into an",
"+= 1 k += 1 class Stack: def __init__(self): self._items = [] def",
"@property def is_empty(self): return len(self._items) == 0 @property def size(self): return len(self._items) class",
"right[j] j += 1 k += 1 class Stack: def __init__(self): self._items =",
"len(self._items) == 0 @property def size(self): return len(self._items) class EvaluateExpression: valid_char = '0123456789+-*/()",
"2 left = array[start:mid] right = array[mid:end] i, j, k = 0, 0,",
"1: start, end = 0, len(array) mid = len(array) // 2 left =",
"tokens = expression.split() for el in tokens: try: # Note: \"10.5\" will NOT"
] |
[
"lcb in merged_split_lcbs: merged.add_lcb(lcb) return merged class Realigner: # local realignment around overlapping",
"= next_hspfrag.hit_start - hspfrag.hit_end if inter_hit_len > 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" * inter_hit_len) inter_query_len",
"seq_end) ) #if border_aln_length > 0: # print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end]) seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\",",
"lambda x: x[0] - x[1]): group = list(map(itemgetter(1), g)) gap_ranges.append((group[0], group[-1])) # tuples",
"- hspfrag.hit_end if inter_hit_len > 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" * inter_hit_len) inter_query_len = next_hspfrag.query_start",
"and use_prev: neighbour_new_entry = prev_new_entry neighbour_lcb = prev_lcb if neighbour_new_entry.strand == \"+\": append",
"[entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i + 1][0]] for i in range(len(gap_ranges) - 1)]) if entry.genome_nr",
"if border_aln_length is not None align only sequences at block border up to",
"and new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) # if not checked yet add it as",
"if lcb.entries[0].strand == \"-\": lcb.reverse_complement_entries() if lcb.entries[0].genome_nr == 1: single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr ==",
"# get surrounding sequences seq_start = interval_start - max_seq_length seq_end = interval_end +",
"and \" + str(len(alignment.genomes)) + \" (number of genomes in XMFA)\") def merge(self,",
"prepend: neighbour_new_entry.sequence = new_entry.sequence + sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence =",
"border_aln_length > 0: # print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end]) seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap =",
"or could be neither appended nor prepended # add LCBs to alignment as",
"max_genome + 1): alignment.genomes[nr - 1] = alignment.genomes[nr] del alignment.genomes[max_genome] return alignment else:",
"> 1: # if more than one entry left search for gaps that",
"append: neighbour_new_entry.sequence = sequence + new_entry.sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence +=",
"tuple_list[idx][1] # current tuple is ok -> store end return exclude_idx align_result =",
"= list(map(itemgetter(1), g)) gap_ranges.append((group[0], group[-1])) # tuples with intervals if len(gap_ranges) > 0:",
"max_length = min([x[4] for x in alignments]) alignments = (lambda max_length=max_length: [item for",
"<= block_length: nr_gaps = len(new_entry.sequence) # check if can be appended to previous",
"i in interval # check border length if i[0] == 0 # start",
"in alignments if item[4] == max_length])() aln_seq_one = alignments[0][0] aln_seq_two = alignments[0][1] else:",
"next_gap) and use_prev: neighbour_new_entry = prev_new_entry neighbour_lcb = prev_lcb if neighbour_new_entry.strand == \"+\":",
"and start sub-sequence after nearest stretch n_stretch_length = 10 n_stretch = 'N' *",
"== 1: single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr == 2: single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb) alignment.lcbs = pairlcbs",
"str(len(alignment.genomes)) + \" (number of genomes in XMFA)\") def merge(self, alignment): for lcb",
"= pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5, -0.1, #default one_alignment_only=True) if len(alignments) > 0: max_score =",
"or not elif len(alignment.lcbs) == 1 and new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) # if",
"alignments if item[2] == max_score])() max_length = min([x[4] for x in alignments]) alignments",
"interval and start sub-sequence after nearest stretch n_stretch_length = 10 n_stretch = 'N'",
"for current interval break if max_length > 0 and max_length < ( seq_end",
"next_hspfrag.hit_start - hspfrag.hit_end if inter_hit_len > 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" * inter_hit_len) inter_query_len =",
"\"between 0 and \" + str(len(alignment.genomes)) + \" (number of genomes in XMFA)\")",
"neighbour_new_entry.strand == \"+\": append = True else: prepend = True elif use_next: neighbour_new_entry",
"not None: max_length = len(aln_seq_one) else: # no alignment, do nothing for current",
"&= set( itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for k in entry.gaps])) rm_gaps = sorted(list(rm_gaps)) # make",
"gap if len(merged_split_lcbs) > 0: prev_lcb = merged_split_lcbs[-1] prev_new_entry = prev_lcb.get_entry(new_genome_nr) if prev_new_entry",
"i[0]) <= border_aln_length for i in interval # check border length if i[0]",
"for lcb in alignment.lcbs: if lcb.length <= length: for entry in lcb.entries: seq",
"* inter_hit_len) inter_query_len = next_hspfrag.query_start - hspfrag.query_end if inter_query_len > 0: seq_one_list.append(\"-\" *",
"create small (less bp than blocklength) LCBs by splitting, but append/prepend sequence merged_split_lcbs",
"range(len(gap_ranges) - 1)]) if entry.genome_nr > rm_genome: entry.genome_nr -= 1 # if no",
"lcb.entries[0].strand == \"-\": lcb.reverse_complement_entries() if lcb.entries[0].genome_nr == 1: single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr == 2:",
"for i in range(len(gap_ranges) - 1)]) if entry.genome_nr > rm_genome: entry.genome_nr -= 1",
"entry.genome_nr > rm_genome: entry.genome_nr -= 1 # if no gaps found only reduce",
"length def realign(self, alignment, processor, border_aln_length=0): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() realigned",
"count in collections.Counter(location_list).items() if count > 1] regions = [] for start in",
"'' or seq_two_nogap == ''): # else: do nothing for current interval if",
"#if border_aln_length > 0: # print(aln_seq_one) # print(aln_seq_two) seq_one = aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two",
"seq_two, realign_regions, processor, border_aln_length): # if border_aln_length is not None align only sequences",
"raise ConsensusXMFAInputError() lcbs = alignment.get_sorted_lcbs(new_genome_nr) # do not create small (less bp than",
"< last_ok_end: #current start smaller than last end -> exclude exclude_idx.append(idx) else: last_ok_end",
"one lcb is unchecked try to merge alignment.lcbs = alignment.get_sorted_lcbs(order) j = 0",
"[] seq_two_list = [] if match.hit_start > 0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" * match.hit_start) if",
"# continue with unchecked lcbs # if only one lcb left check whether",
"alignments]) alignments = (lambda max_length=max_length: [item for item in alignments if item[4] ==",
"1 lcb.entries[:] = entries alignment.lcbs[:] = [lcb for lcb in alignment.lcbs if len(lcb.entries)",
"next_new_entry.sequence[0] == \"-\")\\ or (next_new_entry.strand == \"-\" and next_new_entry.sequence[-1] == \"-\"): next_gap =",
"or consecutive gaps in two sequences # if border_aln_length is not None align",
"entry is small and only created by splitting or aligning of new genome",
"len(merged_split_lcbs) > 0: prev_lcb = merged_split_lcbs[-1] prev_new_entry = prev_lcb.get_entry(new_genome_nr) if prev_new_entry is not",
"prepended to next entry and if that starts with a gap if len(lcbs)",
"SingletonAligner: def genome_count_split(self, alignment): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() single_alignment_1 = Alignment(alignment.xmfa_file)",
"> rm_genome: entry.genome_nr -= 1 elif len(entries) == 1: # if only one",
"len(seq_one) - match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" * seq_len) if match.query_end < len(seq_two): seq_len =",
"interval[0][0], interval[1][1] - interval[1][0]]), key=lambda p: p[1]) # get length of gaps at",
"= align_result[0][0] # add starting sequences, in case query or hit do not",
"= seq_one entry_two.sequence = seq_two new_lcb = LCB() new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb) return realigned",
"new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb]) else: break alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)] # continue with",
"in entries: entry.sequence = ''.join( [entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i + 1][0]] for i in",
"in alignment_two.lcbs: for entry in lcb.entries: entry.genome_nr = genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return alignment class",
"border length if i[0] == 0 # start of block or ((i[1] -",
"_realign(self, seq_one, seq_two, realign_regions, processor, border_aln_length): # if border_aln_length is not None align",
"len(one_first_two_second) > 0: seq_one, seq_two = self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second, processor, border_aln_length) entry_one.sequence =",
"seq_one_list.append(\"-\" * seq_len) seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else: return None, None class SingletonAligner:",
"one_first_two_second = self._get_realign_regions(entry_one.gaps, entry_two.gaps) if len(one_first_two_second) > 0: seq_one, seq_two = self._realign(entry_one.sequence, entry_two.sequence,",
"alignment.lcbs: entries = [entry for entry in lcb.entries if entry.genome_nr != rm_genome] #",
"merged_split_lcbs: merged.add_lcb(lcb) return merged class Realigner: # local realignment around overlapping or consecutive",
"single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb) alignment.lcbs = pairlcbs return alignment, single_alignment_1, single_alignment_2 def join(self, alignment,",
"for nr, genome in alignment.genomes.items(): merged.add_genome(genome, nr) for lcb in merged_split_lcbs: merged.add_lcb(lcb) return",
"== \"-\")\\ or (next_new_entry.strand == \"-\" and next_new_entry.sequence[-1] == \"-\"): next_gap = True",
"- index_offset interval_end = interval[max_index][1] - index_offset # border_aln_length not set OR small",
"genome_names_two.sort(): print(\"ERROR: Can only join alignments from same set of genomes.\") if alignment.genomes[1].file_path",
"True else: append = True if neighbour_new_entry is not None: if new_entry.strand !=",
"+ _check_tuple_overlap(match.query_range_all) hspfrag_keys = list(set(range(len(match.hit_range_all))) - set(exclude_keys)) hspfrag_key_num = len(hspfrag_keys) for hspfrag_idx in",
"next_new_entry is not None and (next_new_entry.start - new_entry.end) == 1: use_next = True",
"def merge(self, alignment): for lcb in alignment.lcbs: lcb.entries = sorted(lcb.entries, key=lambda entry: entry.genome_nr)",
"elif use_next: neighbour_new_entry = next_new_entry neighbour_lcb = next_lcb if neighbour_new_entry.strand == \"+\": prepend",
"entry in lcb.entries: seq = entry.sequence.replace(\"-\", \"\") new_entry = SequenceEntry(entry.genome_nr, entry.start, entry.end, entry.strand,",
"len(seq_one): seq_len = len(seq_one) - match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" * seq_len) if match.query_end <",
"seq_one, seq_two, realign_regions, processor, border_aln_length): # if border_aln_length is not None align only",
"item[4] == max_length])() aln_seq_one = alignments[0][0] aln_seq_two = alignments[0][1] else: # no alignment,",
"= seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\", \"\") if not (seq_one_nogap == '' or",
"and (next_new_entry.start - new_entry.end) == 1: use_next = True if (next_new_entry.strand == \"+\"",
"alignments if item[4] == max_length])() aln_seq_one = alignments[0][0] aln_seq_two = alignments[0][1] else: #",
"1 and new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) # if not checked yet add it",
"= aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two = aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset += ((seq_end - seq_start) -",
"neighbour_new_entry.start = min(new_entry.start, neighbour_new_entry.start) if append: neighbour_new_entry.sequence = sequence + new_entry.sequence if neighbour_consensus_entry",
"len(lcb.entries) == 1: if lcb.entries[0].strand == \"-\": lcb.reverse_complement_entries() if lcb.entries[0].genome_nr == 1: single_alignment_1.add_lcb(lcb)",
"sequences at block border up to given length def realign(self, alignment, processor, border_aln_length=0):",
"2: print(\"ERROR: I don't want to think about cases with more than 2",
"unequal strand reverse complement this lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length for pos in",
"one_alignment_only=True) if len(alignments) > 0: max_score = max([x[2] for x in alignments]) alignments",
"+= 1 if alignment.lcbs[lcb].get_entry(order) is not None: i = 0 if len(alignment.lcbs[lcb].entries) ==",
"could be neither appended nor prepended # add LCBs to alignment as it",
"= Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): merged.add_genome(genome, nr) for lcb in merged_split_lcbs:",
"len(lcbs) > (i+1): next_lcb = lcbs[i + 1] next_new_entry = next_lcb.get_entry(new_genome_nr) if next_new_entry",
"exclude_idx align_result = processor.external_blat(seq_one, seq_two) if align_result is not None: # seq_one equals",
"n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) # find N-stretch between",
"len(lcb.entries) > 0] max_genome = len(alignment.genomes) for nr in range(rm_genome + 1, max_genome",
"ends with a gap if len(merged_split_lcbs) > 0: prev_lcb = merged_split_lcbs[-1] prev_new_entry =",
"# entry should not be merged or could be neither appended nor prepended",
"end in gaps_for_start.items()] + list(ends_dict.keys()) region_starts = [item for item, count in collections.Counter(location_list).items()",
"gap at start or end if (not next_gap) and use_prev: neighbour_new_entry = prev_new_entry",
"+= (\"-\" * nr_gaps) elif prepend: neighbour_new_entry.sequence = new_entry.sequence + sequence if neighbour_consensus_entry",
"seq_len) seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else: return None, None class SingletonAligner: def genome_count_split(self,",
"seq_len = len(seq_one) - match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" * seq_len) if match.query_end < len(seq_two):",
"by splitting or aligning of new genome (consensus is None) if consensus_entry is",
"in two sequences # if border_aln_length is not None align only sequences at",
"neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length += nr_gaps neighbour_new_entry.end = max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start = min(new_entry.start,",
"store end return exclude_idx align_result = processor.external_blat(seq_one, seq_two) if align_result is not None:",
"not None: neighbour_consensus_entry.sequence += (\"-\" * nr_gaps) elif prepend: neighbour_new_entry.sequence = new_entry.sequence +",
"add sequences between aligned intervals to sequences if hspfrag_idx < (hspfrag_key_num - 1):",
"max([x[2] for x in alignments]) alignments = (lambda max_score=max_score: [item for item in",
"!= strand: # if an entry does not fulfill all conditions stop and",
"> 0: seq_one_list.append(\"-\" * match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented: # in really rare cases",
"for item in alignments if item[2] == max_score])() max_length = min([x[4] for x",
"one lcb left check whether it is already checked or not elif len(alignment.lcbs)",
"+ [(lcb.length, lcb.length)] for entry in entries: entry.sequence = ''.join( [entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i",
"border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two # get regions to realign for",
"stretch n_stretch_idx_one = seq_one.find(n_stretch, interval_end, seq_end) n_stretch_idx_two = seq_two.find(n_stretch, interval_end, seq_end) seq_end =",
"None: neighbour_consensus_entry.sequence += (\"-\" * nr_gaps) elif prepend: neighbour_new_entry.sequence = new_entry.sequence + sequence",
"entry_two = lcb.entries[1] # get regions to realign one_first_two_second = self._get_realign_regions(entry_one.gaps, entry_two.gaps) if",
"> 0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" * match.hit_start) if match.query_start > 0: seq_one_list.append(\"-\" * match.query_start)",
"ConsensusXMFAInputError() lcbs = alignment.get_sorted_lcbs(new_genome_nr) # do not create small (less bp than blocklength)",
"0: seq_one, seq_two = self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence",
"= interval_end + max_seq_length # do not go over boundaries of sequences! seq_start",
"alignment as it is else: merged_split_lcbs.append(lcb) merged = Alignment(alignment.xmfa_file) for nr, genome in",
"sequences if hspfrag_idx < (hspfrag_key_num - 1): next_hspfrag = match[hspfrag_keys[hspfrag_idx + 1]] inter_hit_len",
"- interval[0][0], interval[1][1] - interval[1][0]]), key=lambda p: p[1]) # get length of gaps",
"len(entries) > 1: # if more than one entry left search for gaps",
"start or end if (not next_gap) and use_prev: neighbour_new_entry = prev_new_entry neighbour_lcb =",
"return merged class Realigner: # local realignment around overlapping or consecutive gaps in",
"any(short_border_intervals): # check if interval only 'N' - if yes: do not realign",
"0 # start of block or ((i[1] - index_offset) == len(seq_one)) # end",
"this lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break else: i += 1 if i == len(alignment.lcbs[lcb].entries): if",
"# do not create small (less bp than blocklength) LCBs by splitting, but",
"or (alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb - 1].entries[entry].strand) != strand: # if an entry does",
"not None: # seq_one equals hit seq_two equals query # only one query",
"+ n_stretch_length)) n_stretch_idx = seq_two.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start =",
"\"\".join(seq_two_list).upper() else: return None, None class SingletonAligner: def genome_count_split(self, alignment): if len(alignment.genomes) >",
"nr) for lcb in alignment.lcbs: if lcb.length <= length: for entry in lcb.entries:",
"# N-stretches in sequences # find N-stretch between start and interval and start",
"sequence ends if match.hit_end < len(seq_one): seq_len = len(seq_one) - match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\"",
"entry.genome_nr > rm_genome: entry.genome_nr -= 1 lcb.entries[:] = entries alignment.lcbs[:] = [lcb for",
"< 1000: #https://github.com/biopython/biopython/pull/782 alignments = pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5, -0.1, #default one_alignment_only=True) if len(alignments)",
"length: for entry in lcb.entries: seq = entry.sequence.replace(\"-\", \"\") new_entry = SequenceEntry(entry.genome_nr, entry.start,",
"((seq_end - seq_start) - max_length) return seq_one, seq_two def _external_blat(self, seq_one, seq_two, processor):",
"seq_one.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length))",
"border_aln_length == 0 or any(short_border_intervals): # check if interval only 'N' - if",
"# no alignment, do nothing for current interval break else: # do external",
"match.hit_end < len(seq_one): seq_len = len(seq_one) - match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" * seq_len) if",
"and do not merge this lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break else: i += 1 if",
"min([x[4] for x in alignments]) alignments = (lambda max_length=max_length: [item for item in",
"merged.add_lcb(lcb) return merged class Realigner: # local realignment around overlapping or consecutive gaps",
"is None) if consensus_entry is None and new_entry is not None and len(new_entry.sequence)",
"new_entry.sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence += (\"-\" * nr_gaps) elif prepend:",
"regions to realign one_first_two_second = self._get_realign_regions(entry_one.gaps, entry_two.gaps) if len(one_first_two_second) > 0: seq_one, seq_two",
"to realign for updated entries with second entry first two_first_one_second = self._get_realign_regions(entry_two.gaps, entry_one.gaps)",
"alignment.lcbs = pairlcbs return alignment, single_alignment_1, single_alignment_2 def join(self, alignment, alignment_two): if len(alignment.genomes)",
"for lcb in alignment_two.lcbs: for entry in lcb.entries: entry.genome_nr = genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return",
"seq_two_nogap.upper(), -0.5, -0.1, #default one_alignment_only=True) if len(alignments) > 0: max_score = max([x[2] for",
"from same set of genomes.\") if alignment.genomes[1].file_path != alignment_two.genomes[1].file_path: genome_nr_dict = {1: 2,",
"= seq_two[seq_start:seq_end].replace(\"-\", \"\") if not (seq_one_nogap == '' or seq_two_nogap == ''): #",
"== len(alignment.lcbs[lcb - 1].entries): strand = alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb - 1].entries[0].strand for entry",
"{1: 1, 2: 2} for lcb in alignment_two.lcbs: for entry in lcb.entries: entry.genome_nr",
"genome_nr_dict = {1: 1, 2: 2} for lcb in alignment_two.lcbs: for entry in",
"len(seq_two) - match.query_end seq_one_list.append(\"-\" * seq_len) seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else: return None,",
"-> exclude exclude_idx.append(idx) else: last_ok_end = tuple_list[idx][1] # current tuple is ok ->",
"alignment.lcbs[lcb - 1].entries[entry].strand) != strand: # if an entry does not fulfill all",
"+ sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence = (\"-\" * nr_gaps) +",
"> 1] regions = [] for start in region_starts: regions.append([(start, gaps_for_start[start]), (ends_dict[start], start)])",
"= alignment.genomes[nr] del alignment.genomes[max_genome] return alignment else: raise ParameterError(\"remove_genome\", rm_genome, \"between 0 and",
"in range(1, len(alignment.lcbs)): j += 1 if alignment.lcbs[lcb].get_entry(order) is not None: i =",
"import collections import itertools from operator import itemgetter import math from Bio import",
"# only one query and first hit has highest score per definition of",
"next_hspfrag = match[hspfrag_keys[hspfrag_idx + 1]] inter_hit_len = next_hspfrag.hit_start - hspfrag.hit_end if inter_hit_len >",
"n_stretch_length = 10 n_stretch = 'N' * n_stretch_length n_stretch_idx = seq_one.rfind(n_stretch, seq_start, interval_start)",
"at block border up to given length realign_regions = sorted(realign_regions) index_offset = 0",
"< (hspfrag_key_num - 1): next_hspfrag = match[hspfrag_keys[hspfrag_idx + 1]] inter_hit_len = next_hspfrag.hit_start -",
"nr_gaps) + neighbour_consensus_entry.sequence # entry should not be merged or could be neither",
"border_aln_length): # if border_aln_length is not None align only sequences at block border",
"seq_one = aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two = aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset += ((seq_end - seq_start)",
"gaps in sequence entries[0].sequence = entries[0].sequence.replace(\"-\", \"\") if entries[0].genome_nr > rm_genome: entries[0].genome_nr -=",
"hit seq_two equals query # only one query and first hit has highest",
"better than old one #if border_aln_length > 0: # print(aln_seq_one) # print(aln_seq_two) seq_one",
"= exclude_keys + _check_tuple_overlap(match.query_range_all) hspfrag_keys = list(set(range(len(match.hit_range_all))) - set(exclude_keys)) hspfrag_key_num = len(hspfrag_keys) for",
"match.is_fragmented: # in really rare cases fragments are overlapping! exclude_keys = _check_tuple_overlap(match.hit_range_all) exclude_keys",
"else: genome_nr_dict = {1: 1, 2: 2} for lcb in alignment_two.lcbs: for entry",
"if entry.genome_nr != rm_genome] # did LCB include entry of genome to remove?",
"new_alignment.add_lcb(alignment.lcbs[0]) # if not checked yet add it as last lcb and finish",
"0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" * match.hit_start) if match.query_start > 0: seq_one_list.append(\"-\" * match.query_start) seq_two_list.append(seq_two[0:match.query_start])",
"1: # if more than one entry left search for gaps that are",
"= self._external_blat(seq_one_nogap, seq_two_nogap, processor) if aln_seq_one is not None: max_length = len(aln_seq_one) else:",
"seq_end = min(seq_end, (n_stretch_idx_one if n_stretch_idx_one > -1 else seq_end), (n_stretch_idx_two if n_stretch_idx_two",
"= seq_two.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx +",
"lcb is unchecked try to merge alignment.lcbs = alignment.get_sorted_lcbs(order) j = 0 if",
"entries[0].genome_nr > rm_genome: entries[0].genome_nr -= 1 else: for entry in entries: if entry.genome_nr",
"!= alignment.lcbs[lcb - 1].entries[entry].genome_nr \\ or alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb - 1].entries[entry].end != 1",
"1].entries[entry].strand) != strand: # if an entry does not fulfill all conditions stop",
"1].entries[entry].genome_nr \\ or alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb - 1].entries[entry].end != 1 \\ or (alignment.lcbs[lcb].entries[entry].strand",
"= lcbs[i + 1] next_new_entry = next_lcb.get_entry(new_genome_nr) if next_new_entry is not None and",
"do not merge this lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break else: i += 1 if i",
"last_ok_end = tuple_list[idx][1] # current tuple is ok -> store end return exclude_idx",
"seq_one_list.append(\"-\" * inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one = match.aln[0] if seq_rec_one.id == \"seq1\": seq_one_list.append(str(match.aln[0].seq))",
"= max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start = min(new_entry.start, neighbour_new_entry.start) if append: neighbour_new_entry.sequence = sequence +",
"faster join() gap_ranges = [] for k, g in itertools.groupby(enumerate(rm_gaps), lambda x: x[0]",
"in itertools.groupby(enumerate(rm_gaps), lambda x: x[0] - x[1]): group = list(map(itemgetter(1), g)) gap_ranges.append((group[0], group[-1]))",
"if alignment.genomes[1].file_path != alignment_two.genomes[1].file_path: genome_nr_dict = {1: 2, 2: 1} else: genome_nr_dict =",
"short_border_intervals = [(i[1] - i[0]) <= border_aln_length for i in interval # check",
"<= length: for entry in lcb.entries: seq = entry.sequence.replace(\"-\", \"\") new_entry = SequenceEntry(entry.genome_nr,",
"is ok -> store end return exclude_idx align_result = processor.external_blat(seq_one, seq_two) if align_result",
"seq_two = self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two",
"max_genome = len(alignment.genomes) for nr in range(rm_genome + 1, max_genome + 1): alignment.genomes[nr",
"with second entry first two_first_one_second = self._get_realign_regions(entry_two.gaps, entry_one.gaps) if len(two_first_one_second) > 0: seq_two,",
"merged_split_lcbs = [] for i in range(len(lcbs)): lcb = lcbs[i] new_entry = lcb.get_entry(new_genome_nr)",
"if len(alignment.lcbs) > 1: # if more than one lcb is unchecked try",
"1 \\ or (alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb - 1].entries[entry].strand) != strand: # if an",
"LCBs to alignment as it is else: merged_split_lcbs.append(lcb) merged = Alignment(alignment.xmfa_file) for nr,",
"start smaller than last end -> exclude exclude_idx.append(idx) else: last_ok_end = tuple_list[idx][1] #",
"alignment.lcbs if len(lcb.entries) > 0] max_genome = len(alignment.genomes) for nr in range(rm_genome +",
"join() gap_ranges = [] for k, g in itertools.groupby(enumerate(rm_gaps), lambda x: x[0] -",
"\"+\" and prev_new_entry.sequence[-1] == \"-\") \\ or ( prev_new_entry.strand == \"-\" and prev_new_entry.sequence[0]",
"blat match = align_result[0][0] # add starting sequences, in case query or hit",
"[list(range(k, entries[0].gaps[k])) for k in entries[0].gaps])) for entry in entries[1:]: rm_gaps &= set(",
"new genome (consensus is None) if consensus_entry is None and new_entry is not",
"\"+\" and next_new_entry.sequence[0] == \"-\")\\ or (next_new_entry.strand == \"-\" and next_new_entry.sequence[-1] == \"-\"):",
"True if append or prepend: if to_reverse_complement: new_entry.reverse_complement() sequence = neighbour_new_entry.sequence neighbour_consensus_entry =",
"1]] inter_hit_len = next_hspfrag.hit_start - hspfrag.hit_end if inter_hit_len > 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" *",
"len(new_entry.sequence) # check if can be appended to previous entry and if that",
"from seqseqpan.base import * class Separator: def separate_lcbs(self, alignment, length): separated = Alignment(alignment.xmfa_file)",
"if yes: do not realign n_stretch = 'N' * max_seq_length if not (seq_one[interval_start:interval_end]",
"= alignment.get_sorted_lcbs(new_genome_nr) # do not create small (less bp than blocklength) LCBs by",
"def remove(self, alignment, rm_genome): if len(alignment.genomes) >= rm_genome > -1: for lcb in",
"not None align only sequences at block border up to given length def",
"-1 exclude_idx = [] #overlap_detected = False for idx in range(num_tuple): if tuple_list[idx][0]",
"# make intervals of consecutive gap positions for faster join() gap_ranges = []",
"is not None and len(new_entry.sequence) <= block_length: nr_gaps = len(new_entry.sequence) # check if",
"exclude_keys + _check_tuple_overlap(match.query_range_all) hspfrag_keys = list(set(range(len(match.hit_range_all))) - set(exclude_keys)) hspfrag_key_num = len(hspfrag_keys) for hspfrag_idx",
"\"0\" seq_one_list = [] seq_two_list = [] if match.hit_start > 0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\"",
"-= 1 lcb.entries[:] = entries alignment.lcbs[:] = [lcb for lcb in alignment.lcbs if",
"if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() single_alignment_1 = Alignment(alignment.xmfa_file) single_alignment_2 = Alignment(alignment.xmfa_file) single_alignment_1.genomes[1]",
"10 n_stretch = 'N' * n_stretch_length n_stretch_idx = seq_one.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx",
"0] max_genome = len(alignment.genomes) for nr in range(rm_genome + 1, max_genome + 1):",
"((i[1] - index_offset) == len(seq_two))] # end of block interval_start = interval[max_index][0] -",
"1: if lcb.entries[0].strand == \"-\": lcb.reverse_complement_entries() if lcb.entries[0].genome_nr == 1: single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr",
"gap_ranges = gap_ranges + [(lcb.length, lcb.length)] for entry in entries: entry.sequence = ''.join(",
"= lcbs[i] new_entry = lcb.get_entry(new_genome_nr) consensus_entry = lcb.get_entry(consensus_genome_nr) prepend = False append =",
"None # check if new entry is small and only created by splitting",
"for k in entries[0].gaps])) for entry in entries[1:]: rm_gaps &= set( itertools.chain.from_iterable([list(range(k, entry.gaps[k]))",
"Merger: def merge_lcbs(self, alignment, consensus_genome_nr, new_genome_nr, block_length): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError()",
"same set of genomes.\") if alignment.genomes[1].file_path != alignment_two.genomes[1].file_path: genome_nr_dict = {1: 2, 2:",
"make intervals of consecutive gap positions for faster join() gap_ranges = [] for",
"do not realign n_stretch = 'N' * max_seq_length if not (seq_one[interval_start:interval_end] == n_stretch",
"exclude_idx.append(idx) else: last_ok_end = tuple_list[idx][1] # current tuple is ok -> store end",
"Realigner: # local realignment around overlapping or consecutive gaps in two sequences #",
"inter_hit_len = next_hspfrag.hit_start - hspfrag.hit_end if inter_hit_len > 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" * inter_hit_len)",
"n_stretch_idx_two > -1 else seq_end) ) #if border_aln_length > 0: # print(seq_one[seq_start:seq_end]) #",
"= seq_two # get regions to realign for updated entries with second entry",
"Alignment(alignment.xmfa_file) single_alignment_2 = Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] = alignment.genomes[1] single_alignment_2.genomes[2] = alignment.genomes[2] pairlcbs = []",
"< len(seq_one): seq_len = len(seq_one) - match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" * seq_len) if match.query_end",
"to think about cases with more than 2 genomes now.\") genome_names_one = [genome.file_path",
"# check if can be appended to previous entry and if that ends",
"that starts with a gap if len(lcbs) > (i+1): next_lcb = lcbs[i +",
"0 if alignment.lcbs[0].get_entry(order) is not None: new_alignment.add_lcb(alignment.lcbs[0]) for lcb in range(1, len(alignment.lcbs)): j",
"genomes.\") if alignment.genomes[1].file_path != alignment_two.genomes[1].file_path: genome_nr_dict = {1: 2, 2: 1} else: genome_nr_dict",
"or query do not include sequence ends if match.hit_end < len(seq_one): seq_len =",
"and if that starts with a gap if len(lcbs) > (i+1): next_lcb =",
"replace all gaps in sequence entries[0].sequence = entries[0].sequence.replace(\"-\", \"\") if entries[0].genome_nr > rm_genome:",
"is not None: max_length = len(aln_seq_one) else: # no alignment, do nothing for",
"entries rm_gaps = set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k])) for k in entries[0].gaps])) for entry in",
"= sequence + new_entry.sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence += (\"-\" *",
"= tuple_list[idx][1] # current tuple is ok -> store end return exclude_idx align_result",
"def _check_tuple_overlap(tuple_list): num_tuple = len(tuple_list) last_ok_end = -1 exclude_idx = [] #overlap_detected =",
"return None, None class SingletonAligner: def genome_count_split(self, alignment): if len(alignment.genomes) > 2: raise",
"== 1: if lcb.entries[0].strand == \"-\": lcb.reverse_complement_entries() if lcb.entries[0].genome_nr == 1: single_alignment_1.add_lcb(lcb) elif",
"max_index, max_seq_length = max( enumerate([interval[0][1] - interval[0][0], interval[1][1] - interval[1][0]]), key=lambda p: p[1])",
"border up to given length realign_regions = sorted(realign_regions) index_offset = 0 for interval",
"if match.hit_start > 0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" * match.hit_start) if match.query_start > 0: seq_one_list.append(\"-\"",
"else: raise ParameterError(\"remove_genome\", rm_genome, \"between 0 and \" + str(len(alignment.genomes)) + \" (number",
"if (seq_end - seq_start) < 1000: #https://github.com/biopython/biopython/pull/782 alignments = pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5, -0.1,",
"seq_two[interval_start:interval_end] == n_stretch): max_seq_length = math.ceil(max_seq_length * 1.5) # get surrounding sequences seq_start",
"p[1]) # get length of gaps at start or end of block short_border_intervals",
"Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): new_alignment.add_genome(genome, nr) for order in alignment.genomes: if",
"merged class Realigner: # local realignment around overlapping or consecutive gaps in two",
"include entry of genome to remove? if len(entries) < len(lcb.entries): # are there",
"entries[0].genome_nr -= 1 else: for entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr",
"and len(new_entry.sequence) <= block_length: nr_gaps = len(new_entry.sequence) # check if can be appended",
"than last end -> exclude exclude_idx.append(idx) else: last_ok_end = tuple_list[idx][1] # current tuple",
">= rm_genome > -1: for lcb in alignment.lcbs: entries = [entry for entry",
"entries[0].sequence.replace(\"-\", \"\") if entries[0].genome_nr > rm_genome: entries[0].genome_nr -= 1 else: for entry in",
"= len(tuple_list) last_ok_end = -1 exclude_idx = [] #overlap_detected = False for idx",
"entries[0].sequence = entries[0].sequence.replace(\"-\", \"\") if entries[0].genome_nr > rm_genome: entries[0].genome_nr -= 1 else: for",
"hspfrag_key_num = len(hspfrag_keys) for hspfrag_idx in range(hspfrag_key_num): hspfrag_key = hspfrag_keys[hspfrag_idx] hspfrag = match[hspfrag_key]",
"True if (next_new_entry.strand == \"+\" and next_new_entry.sequence[0] == \"-\")\\ or (next_new_entry.strand == \"-\"",
"sequences, in case query or hit do not start at \"0\" seq_one_list =",
"single_alignment_1 = Alignment(alignment.xmfa_file) single_alignment_2 = Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] = alignment.genomes[1] single_alignment_2.genomes[2] = alignment.genomes[2] pairlcbs",
"new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb) return realigned def _get_realign_regions(self, gaps_for_start, gaps_for_end): ends_dict = {end: start",
"interval_end = interval[max_index][1] - index_offset # border_aln_length not set OR small sequence at",
"if next_new_entry is not None and (next_new_entry.start - new_entry.end) == 1: use_next =",
"0: gap_ranges = [(-1, -1)] + gap_ranges if gap_ranges[-1] != lcb.length: gap_ranges =",
"if an entry does not fulfill all conditions stop and do not merge",
"len(alignment.lcbs)): j += 1 if alignment.lcbs[lcb].get_entry(order) is not None: i = 0 if",
"alignment.genomes.values()] genome_names_two = [genome.file_path for genome in alignment_two.genomes.values()] if genome_names_one.sort() != genome_names_two.sort(): print(\"ERROR:",
"aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset += ((seq_end - seq_start) - max_length) return seq_one, seq_two def",
"genome in alignment.genomes.items(): new_alignment.add_genome(genome, nr) for order in alignment.genomes: if len(alignment.lcbs) > 1:",
"rm_genome: entries[0].genome_nr -= 1 else: for entry in entries: if entry.genome_nr > rm_genome:",
"one entry left search for gaps that are present in all remaining entries",
"if match.query_end < len(seq_two): seq_len = len(seq_two) - match.query_end seq_one_list.append(\"-\" * seq_len) seq_two_list.append(seq_two[match.query_end:])",
"genomes now.\") genome_names_one = [genome.file_path for genome in alignment.genomes.values()] genome_names_two = [genome.file_path for",
"= Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): separated.add_genome(genome, nr) for lcb in alignment.lcbs:",
"OR small sequence at start or end of block if border_aln_length == 0",
"prev_new_entry.sequence[0] == \"-\"): prev_gap = True # check if can be prepended to",
"> -1: for lcb in alignment.lcbs: entries = [entry for entry in lcb.entries",
"= sorted(realign_regions) index_offset = 0 for interval in realign_regions: max_index, max_seq_length = max(",
"= max(seq_start, (n_stretch_idx + n_stretch_length)) # find N-stretch between interval and end and",
"print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end]) seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\", \"\") if not",
"(ends_dict[start], start)]) return regions def _realign(self, seq_one, seq_two, realign_regions, processor, border_aln_length): # if",
"None, None class SingletonAligner: def genome_count_split(self, alignment): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError()",
"x: x[0] - x[1]): group = list(map(itemgetter(1), g)) gap_ranges.append((group[0], group[-1])) # tuples with",
"= aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset += ((seq_end - seq_start) - max_length) return seq_one, seq_two",
"genome_names_one.sort() != genome_names_two.sort(): print(\"ERROR: Can only join alignments from same set of genomes.\")",
"in lcb.entries: entry.genome_nr = genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return alignment class Remover: def remove(self, alignment,",
"to_reverse_complement = False next_new_entry = None prev_new_entry = None # check if new",
"False next_new_entry = None prev_new_entry = None # check if new entry is",
"aligned intervals to sequences if hspfrag_idx < (hspfrag_key_num - 1): next_hspfrag = match[hspfrag_keys[hspfrag_idx",
"\\ or ( prev_new_entry.strand == \"-\" and prev_new_entry.sequence[0] == \"-\"): prev_gap = True",
"= min([x[4] for x in alignments]) alignments = (lambda max_length=max_length: [item for item",
"* nr_gaps) elif prepend: neighbour_new_entry.sequence = new_entry.sequence + sequence if neighbour_consensus_entry is not",
"lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length for pos in range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence",
"than one entry left search for gaps that are present in all remaining",
"(lambda max_score=max_score: [item for item in alignments if item[2] == max_score])() max_length =",
"<reponame>sekang2/seq-seq-pan<gh_stars>0 import collections import itertools from operator import itemgetter import math from Bio",
"query or hit do not start at \"0\" seq_one_list = [] seq_two_list =",
"before nearest stretch n_stretch_idx_one = seq_one.find(n_stretch, interval_end, seq_end) n_stretch_idx_two = seq_two.find(n_stretch, interval_end, seq_end)",
"if neighbour_new_entry.strand == \"+\": append = True else: prepend = True elif use_next:",
"not checked yet add it as last lcb and finish break else: break",
"= True if (prev_new_entry.strand == \"+\" and prev_new_entry.sequence[-1] == \"-\") \\ or (",
"= seq_two.find(n_stretch, interval_end, seq_end) seq_end = min(seq_end, (n_stretch_idx_one if n_stretch_idx_one > -1 else",
"in alignment.genomes.items(): realigned.add_genome(genome, nr) # go through lcbs, skip one-entry ones for lcb",
"group = list(map(itemgetter(1), g)) gap_ranges.append((group[0], group[-1])) # tuples with intervals if len(gap_ranges) >",
"itemgetter import math from Bio import pairwise2 from seqseqpan.base import * class Separator:",
"prev_lcb.get_entry(new_genome_nr) if prev_new_entry is not None and (new_entry.start - prev_new_entry.end) == 1: use_prev",
"has highest score per definition of blat match = align_result[0][0] # add starting",
"gaps_for_start, gaps_for_end): ends_dict = {end: start for start, end in gaps_for_end.items()} location_list =",
"seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) # add last sequence parts if hit or query",
"all entries have an unequal strand reverse complement this lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length +=",
"1 elif len(entries) == 1: # if only one entry left replace all",
"prev_lcb if neighbour_new_entry.strand == \"+\": append = True else: prepend = True elif",
"by splitting, but append/prepend sequence merged_split_lcbs = [] for i in range(len(lcbs)): lcb",
"# get length of gaps at start or end of block short_border_intervals =",
"if prev_new_entry is not None and (new_entry.start - prev_new_entry.end) == 1: use_prev =",
"= next_new_entry neighbour_lcb = next_lcb if neighbour_new_entry.strand == \"+\": prepend = True else:",
"alignment.add_lcb(lcb) return alignment class Remover: def remove(self, alignment, rm_genome): if len(alignment.genomes) >= rm_genome",
"len(entries) < len(lcb.entries): # are there any entries left in LCB? if len(entries)",
"[] for k, g in itertools.groupby(enumerate(rm_gaps), lambda x: x[0] - x[1]): group =",
"I don't want to think about cases with more than 2 genomes now.\")",
"= ''.join( [entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i + 1][0]] for i in range(len(gap_ranges) - 1)])",
"want to think about cases with more than 2 genomes now.\") genome_names_one =",
"neighbour_new_entry = next_new_entry neighbour_lcb = next_lcb if neighbour_new_entry.strand == \"+\": prepend = True",
"== \"-\") \\ or ( prev_new_entry.strand == \"-\" and prev_new_entry.sequence[0] == \"-\"): prev_gap",
"border_aln_length for i in interval # check border length if i[0] == 0",
"neighbour_new_entry is not None: if new_entry.strand != neighbour_new_entry.strand: to_reverse_complement = True if append",
"genome nr (avoid looping through entries twice if gaps present) else: for entry",
"x in alignments]) alignments = (lambda max_score=max_score: [item for item in alignments if",
"entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1 lcb.entries[:] = entries alignment.lcbs[:] =",
"== \"-\"): next_gap = True neighbour_new_entry = None # if both, choose the",
"a gap if len(lcbs) > (i+1): next_lcb = lcbs[i + 1] next_new_entry =",
"in lcb.entries if entry.genome_nr != rm_genome] # did LCB include entry of genome",
"Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): realigned.add_genome(genome, nr) # go through lcbs, skip",
"for updated entries with second entry first two_first_one_second = self._get_realign_regions(entry_two.gaps, entry_one.gaps) if len(two_first_one_second)",
"else: pairlcbs.append(lcb) alignment.lcbs = pairlcbs return alignment, single_alignment_1, single_alignment_2 def join(self, alignment, alignment_two):",
"updated entries with second entry first two_first_one_second = self._get_realign_regions(entry_two.gaps, entry_one.gaps) if len(two_first_one_second) >",
"> 2: raise ConsensusXMFAInputError() realigned = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): realigned.add_genome(genome,",
"get regions to realign one_first_two_second = self._get_realign_regions(entry_one.gaps, entry_two.gaps) if len(one_first_two_second) > 0: seq_one,",
"= max([x[2] for x in alignments]) alignments = (lambda max_score=max_score: [item for item",
"continue with unchecked lcbs # if only one lcb left check whether it",
"more than 2 genomes now.\") genome_names_one = [genome.file_path for genome in alignment.genomes.values()] genome_names_two",
"i = 0 if len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb - 1].entries): strand = alignment.lcbs[lcb].entries[0].strand ==",
"appended nor prepended # add LCBs to alignment as it is else: merged_split_lcbs.append(lcb)",
"else: # no alignment, do nothing for current interval break else: # do",
"if aln_seq_one is not None: max_length = len(aln_seq_one) else: # no alignment, do",
"if append: neighbour_new_entry.sequence = sequence + new_entry.sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence",
"(next_new_entry.strand == \"+\" and next_new_entry.sequence[0] == \"-\")\\ or (next_new_entry.strand == \"-\" and next_new_entry.sequence[-1]",
"break else: i += 1 if i == len(alignment.lcbs[lcb].entries): if not strand: #",
"else: prepend = True elif use_next: neighbour_new_entry = next_new_entry neighbour_lcb = next_lcb if",
"splitting or aligning of new genome (consensus is None) if consensus_entry is None",
"alignments[0][0] aln_seq_two = alignments[0][1] else: # no alignment, do nothing for current interval",
"+= 1 if i == len(alignment.lcbs[lcb].entries): if not strand: # if all entries",
"else: append = True if neighbour_new_entry is not None: if new_entry.strand != neighbour_new_entry.strand:",
"lcbs, skip one-entry ones for lcb in alignment.get_sorted_lcbs(0): if len(lcb.entries) == 1: realigned.add_lcb(lcb)",
"min(seq_end, min_orig_seq_length) # N-stretches in sequences # find N-stretch between start and interval",
"match.query_end seq_one_list.append(\"-\" * seq_len) seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else: return None, None class",
"# check border length if i[0] == 0 # start of block or",
"if better than old one #if border_aln_length > 0: # print(aln_seq_one) # print(aln_seq_two)",
"of sequences! seq_start = max(seq_start, 0) min_orig_seq_length = min(len(seq_one), len(seq_two)) seq_end = min(seq_end,",
"if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence = (\"-\" * nr_gaps) + neighbour_consensus_entry.sequence #",
"not include sequence ends if match.hit_end < len(seq_one): seq_len = len(seq_one) - match.hit_end",
"if len(lcb.entries) == 1: if lcb.entries[0].strand == \"-\": lcb.reverse_complement_entries() if lcb.entries[0].genome_nr == 1:",
"seq_start = max(seq_start, 0) min_orig_seq_length = min(len(seq_one), len(seq_two)) seq_end = min(seq_end, min_orig_seq_length) #",
"for i in range(len(lcbs)): lcb = lcbs[i] new_entry = lcb.get_entry(new_genome_nr) consensus_entry = lcb.get_entry(consensus_genome_nr)",
"new_genome_nr, block_length): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() lcbs = alignment.get_sorted_lcbs(new_genome_nr) # do",
"seq_start) < 1000: #https://github.com/biopython/biopython/pull/782 alignments = pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5, -0.1, #default one_alignment_only=True) if",
"neighbour_new_entry.sequence = new_entry.sequence + sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence = (\"-\"",
"_check_tuple_overlap(match.hit_range_all) exclude_keys = exclude_keys + _check_tuple_overlap(match.query_range_all) hspfrag_keys = list(set(range(len(match.hit_range_all))) - set(exclude_keys)) hspfrag_key_num =",
"seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one = match.aln[0] if seq_rec_one.id == \"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq))",
"= [item for item, count in collections.Counter(location_list).items() if count > 1] regions =",
"if not strand: # if all entries have an unequal strand reverse complement",
"lcbs = alignment.get_sorted_lcbs(new_genome_nr) # do not create small (less bp than blocklength) LCBs",
"if not (seq_one_nogap == '' or seq_two_nogap == ''): # else: do nothing",
"> 0: # print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end]) seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\",",
"is small and only created by splitting or aligning of new genome (consensus",
"= alignment.genomes[2] pairlcbs = [] for lcb in alignment.lcbs: if len(lcb.entries) == 1:",
"first hit has highest score per definition of blat match = align_result[0][0] #",
"import math from Bio import pairwise2 from seqseqpan.base import * class Separator: def",
"print(\"ERROR: I don't want to think about cases with more than 2 genomes",
"<= border_aln_length for i in interval # check border length if i[0] ==",
"interval_start = interval[max_index][0] - index_offset interval_end = interval[max_index][1] - index_offset # border_aln_length not",
"+= ((seq_end - seq_start) - max_length) return seq_one, seq_two def _external_blat(self, seq_one, seq_two,",
"fragments are overlapping! exclude_keys = _check_tuple_overlap(match.hit_range_all) exclude_keys = exclude_keys + _check_tuple_overlap(match.query_range_all) hspfrag_keys =",
"seq_two equals query # only one query and first hit has highest score",
"class SingletonAligner: def genome_count_split(self, alignment): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() single_alignment_1 =",
"return regions def _realign(self, seq_one, seq_two, realign_regions, processor, border_aln_length): # if border_aln_length is",
"prev_new_entry neighbour_lcb = prev_lcb if neighbour_new_entry.strand == \"+\": append = True else: prepend",
"_check_tuple_overlap(tuple_list): num_tuple = len(tuple_list) last_ok_end = -1 exclude_idx = [] #overlap_detected = False",
"- 1] = alignment.genomes[nr] del alignment.genomes[max_genome] return alignment else: raise ParameterError(\"remove_genome\", rm_genome, \"between",
"range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb]) else: break alignment.lcbs[:]",
"use_prev = False use_next = False prev_gap = False next_gap = False to_reverse_complement",
"reduce genome nr (avoid looping through entries twice if gaps present) else: for",
"nothing for current interval if (seq_end - seq_start) < 1000: #https://github.com/biopython/biopython/pull/782 alignments =",
"nr) for order in alignment.genomes: if len(alignment.lcbs) > 1: # if more than",
"if more than one entry left search for gaps that are present in",
"- 1].entries[entry].genome_nr \\ or alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb - 1].entries[entry].end != 1 \\ or",
"False use_prev = False use_next = False prev_gap = False next_gap = False",
"* 1.5) # get surrounding sequences seq_start = interval_start - max_seq_length seq_end =",
"for idx in range(num_tuple): if tuple_list[idx][0] < last_ok_end: #current start smaller than last",
"seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\", \"\") if not (seq_one_nogap == '' or seq_two_nogap == ''):",
"that are present in all remaining entries rm_gaps = set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k])) for",
"alignment.genomes[max_genome] return alignment else: raise ParameterError(\"remove_genome\", rm_genome, \"between 0 and \" + str(len(alignment.genomes))",
"alignment.genomes.items(): new_alignment.add_genome(genome, nr) for order in alignment.genomes: if len(alignment.lcbs) > 1: # if",
"= alignments[0][0] aln_seq_two = alignments[0][1] else: # no alignment, do nothing for current",
"interval_start) if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) # find",
"class Separator: def separate_lcbs(self, alignment, length): separated = Alignment(alignment.xmfa_file) for nr, genome in",
"not None align only sequences at block border up to given length realign_regions",
"range(hspfrag_key_num): hspfrag_key = hspfrag_keys[hspfrag_idx] hspfrag = match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) # add sequences between",
"of block or ((i[1] - index_offset) == len(seq_one)) # end of block or",
"aln_seq_one, aln_seq_two = self._external_blat(seq_one_nogap, seq_two_nogap, processor) if aln_seq_one is not None: max_length =",
"border_aln_length=0): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() realigned = Alignment(alignment.xmfa_file) for nr, genome",
"created by splitting or aligning of new genome (consensus is None) if consensus_entry",
"pairlcbs return alignment, single_alignment_1, single_alignment_2 def join(self, alignment, alignment_two): if len(alignment.genomes) > 2:",
"for nr, genome in alignment.genomes.items(): separated.add_genome(genome, nr) for lcb in alignment.lcbs: if lcb.length",
"seq_two[seq_end:]]) index_offset += ((seq_end - seq_start) - max_length) return seq_one, seq_two def _external_blat(self,",
"be neither appended nor prepended # add LCBs to alignment as it is",
"else: entry_one = lcb.entries[0] entry_two = lcb.entries[1] # get regions to realign one_first_two_second",
"= False use_prev = False use_next = False prev_gap = False next_gap =",
"overlapping or consecutive gaps in two sequences # if border_aln_length is not None",
"-> store end return exclude_idx align_result = processor.external_blat(seq_one, seq_two) if align_result is not",
"True if (prev_new_entry.strand == \"+\" and prev_new_entry.sequence[-1] == \"-\") \\ or ( prev_new_entry.strand",
"after nearest stretch n_stretch_length = 10 n_stretch = 'N' * n_stretch_length n_stretch_idx =",
"only one lcb left check whether it is already checked or not elif",
"match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented: # in really rare cases fragments are overlapping! exclude_keys",
"if len(lcb.entries) == 1: realigned.add_lcb(lcb) else: entry_one = lcb.entries[0] entry_two = lcb.entries[1] #",
"in alignment.get_sorted_lcbs(0): if len(lcb.entries) == 1: realigned.add_lcb(lcb) else: entry_one = lcb.entries[0] entry_two =",
"get regions to realign for updated entries with second entry first two_first_one_second =",
"\"-\") \\ or ( prev_new_entry.strand == \"-\" and prev_new_entry.sequence[0] == \"-\"): prev_gap =",
"self._get_realign_regions(entry_two.gaps, entry_one.gaps) if len(two_first_one_second) > 0: seq_two, seq_one = self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second, processor,",
"and (new_entry.start - prev_new_entry.end) == 1: use_prev = True if (prev_new_entry.strand == \"+\"",
"if consensus_entry is None and new_entry is not None and len(new_entry.sequence) <= block_length:",
"alignment.genomes[2] pairlcbs = [] for lcb in alignment.lcbs: if len(lcb.entries) == 1: if",
"for lcb in alignment.lcbs if len(lcb.entries) > 0] max_genome = len(alignment.genomes) for nr",
"be merged or could be neither appended nor prepended # add LCBs to",
"= None # check if new entry is small and only created by",
"if len(alignment.genomes) > 2: print(\"ERROR: I don't want to think about cases with",
"alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb - 1].entries[0].strand for entry in range(0, len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr !=",
"intervals of consecutive gap positions for faster join() gap_ranges = [] for k,",
"processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two new_lcb = LCB() new_lcb.add_entries([entry_one, entry_two])",
"alignment.lcbs[lcb].get_entry(order) is not None: i = 0 if len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb - 1].entries):",
"lcb.get_entry(consensus_genome_nr) prepend = False append = False use_prev = False use_next = False",
"seq_two[seq_start:seq_end].replace(\"-\", \"\") if not (seq_one_nogap == '' or seq_two_nogap == ''): # else:",
"separated.add_genome(genome, nr) for lcb in alignment.lcbs: if lcb.length <= length: for entry in",
"lcb.entries: entry.genome_nr = genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return alignment class Remover: def remove(self, alignment, rm_genome):",
"aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two = aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset += ((seq_end - seq_start) - max_length)",
"if not checked yet add it as last lcb and finish break else:",
"for x in alignments]) alignments = (lambda max_length=max_length: [item for item in alignments",
"def _external_blat(self, seq_one, seq_two, processor): def _check_tuple_overlap(tuple_list): num_tuple = len(tuple_list) last_ok_end = -1",
"now.\") genome_names_one = [genome.file_path for genome in alignment.genomes.values()] genome_names_two = [genome.file_path for genome",
"0 for interval in realign_regions: max_index, max_seq_length = max( enumerate([interval[0][1] - interval[0][0], interval[1][1]",
"of new genome (consensus is None) if consensus_entry is None and new_entry is",
"match[hspfrag_keys[hspfrag_idx + 1]] inter_hit_len = next_hspfrag.hit_start - hspfrag.hit_end if inter_hit_len > 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start])",
"current interval if (seq_end - seq_start) < 1000: #https://github.com/biopython/biopython/pull/782 alignments = pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(),",
"inter_hit_len > 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" * inter_hit_len) inter_query_len = next_hspfrag.query_start - hspfrag.query_end if",
"new_alignment.add_lcb(alignment.lcbs[lcb]) break else: i += 1 if i == len(alignment.lcbs[lcb].entries): if not strand:",
"# print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end]) seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\", \"\") if",
"start or end of block if border_aln_length == 0 or any(short_border_intervals): # check",
"whether it is already checked or not elif len(alignment.lcbs) == 1 and new_alignment.lcbs[-1].entries[0].genome_nr",
"lcb.length <= length: for entry in lcb.entries: seq = entry.sequence.replace(\"-\", \"\") new_entry =",
"gaps at start or end of block short_border_intervals = [(i[1] - i[0]) <=",
"if len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb - 1].entries): strand = alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb - 1].entries[0].strand",
"+ \" (number of genomes in XMFA)\") def merge(self, alignment): for lcb in",
"to given length realign_regions = sorted(realign_regions) index_offset = 0 for interval in realign_regions:",
"== 1: use_next = True if (next_new_entry.strand == \"+\" and next_new_entry.sequence[0] == \"-\")\\",
"= entry.sequence.replace(\"-\", \"\") new_entry = SequenceEntry(entry.genome_nr, entry.start, entry.end, entry.strand, seq) separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb)",
"[] if match.hit_start > 0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" * match.hit_start) if match.query_start > 0:",
"sequence entries[0].sequence = entries[0].sequence.replace(\"-\", \"\") if entries[0].genome_nr > rm_genome: entries[0].genome_nr -= 1 else:",
"seq_start, interval_start) if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) n_stretch_idx",
"region_starts = [item for item, count in collections.Counter(location_list).items() if count > 1] regions",
"the one with gap at start or end if (not next_gap) and use_prev:",
"- seq_start) - max_length) return seq_one, seq_two def _external_blat(self, seq_one, seq_two, processor): def",
"for entry in lcb.entries: entry.genome_nr = genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return alignment class Remover: def",
"* class Separator: def separate_lcbs(self, alignment, length): separated = Alignment(alignment.xmfa_file) for nr, genome",
"= entries[0].sequence.replace(\"-\", \"\") if entries[0].genome_nr > rm_genome: entries[0].genome_nr -= 1 else: for entry",
"in entries[1:]: rm_gaps &= set( itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for k in entry.gaps])) rm_gaps =",
"1: # if more than one lcb is unchecked try to merge alignment.lcbs",
"consensus_entry = lcb.get_entry(consensus_genome_nr) prepend = False append = False use_prev = False use_next",
"neighbour_new_entry.strand: to_reverse_complement = True if append or prepend: if to_reverse_complement: new_entry.reverse_complement() sequence =",
"of block if border_aln_length == 0 or any(short_border_intervals): # check if interval only",
"= len(aln_seq_one) else: # no alignment, do nothing for current interval break if",
"# only use new alignment if better than old one #if border_aln_length >",
"Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): merged.add_genome(genome, nr) for lcb in merged_split_lcbs: merged.add_lcb(lcb)",
"# are there any entries left in LCB? if len(entries) > 1: #",
"del alignment.genomes[max_genome] return alignment else: raise ParameterError(\"remove_genome\", rm_genome, \"between 0 and \" +",
"if tuple_list[idx][0] < last_ok_end: #current start smaller than last end -> exclude exclude_idx.append(idx)",
"in alignment.lcbs: lcb.entries = sorted(lcb.entries, key=lambda entry: entry.genome_nr) new_alignment = Alignment(alignment.xmfa_file) for nr,",
"in range(rm_genome + 1, max_genome + 1): alignment.genomes[nr - 1] = alignment.genomes[nr] del",
"* inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one = match.aln[0] if seq_rec_one.id == \"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq))",
"merged = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): merged.add_genome(genome, nr) for lcb in",
"is already checked or not elif len(alignment.lcbs) == 1 and new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr:",
"seq_end) n_stretch_idx_two = seq_two.find(n_stretch, interval_end, seq_end) seq_end = min(seq_end, (n_stretch_idx_one if n_stretch_idx_one >",
"if that starts with a gap if len(lcbs) > (i+1): next_lcb = lcbs[i",
"+ new_entry.sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence += (\"-\" * nr_gaps) elif",
"if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence += (\"-\" * nr_gaps) elif prepend: neighbour_new_entry.sequence",
"== \"+\": append = True else: prepend = True elif use_next: neighbour_new_entry =",
"alignment.genomes: if len(alignment.lcbs) > 1: # if more than one lcb is unchecked",
"- index_offset # border_aln_length not set OR small sequence at start or end",
"entry: entry.genome_nr) new_alignment = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): new_alignment.add_genome(genome, nr) for",
"= lcb.entries[0] entry_two = lcb.entries[1] # get regions to realign one_first_two_second = self._get_realign_regions(entry_one.gaps,",
"# current tuple is ok -> store end return exclude_idx align_result = processor.external_blat(seq_one,",
"else: # do external blat alignment aln_seq_one, aln_seq_two = self._external_blat(seq_one_nogap, seq_two_nogap, processor) if",
"== \"+\" and next_new_entry.sequence[0] == \"-\")\\ or (next_new_entry.strand == \"-\" and next_new_entry.sequence[-1] ==",
"for entry in entries[1:]: rm_gaps &= set( itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for k in entry.gaps]))",
"sub-sequence after nearest stretch n_stretch_length = 10 n_stretch = 'N' * n_stretch_length n_stretch_idx",
"- seq_start ): # only use new alignment if better than old one",
"seq_one entry_two.sequence = seq_two # get regions to realign for updated entries with",
"in alignment.lcbs if len(lcb.entries) > 0] max_genome = len(alignment.genomes) for nr in range(rm_genome",
"(\"-\" * nr_gaps) + neighbour_consensus_entry.sequence # entry should not be merged or could",
"tuple_list[idx][0] < last_ok_end: #current start smaller than last end -> exclude exclude_idx.append(idx) else:",
"exclude_keys = _check_tuple_overlap(match.hit_range_all) exclude_keys = exclude_keys + _check_tuple_overlap(match.query_range_all) hspfrag_keys = list(set(range(len(match.hit_range_all))) - set(exclude_keys))",
"[(-1, -1)] + gap_ranges if gap_ranges[-1] != lcb.length: gap_ranges = gap_ranges + [(lcb.length,",
"in alignment.lcbs: entries = [entry for entry in lcb.entries if entry.genome_nr != rm_genome]",
"for k, g in itertools.groupby(enumerate(rm_gaps), lambda x: x[0] - x[1]): group = list(map(itemgetter(1),",
"None: i = 0 if len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb - 1].entries): strand = alignment.lcbs[lcb].entries[0].strand",
"2: single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb) alignment.lcbs = pairlcbs return alignment, single_alignment_1, single_alignment_2 def join(self,",
"last end -> exclude exclude_idx.append(idx) else: last_ok_end = tuple_list[idx][1] # current tuple is",
"neighbour_new_entry.end = max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start = min(new_entry.start, neighbour_new_entry.start) if append: neighbour_new_entry.sequence = sequence",
"a gap if len(merged_split_lcbs) > 0: prev_lcb = merged_split_lcbs[-1] prev_new_entry = prev_lcb.get_entry(new_genome_nr) if",
"> 0: seq_two, seq_one = self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second, processor, border_aln_length) entry_one.sequence = seq_one",
"len(lcb.entries): # are there any entries left in LCB? if len(entries) > 1:",
"rm_genome: entry.genome_nr -= 1 lcb.entries[:] = entries alignment.lcbs[:] = [lcb for lcb in",
"len(seq_two): seq_len = len(seq_two) - match.query_end seq_one_list.append(\"-\" * seq_len) seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper()",
"gaps present) else: for entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr -=",
"new_entry.end) == 1: use_next = True if (next_new_entry.strand == \"+\" and next_new_entry.sequence[0] ==",
"max_seq_length = max( enumerate([interval[0][1] - interval[0][0], interval[1][1] - interval[1][0]]), key=lambda p: p[1]) #",
"lcb.entries[:] = entries alignment.lcbs[:] = [lcb for lcb in alignment.lcbs if len(lcb.entries) >",
"in merged_split_lcbs: merged.add_lcb(lcb) return merged class Realigner: # local realignment around overlapping or",
"entries[0].gaps[k])) for k in entries[0].gaps])) for entry in entries[1:]: rm_gaps &= set( itertools.chain.from_iterable([list(range(k,",
"entries[1:]: rm_gaps &= set( itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for k in entry.gaps])) rm_gaps = sorted(list(rm_gaps))",
"#https://github.com/biopython/biopython/pull/782 alignments = pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5, -0.1, #default one_alignment_only=True) if len(alignments) > 0:",
"entry left search for gaps that are present in all remaining entries rm_gaps",
"single_alignment_2 = Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] = alignment.genomes[1] single_alignment_2.genomes[2] = alignment.genomes[2] pairlcbs = [] for",
"entry.genome_nr -= 1 lcb.entries[:] = entries alignment.lcbs[:] = [lcb for lcb in alignment.lcbs",
"lcb.reverse_complement_entries() if lcb.entries[0].genome_nr == 1: single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr == 2: single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb)",
"start or end of block short_border_intervals = [(i[1] - i[0]) <= border_aln_length for",
"if that ends with a gap if len(merged_split_lcbs) > 0: prev_lcb = merged_split_lcbs[-1]",
"entries alignment.lcbs[:] = [lcb for lcb in alignment.lcbs if len(lcb.entries) > 0] max_genome",
"entry_two.sequence, one_first_two_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two # get regions",
"ends_dict = {end: start for start, end in gaps_for_end.items()} location_list = [start for",
"in collections.Counter(location_list).items() if count > 1] regions = [] for start in region_starts:",
"if (not next_gap) and use_prev: neighbour_new_entry = prev_new_entry neighbour_lcb = prev_lcb if neighbour_new_entry.strand",
"if align_result is not None: # seq_one equals hit seq_two equals query #",
"alignment_two.genomes.values()] if genome_names_one.sort() != genome_names_two.sort(): print(\"ERROR: Can only join alignments from same set",
"(n_stretch_idx + n_stretch_length)) # find N-stretch between interval and end and end sub-sequence",
"stretch n_stretch_length = 10 n_stretch = 'N' * n_stretch_length n_stretch_idx = seq_one.rfind(n_stretch, seq_start,",
"realign_regions, processor, border_aln_length): # if border_aln_length is not None align only sequences at",
"about cases with more than 2 genomes now.\") genome_names_one = [genome.file_path for genome",
"\"-\")\\ or (next_new_entry.strand == \"-\" and next_new_entry.sequence[-1] == \"-\"): next_gap = True neighbour_new_entry",
"end and end sub-sequence before nearest stretch n_stretch_idx_one = seq_one.find(n_stretch, interval_end, seq_end) n_stretch_idx_two",
"def join(self, alignment, alignment_two): if len(alignment.genomes) > 2: print(\"ERROR: I don't want to",
"of gaps at start or end of block short_border_intervals = [(i[1] - i[0])",
"all remaining entries rm_gaps = set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k])) for k in entries[0].gaps])) for",
"to previous entry and if that ends with a gap if len(merged_split_lcbs) >",
"None align only sequences at block border up to given length realign_regions =",
"entry_two.sequence = seq_two new_lcb = LCB() new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb) return realigned def _get_realign_regions(self,",
"for start, end in gaps_for_end.items()} location_list = [start for start, end in gaps_for_start.items()]",
"alignment aln_seq_one, aln_seq_two = self._external_blat(seq_one_nogap, seq_two_nogap, processor) if aln_seq_one is not None: max_length",
"gaps that are present in all remaining entries rm_gaps = set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k]))",
"len(lcb.entries) == 1: realigned.add_lcb(lcb) else: entry_one = lcb.entries[0] entry_two = lcb.entries[1] # get",
"realigned = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): realigned.add_genome(genome, nr) # go through",
"False next_gap = False to_reverse_complement = False next_new_entry = None prev_new_entry = None",
"alignment.lcbs[j:len(alignment.lcbs)] # continue with unchecked lcbs # if only one lcb left check",
"> -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) # find N-stretch between interval",
"prev_gap = True # check if can be prepended to next entry and",
"neighbour_lcb = prev_lcb if neighbour_new_entry.strand == \"+\": append = True else: prepend =",
"1 if i == len(alignment.lcbs[lcb].entries): if not strand: # if all entries have",
"in sequence entries[0].sequence = entries[0].sequence.replace(\"-\", \"\") if entries[0].genome_nr > rm_genome: entries[0].genome_nr -= 1",
"> 0 and max_length < ( seq_end - seq_start ): # only use",
"to remove? if len(entries) < len(lcb.entries): # are there any entries left in",
"= match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) # add sequences between aligned intervals to sequences if",
"> 0: seq_one_list.append(\"-\" * inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one = match.aln[0] if seq_rec_one.id ==",
"neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence = (\"-\" * nr_gaps) + neighbour_consensus_entry.sequence # entry",
"[] for i in range(len(lcbs)): lcb = lcbs[i] new_entry = lcb.get_entry(new_genome_nr) consensus_entry =",
"collections import itertools from operator import itemgetter import math from Bio import pairwise2",
"gaps_for_end): ends_dict = {end: start for start, end in gaps_for_end.items()} location_list = [start",
"for lcb in alignment.lcbs: lcb.entries = sorted(lcb.entries, key=lambda entry: entry.genome_nr) new_alignment = Alignment(alignment.xmfa_file)",
"== \"-\" and prev_new_entry.sequence[0] == \"-\"): prev_gap = True # check if can",
"alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb - 1].entries[entry].end != 1 \\ or (alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb -",
"next_new_entry.sequence[-1] == \"-\"): next_gap = True neighbour_new_entry = None # if both, choose",
"alignments]) alignments = (lambda max_score=max_score: [item for item in alignments if item[2] ==",
"- match.query_end seq_one_list.append(\"-\" * seq_len) seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else: return None, None",
"if alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb - 1].entries[entry].genome_nr \\ or alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb - 1].entries[entry].end",
"== 2: single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb) alignment.lcbs = pairlcbs return alignment, single_alignment_1, single_alignment_2 def",
"== len(alignment.lcbs[lcb].entries): if not strand: # if all entries have an unequal strand",
"n_stretch_length n_stretch_idx = seq_one.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start = max(seq_start,",
"for lcb in alignment.lcbs: if len(lcb.entries) == 1: if lcb.entries[0].strand == \"-\": lcb.reverse_complement_entries()",
"start, end in gaps_for_start.items()] + list(ends_dict.keys()) region_starts = [item for item, count in",
"None align only sequences at block border up to given length def realign(self,",
"LCB include entry of genome to remove? if len(entries) < len(lcb.entries): # are",
"not set OR small sequence at start or end of block if border_aln_length",
"sequences! seq_start = max(seq_start, 0) min_orig_seq_length = min(len(seq_one), len(seq_two)) seq_end = min(seq_end, min_orig_seq_length)",
"= 'N' * max_seq_length if not (seq_one[interval_start:interval_end] == n_stretch or seq_two[interval_start:interval_end] == n_stretch):",
"= alignment.lcbs[j:len(alignment.lcbs)] # continue with unchecked lcbs # if only one lcb left",
"0 and \" + str(len(alignment.genomes)) + \" (number of genomes in XMFA)\") def",
"operator import itemgetter import math from Bio import pairwise2 from seqseqpan.base import *",
"nr_gaps) elif prepend: neighbour_new_entry.sequence = new_entry.sequence + sequence if neighbour_consensus_entry is not None:",
"alignment_two.genomes[1].file_path: genome_nr_dict = {1: 2, 2: 1} else: genome_nr_dict = {1: 1, 2:",
"border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two new_lcb = LCB() new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb)",
"gap_ranges[0][0] != 0: gap_ranges = [(-1, -1)] + gap_ranges if gap_ranges[-1] != lcb.length:",
"seq_two = aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset += ((seq_end - seq_start) - max_length) return seq_one,",
"to merge alignment.lcbs = alignment.get_sorted_lcbs(order) j = 0 if alignment.lcbs[0].get_entry(order) is not None:",
"consecutive gaps in two sequences # if border_aln_length is not None align only",
"to_reverse_complement = True if append or prepend: if to_reverse_complement: new_entry.reverse_complement() sequence = neighbour_new_entry.sequence",
"if inter_hit_len > 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" * inter_hit_len) inter_query_len = next_hspfrag.query_start - hspfrag.query_end",
"= -1 exclude_idx = [] #overlap_detected = False for idx in range(num_tuple): if",
"if only one lcb left check whether it is already checked or not",
"lcb in alignment.lcbs: lcb.entries = sorted(lcb.entries, key=lambda entry: entry.genome_nr) new_alignment = Alignment(alignment.xmfa_file) for",
"> 2: print(\"ERROR: I don't want to think about cases with more than",
"lcb in alignment.get_sorted_lcbs(0): if len(lcb.entries) == 1: realigned.add_lcb(lcb) else: entry_one = lcb.entries[0] entry_two",
"sequences # find N-stretch between start and interval and start sub-sequence after nearest",
"previous entry and if that ends with a gap if len(merged_split_lcbs) > 0:",
"True # check if can be prepended to next entry and if that",
"for k in entry.gaps])) rm_gaps = sorted(list(rm_gaps)) # make intervals of consecutive gap",
"pairlcbs = [] for lcb in alignment.lcbs: if len(lcb.entries) == 1: if lcb.entries[0].strand",
"== max_score])() max_length = min([x[4] for x in alignments]) alignments = (lambda max_length=max_length:",
"in alignments]) alignments = (lambda max_length=max_length: [item for item in alignments if item[4]",
"seq_start) - max_length) return seq_one, seq_two def _external_blat(self, seq_one, seq_two, processor): def _check_tuple_overlap(tuple_list):",
"prev_lcb = merged_split_lcbs[-1] prev_new_entry = prev_lcb.get_entry(new_genome_nr) if prev_new_entry is not None and (new_entry.start",
"in entry.gaps])) rm_gaps = sorted(list(rm_gaps)) # make intervals of consecutive gap positions for",
"in region_starts: regions.append([(start, gaps_for_start[start]), (ends_dict[start], start)]) return regions def _realign(self, seq_one, seq_two, realign_regions,",
"lcb in alignment_two.lcbs: for entry in lcb.entries: entry.genome_nr = genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return alignment",
"-1: for lcb in alignment.lcbs: entries = [entry for entry in lcb.entries if",
"i in range(len(gap_ranges) - 1)]) if entry.genome_nr > rm_genome: entry.genome_nr -= 1 #",
"in range(len(gap_ranges) - 1)]) if entry.genome_nr > rm_genome: entry.genome_nr -= 1 # if",
"seq_one, seq_two def _external_blat(self, seq_one, seq_two, processor): def _check_tuple_overlap(tuple_list): num_tuple = len(tuple_list) last_ok_end",
"+ 1] next_new_entry = next_lcb.get_entry(new_genome_nr) if next_new_entry is not None and (next_new_entry.start -",
"separate_lcbs(self, alignment, length): separated = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): separated.add_genome(genome, nr)",
"== len(seq_two))] # end of block interval_start = interval[max_index][0] - index_offset interval_end =",
"neighbour_new_entry.start) if append: neighbour_new_entry.sequence = sequence + new_entry.sequence if neighbour_consensus_entry is not None:",
"_check_tuple_overlap(match.query_range_all) hspfrag_keys = list(set(range(len(match.hit_range_all))) - set(exclude_keys)) hspfrag_key_num = len(hspfrag_keys) for hspfrag_idx in range(hspfrag_key_num):",
"entry.gaps])) rm_gaps = sorted(list(rm_gaps)) # make intervals of consecutive gap positions for faster",
"= gap_ranges + [(lcb.length, lcb.length)] for entry in entries: entry.sequence = ''.join( [entry.sequence[(gap_ranges[i][1]",
"entry should not be merged or could be neither appended nor prepended #",
"block interval_start = interval[max_index][0] - index_offset interval_end = interval[max_index][1] - index_offset # border_aln_length",
"single_alignment_1.genomes[1] = alignment.genomes[1] single_alignment_2.genomes[2] = alignment.genomes[2] pairlcbs = [] for lcb in alignment.lcbs:",
"seq_two def _external_blat(self, seq_one, seq_two, processor): def _check_tuple_overlap(tuple_list): num_tuple = len(tuple_list) last_ok_end =",
"== \"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) # add last sequence parts if",
"alignment.lcbs[lcb - 1].entries[0].strand for entry in range(0, len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb -",
"aln_seq_two = self._external_blat(seq_one_nogap, seq_two_nogap, processor) if aln_seq_one is not None: max_length = len(aln_seq_one)",
"= True else: append = True if neighbour_new_entry is not None: if new_entry.strand",
"or aligning of new genome (consensus is None) if consensus_entry is None and",
"do nothing for current interval break if max_length > 0 and max_length <",
"= True if append or prepend: if to_reverse_complement: new_entry.reverse_complement() sequence = neighbour_new_entry.sequence neighbour_consensus_entry",
"= min(seq_end, min_orig_seq_length) # N-stretches in sequences # find N-stretch between start and",
"= prev_lcb if neighbour_new_entry.strand == \"+\": append = True else: prepend = True",
"(seq_one_nogap == '' or seq_two_nogap == ''): # else: do nothing for current",
"0: seq_one_list.append(\"-\" * match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented: # in really rare cases fragments",
"max_seq_length = math.ceil(max_seq_length * 1.5) # get surrounding sequences seq_start = interval_start -",
"from Bio import pairwise2 from seqseqpan.base import * class Separator: def separate_lcbs(self, alignment,",
"if to_reverse_complement: new_entry.reverse_complement() sequence = neighbour_new_entry.sequence neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length += nr_gaps neighbour_new_entry.end",
"= pairlcbs return alignment, single_alignment_1, single_alignment_2 def join(self, alignment, alignment_two): if len(alignment.genomes) >",
"genome in alignment.genomes.items(): separated.add_genome(genome, nr) for lcb in alignment.lcbs: if lcb.length <= length:",
"seq) separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb) return separated class Merger: def merge_lcbs(self, alignment, consensus_genome_nr, new_genome_nr,",
"n_stretch_idx = seq_one.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx",
") #if border_aln_length > 0: # print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end]) seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\", \"\")",
"= True if (next_new_entry.strand == \"+\" and next_new_entry.sequence[0] == \"-\")\\ or (next_new_entry.strand ==",
"single_alignment_2 def join(self, alignment, alignment_two): if len(alignment.genomes) > 2: print(\"ERROR: I don't want",
"= None # if both, choose the one with gap at start or",
"neighbour_lcb = next_lcb if neighbour_new_entry.strand == \"+\": prepend = True else: append =",
"1):gap_ranges[i + 1][0]] for i in range(len(gap_ranges) - 1)]) if entry.genome_nr > rm_genome:",
"index_offset) == len(seq_two))] # end of block interval_start = interval[max_index][0] - index_offset interval_end",
"== n_stretch): max_seq_length = math.ceil(max_seq_length * 1.5) # get surrounding sequences seq_start =",
"new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb]) else: break alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)]",
"1): alignment.genomes[nr - 1] = alignment.genomes[nr] del alignment.genomes[max_genome] return alignment else: raise ParameterError(\"remove_genome\",",
"external blat alignment aln_seq_one, aln_seq_two = self._external_blat(seq_one_nogap, seq_two_nogap, processor) if aln_seq_one is not",
"0 or any(short_border_intervals): # check if interval only 'N' - if yes: do",
"# check if interval only 'N' - if yes: do not realign n_stretch",
"N-stretches in sequences # find N-stretch between start and interval and start sub-sequence",
"= alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb - 1].entries[0].strand for entry in range(0, len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr",
"regions def _realign(self, seq_one, seq_two, realign_regions, processor, border_aln_length): # if border_aln_length is not",
"len(alignments) > 0: max_score = max([x[2] for x in alignments]) alignments = (lambda",
"blat alignment aln_seq_one, aln_seq_two = self._external_blat(seq_one_nogap, seq_two_nogap, processor) if aln_seq_one is not None:",
"nearest stretch n_stretch_idx_one = seq_one.find(n_stretch, interval_end, seq_end) n_stretch_idx_two = seq_two.find(n_stretch, interval_end, seq_end) seq_end",
"= Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] = alignment.genomes[1] single_alignment_2.genomes[2] = alignment.genomes[2] pairlcbs = [] for lcb",
"there any entries left in LCB? if len(entries) > 1: # if more",
"itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for k in entry.gaps])) rm_gaps = sorted(list(rm_gaps)) # make intervals of",
"realign one_first_two_second = self._get_realign_regions(entry_one.gaps, entry_two.gaps) if len(one_first_two_second) > 0: seq_one, seq_two = self._realign(entry_one.sequence,",
"\" (number of genomes in XMFA)\") def merge(self, alignment): for lcb in alignment.lcbs:",
"sequence merged_split_lcbs = [] for i in range(len(lcbs)): lcb = lcbs[i] new_entry =",
"or end if (not next_gap) and use_prev: neighbour_new_entry = prev_new_entry neighbour_lcb = prev_lcb",
"[] for start in region_starts: regions.append([(start, gaps_for_start[start]), (ends_dict[start], start)]) return regions def _realign(self,",
"if lcb.entries[0].genome_nr == 1: single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr == 2: single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb) alignment.lcbs",
"alignment.lcbs: lcb.entries = sorted(lcb.entries, key=lambda entry: entry.genome_nr) new_alignment = Alignment(alignment.xmfa_file) for nr, genome",
"= self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two #",
"hspfrag_keys[hspfrag_idx] hspfrag = match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) # add sequences between aligned intervals to",
"math from Bio import pairwise2 from seqseqpan.base import * class Separator: def separate_lcbs(self,",
"if can be appended to previous entry and if that ends with a",
"True if neighbour_new_entry is not None: if new_entry.strand != neighbour_new_entry.strand: to_reverse_complement = True",
"len(alignment.genomes) >= rm_genome > -1: for lcb in alignment.lcbs: entries = [entry for",
"or alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb - 1].entries[entry].end != 1 \\ or (alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb",
"seq_one equals hit seq_two equals query # only one query and first hit",
"only join alignments from same set of genomes.\") if alignment.genomes[1].file_path != alignment_two.genomes[1].file_path: genome_nr_dict",
"nr, genome in alignment.genomes.items(): merged.add_genome(genome, nr) for lcb in merged_split_lcbs: merged.add_lcb(lcb) return merged",
"nr in range(rm_genome + 1, max_genome + 1): alignment.genomes[nr - 1] = alignment.genomes[nr]",
"conditions stop and do not merge this lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break else: i +=",
"not None and len(new_entry.sequence) <= block_length: nr_gaps = len(new_entry.sequence) # check if can",
"only use new alignment if better than old one #if border_aln_length > 0:",
"1: # if only one entry left replace all gaps in sequence entries[0].sequence",
"one with gap at start or end if (not next_gap) and use_prev: neighbour_new_entry",
"seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) # add last sequence parts if hit or",
"return alignment, single_alignment_1, single_alignment_2 def join(self, alignment, alignment_two): if len(alignment.genomes) > 2: print(\"ERROR:",
"else: do nothing for current interval if (seq_end - seq_start) < 1000: #https://github.com/biopython/biopython/pull/782",
"definition of blat match = align_result[0][0] # add starting sequences, in case query",
"entry.end, entry.strand, seq) separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb) return separated class Merger: def merge_lcbs(self, alignment,",
"add LCBs to alignment as it is else: merged_split_lcbs.append(lcb) merged = Alignment(alignment.xmfa_file) for",
"# get regions to realign one_first_two_second = self._get_realign_regions(entry_one.gaps, entry_two.gaps) if len(one_first_two_second) > 0:",
"0: # print(aln_seq_one) # print(aln_seq_two) seq_one = aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two = aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]])",
"and if that ends with a gap if len(merged_split_lcbs) > 0: prev_lcb =",
"case query or hit do not start at \"0\" seq_one_list = [] seq_two_list",
"checked yet add it as last lcb and finish break else: break return",
"len(hspfrag_keys) for hspfrag_idx in range(hspfrag_key_num): hspfrag_key = hspfrag_keys[hspfrag_idx] hspfrag = match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq))",
"hit do not start at \"0\" seq_one_list = [] seq_two_list = [] if",
"alignment.lcbs: if lcb.length <= length: for entry in lcb.entries: seq = entry.sequence.replace(\"-\", \"\")",
"k in entries[0].gaps])) for entry in entries[1:]: rm_gaps &= set( itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for",
"match = align_result[0][0] # add starting sequences, in case query or hit do",
"= lcb.get_entry(consensus_genome_nr) prepend = False append = False use_prev = False use_next =",
"if n_stretch_idx_one > -1 else seq_end), (n_stretch_idx_two if n_stretch_idx_two > -1 else seq_end)",
"= min(seq_end, (n_stretch_idx_one if n_stretch_idx_one > -1 else seq_end), (n_stretch_idx_two if n_stretch_idx_two >",
"'N' * max_seq_length if not (seq_one[interval_start:interval_end] == n_stretch or seq_two[interval_start:interval_end] == n_stretch): max_seq_length",
"with more than 2 genomes now.\") genome_names_one = [genome.file_path for genome in alignment.genomes.values()]",
"# find N-stretch between start and interval and start sub-sequence after nearest stretch",
"rm_genome: entry.genome_nr -= 1 # if no gaps found only reduce genome nr",
"0: seq_two, seq_one = self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence",
"max(seq_start, (n_stretch_idx + n_stretch_length)) # find N-stretch between interval and end and end",
"1].entries): strand = alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb - 1].entries[0].strand for entry in range(0, len(alignment.lcbs[lcb].entries)):",
"is not None: neighbour_consensus_entry.sequence += (\"-\" * nr_gaps) elif prepend: neighbour_new_entry.sequence = new_entry.sequence",
"= next_lcb if neighbour_new_entry.strand == \"+\": prepend = True else: append = True",
"n_stretch_idx_one > -1 else seq_end), (n_stretch_idx_two if n_stretch_idx_two > -1 else seq_end) )",
"# if more than one lcb is unchecked try to merge alignment.lcbs =",
"\"-\" and prev_new_entry.sequence[0] == \"-\"): prev_gap = True # check if can be",
"itertools.groupby(enumerate(rm_gaps), lambda x: x[0] - x[1]): group = list(map(itemgetter(1), g)) gap_ranges.append((group[0], group[-1])) #",
"merge alignment.lcbs = alignment.get_sorted_lcbs(order) j = 0 if alignment.lcbs[0].get_entry(order) is not None: new_alignment.add_lcb(alignment.lcbs[0])",
"have an unequal strand reverse complement this lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length for",
"up to given length def realign(self, alignment, processor, border_aln_length=0): if len(alignment.genomes) > 2:",
"gap_ranges.append((group[0], group[-1])) # tuples with intervals if len(gap_ranges) > 0: if gap_ranges[0][0] !=",
"and next_new_entry.sequence[0] == \"-\")\\ or (next_new_entry.strand == \"-\" and next_new_entry.sequence[-1] == \"-\"): next_gap",
"range(0, len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb - 1].entries[entry].genome_nr \\ or alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb",
"append = True else: prepend = True elif use_next: neighbour_new_entry = next_new_entry neighbour_lcb",
"in alignment.genomes.values()] genome_names_two = [genome.file_path for genome in alignment_two.genomes.values()] if genome_names_one.sort() != genome_names_two.sort():",
"# if only one entry left replace all gaps in sequence entries[0].sequence =",
"sequences seq_start = interval_start - max_seq_length seq_end = interval_end + max_seq_length # do",
"+ neighbour_consensus_entry.sequence # entry should not be merged or could be neither appended",
"hspfrag_keys = list(set(range(len(match.hit_range_all))) - set(exclude_keys)) hspfrag_key_num = len(hspfrag_keys) for hspfrag_idx in range(hspfrag_key_num): hspfrag_key",
"import itemgetter import math from Bio import pairwise2 from seqseqpan.base import * class",
"is not None and (new_entry.start - prev_new_entry.end) == 1: use_prev = True if",
"separated = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): separated.add_genome(genome, nr) for lcb in",
"no gaps found only reduce genome nr (avoid looping through entries twice if",
"than 2 genomes now.\") genome_names_one = [genome.file_path for genome in alignment.genomes.values()] genome_names_two =",
"processor) if aln_seq_one is not None: max_length = len(aln_seq_one) else: # no alignment,",
"def merge_lcbs(self, alignment, consensus_genome_nr, new_genome_nr, block_length): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() lcbs",
"1] = alignment.genomes[nr] del alignment.genomes[max_genome] return alignment else: raise ParameterError(\"remove_genome\", rm_genome, \"between 0",
"-1)] + gap_ranges if gap_ranges[-1] != lcb.length: gap_ranges = gap_ranges + [(lcb.length, lcb.length)]",
"\"\") if entries[0].genome_nr > rm_genome: entries[0].genome_nr -= 1 else: for entry in entries:",
"for faster join() gap_ranges = [] for k, g in itertools.groupby(enumerate(rm_gaps), lambda x:",
"def _get_realign_regions(self, gaps_for_start, gaps_for_end): ends_dict = {end: start for start, end in gaps_for_end.items()}",
"entry and if that ends with a gap if len(merged_split_lcbs) > 0: prev_lcb",
"is else: merged_split_lcbs.append(lcb) merged = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): merged.add_genome(genome, nr)",
"(number of genomes in XMFA)\") def merge(self, alignment): for lcb in alignment.lcbs: lcb.entries",
"exclude_idx = [] #overlap_detected = False for idx in range(num_tuple): if tuple_list[idx][0] <",
"separated.add_lcb(lcb) return separated class Merger: def merge_lcbs(self, alignment, consensus_genome_nr, new_genome_nr, block_length): if len(alignment.genomes)",
"or end of block if border_aln_length == 0 or any(short_border_intervals): # check if",
"entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1 elif len(entries) == 1: #",
"== ''): # else: do nothing for current interval if (seq_end - seq_start)",
"> rm_genome: entries[0].genome_nr -= 1 else: for entry in entries: if entry.genome_nr >",
"to next entry and if that starts with a gap if len(lcbs) >",
"= Alignment(alignment.xmfa_file) single_alignment_2 = Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] = alignment.genomes[1] single_alignment_2.genomes[2] = alignment.genomes[2] pairlcbs =",
"for entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1 lcb.entries[:] =",
"nearest stretch n_stretch_length = 10 n_stretch = 'N' * n_stretch_length n_stretch_idx = seq_one.rfind(n_stretch,",
"# in really rare cases fragments are overlapping! exclude_keys = _check_tuple_overlap(match.hit_range_all) exclude_keys =",
"or prepend: if to_reverse_complement: new_entry.reverse_complement() sequence = neighbour_new_entry.sequence neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length +=",
"1] regions = [] for start in region_starts: regions.append([(start, gaps_for_start[start]), (ends_dict[start], start)]) return",
"max_length = len(aln_seq_one) else: # no alignment, do nothing for current interval break",
"for interval in realign_regions: max_index, max_seq_length = max( enumerate([interval[0][1] - interval[0][0], interval[1][1] -",
"as it is else: merged_split_lcbs.append(lcb) merged = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items():",
"raise ConsensusXMFAInputError() single_alignment_1 = Alignment(alignment.xmfa_file) single_alignment_2 = Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] = alignment.genomes[1] single_alignment_2.genomes[2] =",
"n_stretch = 'N' * n_stretch_length n_stretch_idx = seq_one.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx >",
"can be appended to previous entry and if that ends with a gap",
"# did LCB include entry of genome to remove? if len(entries) < len(lcb.entries):",
"!= 0: gap_ranges = [(-1, -1)] + gap_ranges if gap_ranges[-1] != lcb.length: gap_ranges",
"(less bp than blocklength) LCBs by splitting, but append/prepend sequence merged_split_lcbs = []",
"and interval and start sub-sequence after nearest stretch n_stretch_length = 10 n_stretch =",
"if neighbour_new_entry is not None: if new_entry.strand != neighbour_new_entry.strand: to_reverse_complement = True if",
"= len(seq_one) - match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" * seq_len) if match.query_end < len(seq_two): seq_len",
"genome to remove? if len(entries) < len(lcb.entries): # are there any entries left",
"interval break else: # do external blat alignment aln_seq_one, aln_seq_two = self._external_blat(seq_one_nogap, seq_two_nogap,",
"alignment_two): if len(alignment.genomes) > 2: print(\"ERROR: I don't want to think about cases",
"0: max_score = max([x[2] for x in alignments]) alignments = (lambda max_score=max_score: [item",
"len(new_entry.sequence) <= block_length: nr_gaps = len(new_entry.sequence) # check if can be appended to",
"gaps found only reduce genome nr (avoid looping through entries twice if gaps",
"last_ok_end: #current start smaller than last end -> exclude exclude_idx.append(idx) else: last_ok_end =",
"key=lambda entry: entry.genome_nr) new_alignment = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): new_alignment.add_genome(genome, nr)",
"in range(len(lcbs)): lcb = lcbs[i] new_entry = lcb.get_entry(new_genome_nr) consensus_entry = lcb.get_entry(consensus_genome_nr) prepend =",
"consensus_entry is None and new_entry is not None and len(new_entry.sequence) <= block_length: nr_gaps",
"(seq_one[interval_start:interval_end] == n_stretch or seq_two[interval_start:interval_end] == n_stretch): max_seq_length = math.ceil(max_seq_length * 1.5) #",
"# check if new entry is small and only created by splitting or",
"[item for item, count in collections.Counter(location_list).items() if count > 1] regions = []",
"processor.external_blat(seq_one, seq_two) if align_result is not None: # seq_one equals hit seq_two equals",
"merged_split_lcbs.append(lcb) merged = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): merged.add_genome(genome, nr) for lcb",
"None) if consensus_entry is None and new_entry is not None and len(new_entry.sequence) <=",
"interval_end + max_seq_length # do not go over boundaries of sequences! seq_start =",
"seq_end - seq_start ): # only use new alignment if better than old",
"max_length > 0 and max_length < ( seq_end - seq_start ): # only",
"if match.hit_end < len(seq_one): seq_len = len(seq_one) - match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" * seq_len)",
"n_stretch_idx_two = seq_two.find(n_stretch, interval_end, seq_end) seq_end = min(seq_end, (n_stretch_idx_one if n_stretch_idx_one > -1",
"# seq_one equals hit seq_two equals query # only one query and first",
"= sorted(list(rm_gaps)) # make intervals of consecutive gap positions for faster join() gap_ranges",
"new_entry is not None and len(new_entry.sequence) <= block_length: nr_gaps = len(new_entry.sequence) # check",
"if new_entry.strand != neighbour_new_entry.strand: to_reverse_complement = True if append or prepend: if to_reverse_complement:",
"if no gaps found only reduce genome nr (avoid looping through entries twice",
"None: neighbour_consensus_entry.sequence = (\"-\" * nr_gaps) + neighbour_consensus_entry.sequence # entry should not be",
"really rare cases fragments are overlapping! exclude_keys = _check_tuple_overlap(match.hit_range_all) exclude_keys = exclude_keys +",
"> 1: # if more than one lcb is unchecked try to merge",
"not None: if new_entry.strand != neighbour_new_entry.strand: to_reverse_complement = True if append or prepend:",
"next_new_entry neighbour_lcb = next_lcb if neighbour_new_entry.strand == \"+\": prepend = True else: append",
"or ( prev_new_entry.strand == \"-\" and prev_new_entry.sequence[0] == \"-\"): prev_gap = True #",
"alignment.genomes.items(): merged.add_genome(genome, nr) for lcb in merged_split_lcbs: merged.add_lcb(lcb) return merged class Realigner: #",
"unchecked try to merge alignment.lcbs = alignment.get_sorted_lcbs(order) j = 0 if alignment.lcbs[0].get_entry(order) is",
"one entry left replace all gaps in sequence entries[0].sequence = entries[0].sequence.replace(\"-\", \"\") if",
"seq = entry.sequence.replace(\"-\", \"\") new_entry = SequenceEntry(entry.genome_nr, entry.start, entry.end, entry.strand, seq) separated.add_lcb_entries(new_entry) else:",
"if interval only 'N' - if yes: do not realign n_stretch = 'N'",
"block or ((i[1] - index_offset) == len(seq_two))] # end of block interval_start =",
"is not None align only sequences at block border up to given length",
"else: last_ok_end = tuple_list[idx][1] # current tuple is ok -> store end return",
"seq_rec_one = match.aln[0] if seq_rec_one.id == \"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) #",
"use_next: neighbour_new_entry = next_new_entry neighbour_lcb = next_lcb if neighbour_new_entry.strand == \"+\": prepend =",
"end sub-sequence before nearest stretch n_stretch_idx_one = seq_one.find(n_stretch, interval_end, seq_end) n_stretch_idx_two = seq_two.find(n_stretch,",
"== alignment.lcbs[lcb - 1].entries[0].strand for entry in range(0, len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb",
"= [] for start in region_starts: regions.append([(start, gaps_for_start[start]), (ends_dict[start], start)]) return regions def",
"entry in lcb.entries: entry.genome_nr = genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return alignment class Remover: def remove(self,",
"in alignments]) alignments = (lambda max_score=max_score: [item for item in alignments if item[2]",
"search for gaps that are present in all remaining entries rm_gaps = set(itertools.chain.from_iterable(",
"present in all remaining entries rm_gaps = set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k])) for k in",
"for entry in lcb.entries: seq = entry.sequence.replace(\"-\", \"\") new_entry = SequenceEntry(entry.genome_nr, entry.start, entry.end,",
"for gaps that are present in all remaining entries rm_gaps = set(itertools.chain.from_iterable( [list(range(k,",
"else: i += 1 if i == len(alignment.lcbs[lcb].entries): if not strand: # if",
"more than one lcb is unchecked try to merge alignment.lcbs = alignment.get_sorted_lcbs(order) j",
"i in range(len(lcbs)): lcb = lcbs[i] new_entry = lcb.get_entry(new_genome_nr) consensus_entry = lcb.get_entry(consensus_genome_nr) prepend",
"ConsensusXMFAInputError() single_alignment_1 = Alignment(alignment.xmfa_file) single_alignment_2 = Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] = alignment.genomes[1] single_alignment_2.genomes[2] = alignment.genomes[2]",
"if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) n_stretch_idx = seq_two.rfind(n_stretch,",
"if inter_query_len > 0: seq_one_list.append(\"-\" * inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one = match.aln[0] if",
"XMFA)\") def merge(self, alignment): for lcb in alignment.lcbs: lcb.entries = sorted(lcb.entries, key=lambda entry:",
"group[-1])) # tuples with intervals if len(gap_ranges) > 0: if gap_ranges[0][0] != 0:",
"merged.add_genome(genome, nr) for lcb in merged_split_lcbs: merged.add_lcb(lcb) return merged class Realigner: # local",
"= Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): new_alignment.add_genome(genome, nr) for order in alignment.genomes:",
"not fulfill all conditions stop and do not merge this lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break",
"# local realignment around overlapping or consecutive gaps in two sequences # if",
"entry.strand, seq) separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb) return separated class Merger: def merge_lcbs(self, alignment, consensus_genome_nr,",
"it is already checked or not elif len(alignment.lcbs) == 1 and new_alignment.lcbs[-1].entries[0].genome_nr !=",
"check border length if i[0] == 0 # start of block or ((i[1]",
"= _check_tuple_overlap(match.hit_range_all) exclude_keys = exclude_keys + _check_tuple_overlap(match.query_range_all) hspfrag_keys = list(set(range(len(match.hit_range_all))) - set(exclude_keys)) hspfrag_key_num",
"self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two new_lcb =",
"- match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" * seq_len) if match.query_end < len(seq_two): seq_len = len(seq_two)",
"max_score=max_score: [item for item in alignments if item[2] == max_score])() max_length = min([x[4]",
"item[2] == max_score])() max_length = min([x[4] for x in alignments]) alignments = (lambda",
"for entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1 elif len(entries)",
"else seq_end) ) #if border_aln_length > 0: # print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end]) seq_one_nogap =",
"== 1: # if only one entry left replace all gaps in sequence",
"0 and max_length < ( seq_end - seq_start ): # only use new",
"processor, border_aln_length=0): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() realigned = Alignment(alignment.xmfa_file) for nr,",
"entry.genome_nr = genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return alignment class Remover: def remove(self, alignment, rm_genome): if",
"if not (seq_one[interval_start:interval_end] == n_stretch or seq_two[interval_start:interval_end] == n_stretch): max_seq_length = math.ceil(max_seq_length *",
"seq_len) if match.query_end < len(seq_two): seq_len = len(seq_two) - match.query_end seq_one_list.append(\"-\" * seq_len)",
"(consensus is None) if consensus_entry is None and new_entry is not None and",
"- alignment.lcbs[lcb - 1].entries[entry].end != 1 \\ or (alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb - 1].entries[entry].strand)",
"> rm_genome: entry.genome_nr -= 1 # if no gaps found only reduce genome",
"realigned.add_lcb(lcb) else: entry_one = lcb.entries[0] entry_two = lcb.entries[1] # get regions to realign",
"nor prepended # add LCBs to alignment as it is else: merged_split_lcbs.append(lcb) merged",
"0: if gap_ranges[0][0] != 0: gap_ranges = [(-1, -1)] + gap_ranges if gap_ranges[-1]",
"sequence at start or end of block if border_aln_length == 0 or any(short_border_intervals):",
"gap positions for faster join() gap_ranges = [] for k, g in itertools.groupby(enumerate(rm_gaps),",
"append = True if neighbour_new_entry is not None: if new_entry.strand != neighbour_new_entry.strand: to_reverse_complement",
"merge(self, alignment): for lcb in alignment.lcbs: lcb.entries = sorted(lcb.entries, key=lambda entry: entry.genome_nr) new_alignment",
"nr, genome in alignment.genomes.items(): realigned.add_genome(genome, nr) # go through lcbs, skip one-entry ones",
"set of genomes.\") if alignment.genomes[1].file_path != alignment_two.genomes[1].file_path: genome_nr_dict = {1: 2, 2: 1}",
"if len(lcb.entries) > 0] max_genome = len(alignment.genomes) for nr in range(rm_genome + 1,",
"gap_ranges[-1] != lcb.length: gap_ranges = gap_ranges + [(lcb.length, lcb.length)] for entry in entries:",
"== n_stretch or seq_two[interval_start:interval_end] == n_stretch): max_seq_length = math.ceil(max_seq_length * 1.5) # get",
"alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) # if not checked yet add it as last lcb and",
"local realignment around overlapping or consecutive gaps in two sequences # if border_aln_length",
"block_length): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() lcbs = alignment.get_sorted_lcbs(new_genome_nr) # do not",
"= None prev_new_entry = None # check if new entry is small and",
"- index_offset) == len(seq_one)) # end of block or ((i[1] - index_offset) ==",
"> 0: # print(aln_seq_one) # print(aln_seq_two) seq_one = aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two = aln_seq_two.join([seq_two[:seq_start],",
"one query and first hit has highest score per definition of blat match",
"neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length += nr_gaps neighbour_new_entry.end = max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start = min(new_entry.start, neighbour_new_entry.start) if",
"or any(short_border_intervals): # check if interval only 'N' - if yes: do not",
"alignment.lcbs[lcb - 1].entries[entry].genome_nr \\ or alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb - 1].entries[entry].end != 1 \\",
"self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two # get",
"[genome.file_path for genome in alignment.genomes.values()] genome_names_two = [genome.file_path for genome in alignment_two.genomes.values()] if",
"[(lcb.length, lcb.length)] for entry in entries: entry.sequence = ''.join( [entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i +",
"new_alignment.add_lcb(alignment.lcbs[lcb]) else: break alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)] # continue with unchecked lcbs # if",
"= False append = False use_prev = False use_next = False prev_gap =",
"border up to given length def realign(self, alignment, processor, border_aln_length=0): if len(alignment.genomes) >",
"1 else: for entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1",
"realign n_stretch = 'N' * max_seq_length if not (seq_one[interval_start:interval_end] == n_stretch or seq_two[interval_start:interval_end]",
"break else: # do external blat alignment aln_seq_one, aln_seq_two = self._external_blat(seq_one_nogap, seq_two_nogap, processor)",
"= {1: 1, 2: 2} for lcb in alignment_two.lcbs: for entry in lcb.entries:",
"N-stretch between start and interval and start sub-sequence after nearest stretch n_stretch_length =",
"= [lcb for lcb in alignment.lcbs if len(lcb.entries) > 0] max_genome = len(alignment.genomes)",
"break if max_length > 0 and max_length < ( seq_end - seq_start ):",
"2 genomes now.\") genome_names_one = [genome.file_path for genome in alignment.genomes.values()] genome_names_two = [genome.file_path",
"= len(hspfrag_keys) for hspfrag_idx in range(hspfrag_key_num): hspfrag_key = hspfrag_keys[hspfrag_idx] hspfrag = match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq))",
"alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)] # continue with unchecked lcbs # if only one lcb",
"alignment.genomes[nr] del alignment.genomes[max_genome] return alignment else: raise ParameterError(\"remove_genome\", rm_genome, \"between 0 and \"",
"# print(seq_two[seq_start:seq_end]) seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\", \"\") if not (seq_one_nogap",
"prepend = True else: append = True if neighbour_new_entry is not None: if",
"if gaps present) else: for entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr",
"+ 1): alignment.genomes[nr - 1] = alignment.genomes[nr] del alignment.genomes[max_genome] return alignment else: raise",
"if gap_ranges[-1] != lcb.length: gap_ranges = gap_ranges + [(lcb.length, lcb.length)] for entry in",
"seq_two_list.append(\"-\" * inter_hit_len) inter_query_len = next_hspfrag.query_start - hspfrag.query_end if inter_query_len > 0: seq_one_list.append(\"-\"",
"next_gap = True neighbour_new_entry = None # if both, choose the one with",
"seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else: return None, None class SingletonAligner: def genome_count_split(self, alignment):",
"len(alignment.genomes) > 2: raise ConsensusXMFAInputError() lcbs = alignment.get_sorted_lcbs(new_genome_nr) # do not create small",
"= neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length += nr_gaps neighbour_new_entry.end = max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start = min(new_entry.start, neighbour_new_entry.start)",
"alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb - 1].entries[entry].genome_nr \\ or alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb - 1].entries[entry].end !=",
"= False use_next = False prev_gap = False next_gap = False to_reverse_complement =",
"= interval_start - max_seq_length seq_end = interval_end + max_seq_length # do not go",
"alignment.genomes[1].file_path != alignment_two.genomes[1].file_path: genome_nr_dict = {1: 2, 2: 1} else: genome_nr_dict = {1:",
"= max(seq_start, (n_stretch_idx + n_stretch_length)) n_stretch_idx = seq_two.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx >",
"> -1 else seq_end), (n_stretch_idx_two if n_stretch_idx_two > -1 else seq_end) ) #if",
"use new alignment if better than old one #if border_aln_length > 0: #",
"seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" * match.hit_start) if match.query_start > 0: seq_one_list.append(\"-\" * match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if",
"current interval break else: # do external blat alignment aln_seq_one, aln_seq_two = self._external_blat(seq_one_nogap,",
"between start and interval and start sub-sequence after nearest stretch n_stretch_length = 10",
"return exclude_idx align_result = processor.external_blat(seq_one, seq_two) if align_result is not None: # seq_one",
"in alignment.lcbs: if lcb.length <= length: for entry in lcb.entries: seq = entry.sequence.replace(\"-\",",
"1)]) if entry.genome_nr > rm_genome: entry.genome_nr -= 1 # if no gaps found",
"if entry.genome_nr > rm_genome: entry.genome_nr -= 1 # if no gaps found only",
"+ str(len(alignment.genomes)) + \" (number of genomes in XMFA)\") def merge(self, alignment): for",
"entries: entry.sequence = ''.join( [entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i + 1][0]] for i in range(len(gap_ranges)",
"is not None: neighbour_consensus_entry.sequence = (\"-\" * nr_gaps) + neighbour_consensus_entry.sequence # entry should",
"(n_stretch_idx_two if n_stretch_idx_two > -1 else seq_end) ) #if border_aln_length > 0: #",
"count > 1] regions = [] for start in region_starts: regions.append([(start, gaps_for_start[start]), (ends_dict[start],",
"get surrounding sequences seq_start = interval_start - max_seq_length seq_end = interval_end + max_seq_length",
"(seq_end - seq_start) < 1000: #https://github.com/biopython/biopython/pull/782 alignments = pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5, -0.1, #default",
"Can only join alignments from same set of genomes.\") if alignment.genomes[1].file_path != alignment_two.genomes[1].file_path:",
"!= alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) # if not checked yet add it as last lcb",
"= prev_new_entry neighbour_lcb = prev_lcb if neighbour_new_entry.strand == \"+\": append = True else:",
"seq_one entry_two.sequence = seq_two new_lcb = LCB() new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb) return realigned def",
"not go over boundaries of sequences! seq_start = max(seq_start, 0) min_orig_seq_length = min(len(seq_one),",
"if neighbour_new_entry.strand == \"+\": prepend = True else: append = True if neighbour_new_entry",
"not elif len(alignment.lcbs) == 1 and new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) # if not",
"in gaps_for_start.items()] + list(ends_dict.keys()) region_starts = [item for item, count in collections.Counter(location_list).items() if",
"seq_two.find(n_stretch, interval_end, seq_end) seq_end = min(seq_end, (n_stretch_idx_one if n_stretch_idx_one > -1 else seq_end),",
"2, 2: 1} else: genome_nr_dict = {1: 1, 2: 2} for lcb in",
"return separated class Merger: def merge_lcbs(self, alignment, consensus_genome_nr, new_genome_nr, block_length): if len(alignment.genomes) >",
"current interval break if max_length > 0 and max_length < ( seq_end -",
"of block short_border_intervals = [(i[1] - i[0]) <= border_aln_length for i in interval",
"prev_new_entry.sequence[-1] == \"-\") \\ or ( prev_new_entry.strand == \"-\" and prev_new_entry.sequence[0] == \"-\"):",
"appended to previous entry and if that ends with a gap if len(merged_split_lcbs)",
"False append = False use_prev = False use_next = False prev_gap = False",
"two sequences # if border_aln_length is not None align only sequences at block",
"length if i[0] == 0 # start of block or ((i[1] - index_offset)",
"or (next_new_entry.strand == \"-\" and next_new_entry.sequence[-1] == \"-\"): next_gap = True neighbour_new_entry =",
"False to_reverse_complement = False next_new_entry = None prev_new_entry = None # check if",
"index_offset # border_aln_length not set OR small sequence at start or end of",
"hspfrag_idx < (hspfrag_key_num - 1): next_hspfrag = match[hspfrag_keys[hspfrag_idx + 1]] inter_hit_len = next_hspfrag.hit_start",
"neighbour_consensus_entry.sequence += (\"-\" * nr_gaps) elif prepend: neighbour_new_entry.sequence = new_entry.sequence + sequence if",
"nr_gaps = len(new_entry.sequence) # check if can be appended to previous entry and",
"through lcbs, skip one-entry ones for lcb in alignment.get_sorted_lcbs(0): if len(lcb.entries) == 1:",
"_get_realign_regions(self, gaps_for_start, gaps_for_end): ends_dict = {end: start for start, end in gaps_for_end.items()} location_list",
"small (less bp than blocklength) LCBs by splitting, but append/prepend sequence merged_split_lcbs =",
"= Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): realigned.add_genome(genome, nr) # go through lcbs,",
"= self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two new_lcb",
"yes: do not realign n_stretch = 'N' * max_seq_length if not (seq_one[interval_start:interval_end] ==",
"max(seq_start, 0) min_orig_seq_length = min(len(seq_one), len(seq_two)) seq_end = min(seq_end, min_orig_seq_length) # N-stretches in",
"itertools from operator import itemgetter import math from Bio import pairwise2 from seqseqpan.base",
"list(set(range(len(match.hit_range_all))) - set(exclude_keys)) hspfrag_key_num = len(hspfrag_keys) for hspfrag_idx in range(hspfrag_key_num): hspfrag_key = hspfrag_keys[hspfrag_idx]",
"next_new_entry = None prev_new_entry = None # check if new entry is small",
"hspfrag_key = hspfrag_keys[hspfrag_idx] hspfrag = match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) # add sequences between aligned",
"if more than one lcb is unchecked try to merge alignment.lcbs = alignment.get_sorted_lcbs(order)",
"min_orig_seq_length) # N-stretches in sequences # find N-stretch between start and interval and",
"first two_first_one_second = self._get_realign_regions(entry_two.gaps, entry_one.gaps) if len(two_first_one_second) > 0: seq_two, seq_one = self._realign(entry_two.sequence,",
"new_entry.sequence + sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence = (\"-\" * nr_gaps)",
"else: # no alignment, do nothing for current interval break if max_length >",
"alignment.lcbs[lcb].length for pos in range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end else:",
"num_tuple = len(tuple_list) last_ok_end = -1 exclude_idx = [] #overlap_detected = False for",
"merged or could be neither appended nor prepended # add LCBs to alignment",
"# else: do nothing for current interval if (seq_end - seq_start) < 1000:",
"= [] for k, g in itertools.groupby(enumerate(rm_gaps), lambda x: x[0] - x[1]): group",
"processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two # get regions to realign",
"len(alignment.genomes) > 2: print(\"ERROR: I don't want to think about cases with more",
"align only sequences at block border up to given length realign_regions = sorted(realign_regions)",
"than blocklength) LCBs by splitting, but append/prepend sequence merged_split_lcbs = [] for i",
"nr_gaps neighbour_new_entry.end = max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start = min(new_entry.start, neighbour_new_entry.start) if append: neighbour_new_entry.sequence =",
"merge_lcbs(self, alignment, consensus_genome_nr, new_genome_nr, block_length): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() lcbs =",
"genome in alignment.genomes.items(): realigned.add_genome(genome, nr) # go through lcbs, skip one-entry ones for",
"= max( enumerate([interval[0][1] - interval[0][0], interval[1][1] - interval[1][0]]), key=lambda p: p[1]) # get",
"sorted(realign_regions) index_offset = 0 for interval in realign_regions: max_index, max_seq_length = max( enumerate([interval[0][1]",
"in entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1 lcb.entries[:] = entries alignment.lcbs[:]",
"n_stretch): max_seq_length = math.ceil(max_seq_length * 1.5) # get surrounding sequences seq_start = interval_start",
"single_alignment_1, single_alignment_2 def join(self, alignment, alignment_two): if len(alignment.genomes) > 2: print(\"ERROR: I don't",
"# if an entry does not fulfill all conditions stop and do not",
"neighbour_new_entry = prev_new_entry neighbour_lcb = prev_lcb if neighbour_new_entry.strand == \"+\": append = True",
"range(rm_genome + 1, max_genome + 1): alignment.genomes[nr - 1] = alignment.genomes[nr] del alignment.genomes[max_genome]",
"to alignment as it is else: merged_split_lcbs.append(lcb) merged = Alignment(alignment.xmfa_file) for nr, genome",
"are there any entries left in LCB? if len(entries) > 1: # if",
"in alignment_two.genomes.values()] if genome_names_one.sort() != genome_names_two.sort(): print(\"ERROR: Can only join alignments from same",
"1, 2: 2} for lcb in alignment_two.lcbs: for entry in lcb.entries: entry.genome_nr =",
"up to given length realign_regions = sorted(realign_regions) index_offset = 0 for interval in",
"nothing for current interval break if max_length > 0 and max_length < (",
"- 1].entries[entry].end != 1 \\ or (alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb - 1].entries[entry].strand) != strand:",
"entry does not fulfill all conditions stop and do not merge this lcb",
"1 if alignment.lcbs[lcb].get_entry(order) is not None: i = 0 if len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb",
"True else: prepend = True elif use_next: neighbour_new_entry = next_new_entry neighbour_lcb = next_lcb",
"entry_one.sequence, two_first_one_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two new_lcb = LCB()",
"use_prev: neighbour_new_entry = prev_new_entry neighbour_lcb = prev_lcb if neighbour_new_entry.strand == \"+\": append =",
"ConsensusXMFAInputError() realigned = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): realigned.add_genome(genome, nr) # go",
"None: new_alignment.add_lcb(alignment.lcbs[0]) for lcb in range(1, len(alignment.lcbs)): j += 1 if alignment.lcbs[lcb].get_entry(order) is",
"* seq_len) if match.query_end < len(seq_two): seq_len = len(seq_two) - match.query_end seq_one_list.append(\"-\" *",
"seq_two_list.append(str(hspfrag.query.seq)) # add sequences between aligned intervals to sequences if hspfrag_idx < (hspfrag_key_num",
"math.ceil(max_seq_length * 1.5) # get surrounding sequences seq_start = interval_start - max_seq_length seq_end",
"(n_stretch_idx_one if n_stretch_idx_one > -1 else seq_end), (n_stretch_idx_two if n_stretch_idx_two > -1 else",
"is not None: # seq_one equals hit seq_two equals query # only one",
"2: 1} else: genome_nr_dict = {1: 1, 2: 2} for lcb in alignment_two.lcbs:",
"find N-stretch between interval and end and end sub-sequence before nearest stretch n_stretch_idx_one",
"seq_end = min(seq_end, min_orig_seq_length) # N-stretches in sequences # find N-stretch between start",
"set OR small sequence at start or end of block if border_aln_length ==",
"1: single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr == 2: single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb) alignment.lcbs = pairlcbs return",
"is unchecked try to merge alignment.lcbs = alignment.get_sorted_lcbs(order) j = 0 if alignment.lcbs[0].get_entry(order)",
"seq_one, seq_two = self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence =",
"list(map(itemgetter(1), g)) gap_ranges.append((group[0], group[-1])) # tuples with intervals if len(gap_ranges) > 0: if",
"= SequenceEntry(entry.genome_nr, entry.start, entry.end, entry.strand, seq) separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb) return separated class Merger:",
"1} else: genome_nr_dict = {1: 1, 2: 2} for lcb in alignment_two.lcbs: for",
"len(tuple_list) last_ok_end = -1 exclude_idx = [] #overlap_detected = False for idx in",
"rm_genome > -1: for lcb in alignment.lcbs: entries = [entry for entry in",
"== 1: realigned.add_lcb(lcb) else: entry_one = lcb.entries[0] entry_two = lcb.entries[1] # get regions",
"and prev_new_entry.sequence[0] == \"-\"): prev_gap = True # check if can be prepended",
"alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb]) else: break alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)] # continue",
"regions to realign for updated entries with second entry first two_first_one_second = self._get_realign_regions(entry_two.gaps,",
"return alignment class Remover: def remove(self, alignment, rm_genome): if len(alignment.genomes) >= rm_genome >",
"is not None and (next_new_entry.start - new_entry.end) == 1: use_next = True if",
"smaller than last end -> exclude exclude_idx.append(idx) else: last_ok_end = tuple_list[idx][1] # current",
"n_stretch_idx_one = seq_one.find(n_stretch, interval_end, seq_end) n_stretch_idx_two = seq_two.find(n_stretch, interval_end, seq_end) seq_end = min(seq_end,",
"lcb in alignment.lcbs: if len(lcb.entries) == 1: if lcb.entries[0].strand == \"-\": lcb.reverse_complement_entries() if",
"else: for entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1 lcb.entries[:]",
"strand = alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb - 1].entries[0].strand for entry in range(0, len(alignment.lcbs[lcb].entries)): if",
"but append/prepend sequence merged_split_lcbs = [] for i in range(len(lcbs)): lcb = lcbs[i]",
"len(alignment.genomes) > 2: raise ConsensusXMFAInputError() single_alignment_1 = Alignment(alignment.xmfa_file) single_alignment_2 = Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] =",
"= [] for i in range(len(lcbs)): lcb = lcbs[i] new_entry = lcb.get_entry(new_genome_nr) consensus_entry",
"only 'N' - if yes: do not realign n_stretch = 'N' * max_seq_length",
"end in gaps_for_end.items()} location_list = [start for start, end in gaps_for_start.items()] + list(ends_dict.keys())",
"None and new_entry is not None and len(new_entry.sequence) <= block_length: nr_gaps = len(new_entry.sequence)",
"== \"-\" and next_new_entry.sequence[-1] == \"-\"): next_gap = True neighbour_new_entry = None #",
"len(entries) == 1: # if only one entry left replace all gaps in",
"prev_new_entry = None # check if new entry is small and only created",
"of consecutive gap positions for faster join() gap_ranges = [] for k, g",
"per definition of blat match = align_result[0][0] # add starting sequences, in case",
"(not next_gap) and use_prev: neighbour_new_entry = prev_new_entry neighbour_lcb = prev_lcb if neighbour_new_entry.strand ==",
"interval_start) if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) n_stretch_idx =",
"= len(alignment.genomes) for nr in range(rm_genome + 1, max_genome + 1): alignment.genomes[nr -",
"index_offset) == len(seq_one)) # end of block or ((i[1] - index_offset) == len(seq_two))]",
"in entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1 elif len(entries) == 1:",
"0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" * inter_hit_len) inter_query_len = next_hspfrag.query_start - hspfrag.query_end if inter_query_len >",
"new_lcb = LCB() new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb) return realigned def _get_realign_regions(self, gaps_for_start, gaps_for_end): ends_dict",
"or end of block short_border_intervals = [(i[1] - i[0]) <= border_aln_length for i",
"hspfrag = match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) # add sequences between aligned intervals to sequences",
"lcbs[i + 1] next_new_entry = next_lcb.get_entry(new_genome_nr) if next_new_entry is not None and (next_new_entry.start",
"prev_new_entry = prev_lcb.get_entry(new_genome_nr) if prev_new_entry is not None and (new_entry.start - prev_new_entry.end) ==",
"exclude exclude_idx.append(idx) else: last_ok_end = tuple_list[idx][1] # current tuple is ok -> store",
"neighbour_consensus_entry.sequence = (\"-\" * nr_gaps) + neighbour_consensus_entry.sequence # entry should not be merged",
"- if yes: do not realign n_stretch = 'N' * max_seq_length if not",
"neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence += (\"-\" * nr_gaps) elif prepend: neighbour_new_entry.sequence =",
"None class SingletonAligner: def genome_count_split(self, alignment): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() single_alignment_1",
"for current interval if (seq_end - seq_start) < 1000: #https://github.com/biopython/biopython/pull/782 alignments = pairwise2.align.globalxs(seq_one_nogap.upper(),",
"current tuple is ok -> store end return exclude_idx align_result = processor.external_blat(seq_one, seq_two)",
"> 0: max_score = max([x[2] for x in alignments]) alignments = (lambda max_score=max_score:",
"\"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) # add last sequence parts if hit",
"remaining entries rm_gaps = set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k])) for k in entries[0].gaps])) for entry",
"of genomes in XMFA)\") def merge(self, alignment): for lcb in alignment.lcbs: lcb.entries =",
"== 0 # start of block or ((i[1] - index_offset) == len(seq_one)) #",
"end -> exclude exclude_idx.append(idx) else: last_ok_end = tuple_list[idx][1] # current tuple is ok",
"neighbour_new_entry.end) neighbour_new_entry.start = min(new_entry.start, neighbour_new_entry.start) if append: neighbour_new_entry.sequence = sequence + new_entry.sequence if",
"= True neighbour_new_entry = None # if both, choose the one with gap",
"or seq_two[interval_start:interval_end] == n_stretch): max_seq_length = math.ceil(max_seq_length * 1.5) # get surrounding sequences",
"== max_length])() aln_seq_one = alignments[0][0] aln_seq_two = alignments[0][1] else: # no alignment, do",
"of genomes.\") if alignment.genomes[1].file_path != alignment_two.genomes[1].file_path: genome_nr_dict = {1: 2, 2: 1} else:",
"> -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) n_stretch_idx = seq_two.rfind(n_stretch, seq_start, interval_start)",
"seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) # add sequences between aligned intervals to sequences if hspfrag_idx <",
"= new_entry.sequence + sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence = (\"-\" *",
"max_seq_length if not (seq_one[interval_start:interval_end] == n_stretch or seq_two[interval_start:interval_end] == n_stretch): max_seq_length = math.ceil(max_seq_length",
"if len(lcbs) > (i+1): next_lcb = lcbs[i + 1] next_new_entry = next_lcb.get_entry(new_genome_nr) if",
"of block interval_start = interval[max_index][0] - index_offset interval_end = interval[max_index][1] - index_offset #",
"{1: 2, 2: 1} else: genome_nr_dict = {1: 1, 2: 2} for lcb",
"= self._get_realign_regions(entry_one.gaps, entry_two.gaps) if len(one_first_two_second) > 0: seq_one, seq_two = self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second,",
"- 1].entries[entry].strand) != strand: # if an entry does not fulfill all conditions",
"= (lambda max_score=max_score: [item for item in alignments if item[2] == max_score])() max_length",
"idx in range(num_tuple): if tuple_list[idx][0] < last_ok_end: #current start smaller than last end",
"- i[0]) <= border_aln_length for i in interval # check border length if",
"( seq_end - seq_start ): # only use new alignment if better than",
"alignment.get_sorted_lcbs(new_genome_nr) # do not create small (less bp than blocklength) LCBs by splitting,",
"print(aln_seq_one) # print(aln_seq_two) seq_one = aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two = aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset +=",
"# print(aln_seq_two) seq_one = aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two = aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset += ((seq_end",
"else seq_end), (n_stretch_idx_two if n_stretch_idx_two > -1 else seq_end) ) #if border_aln_length >",
"= processor.external_blat(seq_one, seq_two) if align_result is not None: # seq_one equals hit seq_two",
"None # if both, choose the one with gap at start or end",
"> 2: raise ConsensusXMFAInputError() single_alignment_1 = Alignment(alignment.xmfa_file) single_alignment_2 = Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] = alignment.genomes[1]",
"splitting, but append/prepend sequence merged_split_lcbs = [] for i in range(len(lcbs)): lcb =",
"if append or prepend: if to_reverse_complement: new_entry.reverse_complement() sequence = neighbour_new_entry.sequence neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr)",
"k in entry.gaps])) rm_gaps = sorted(list(rm_gaps)) # make intervals of consecutive gap positions",
"1: realigned.add_lcb(lcb) else: entry_one = lcb.entries[0] entry_two = lcb.entries[1] # get regions to",
"add last sequence parts if hit or query do not include sequence ends",
"= [start for start, end in gaps_for_start.items()] + list(ends_dict.keys()) region_starts = [item for",
"item in alignments if item[4] == max_length])() aln_seq_one = alignments[0][0] aln_seq_two = alignments[0][1]",
"end if (not next_gap) and use_prev: neighbour_new_entry = prev_new_entry neighbour_lcb = prev_lcb if",
"= [] if match.hit_start > 0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" * match.hit_start) if match.query_start >",
"in XMFA)\") def merge(self, alignment): for lcb in alignment.lcbs: lcb.entries = sorted(lcb.entries, key=lambda",
"last sequence parts if hit or query do not include sequence ends if",
"seq_start ): # only use new alignment if better than old one #if",
"# if border_aln_length is not None align only sequences at block border up",
"separated class Merger: def merge_lcbs(self, alignment, consensus_genome_nr, new_genome_nr, block_length): if len(alignment.genomes) > 2:",
"gaps_for_start.items()] + list(ends_dict.keys()) region_starts = [item for item, count in collections.Counter(location_list).items() if count",
"use_prev = True if (prev_new_entry.strand == \"+\" and prev_new_entry.sequence[-1] == \"-\") \\ or",
"aln_seq_two = alignments[0][1] else: # no alignment, do nothing for current interval break",
"= 0 if len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb - 1].entries): strand = alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb",
"from operator import itemgetter import math from Bio import pairwise2 from seqseqpan.base import",
"1].entries[entry].end != 1 \\ or (alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb - 1].entries[entry].strand) != strand: #",
"!= genome_names_two.sort(): print(\"ERROR: Can only join alignments from same set of genomes.\") if",
"gap_ranges = [] for k, g in itertools.groupby(enumerate(rm_gaps), lambda x: x[0] - x[1]):",
"boundaries of sequences! seq_start = max(seq_start, 0) min_orig_seq_length = min(len(seq_one), len(seq_two)) seq_end =",
"lcb.entries[0].genome_nr == 2: single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb) alignment.lcbs = pairlcbs return alignment, single_alignment_1, single_alignment_2",
"if lcb.length <= length: for entry in lcb.entries: seq = entry.sequence.replace(\"-\", \"\") new_entry",
"len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb - 1].entries): strand = alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb - 1].entries[0].strand for",
"genome (consensus is None) if consensus_entry is None and new_entry is not None",
"in case query or hit do not start at \"0\" seq_one_list = []",
"def _realign(self, seq_one, seq_two, realign_regions, processor, border_aln_length): # if border_aln_length is not None",
"\"\") seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\", \"\") if not (seq_one_nogap == '' or seq_two_nogap ==",
"if (next_new_entry.strand == \"+\" and next_new_entry.sequence[0] == \"-\")\\ or (next_new_entry.strand == \"-\" and",
"if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() realigned = Alignment(alignment.xmfa_file) for nr, genome in",
"length): separated = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): separated.add_genome(genome, nr) for lcb",
"lcb in alignment.lcbs: if lcb.length <= length: for entry in lcb.entries: seq =",
"small sequence at start or end of block if border_aln_length == 0 or",
"* max_seq_length if not (seq_one[interval_start:interval_end] == n_stretch or seq_two[interval_start:interval_end] == n_stretch): max_seq_length =",
"inter_hit_len) inter_query_len = next_hspfrag.query_start - hspfrag.query_end if inter_query_len > 0: seq_one_list.append(\"-\" * inter_query_len)",
"0 if len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb - 1].entries): strand = alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb -",
"Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): separated.add_genome(genome, nr) for lcb in alignment.lcbs: if",
"if len(merged_split_lcbs) > 0: prev_lcb = merged_split_lcbs[-1] prev_new_entry = prev_lcb.get_entry(new_genome_nr) if prev_new_entry is",
"if len(one_first_two_second) > 0: seq_one, seq_two = self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second, processor, border_aln_length) entry_one.sequence",
"if both, choose the one with gap at start or end if (not",
"be appended to previous entry and if that ends with a gap if",
"alignment class Remover: def remove(self, alignment, rm_genome): if len(alignment.genomes) >= rm_genome > -1:",
"if max_length > 0 and max_length < ( seq_end - seq_start ): #",
"genome_count_split(self, alignment): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() single_alignment_1 = Alignment(alignment.xmfa_file) single_alignment_2 =",
"for entry in entries: entry.sequence = ''.join( [entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i + 1][0]] for",
"> rm_genome: entry.genome_nr -= 1 lcb.entries[:] = entries alignment.lcbs[:] = [lcb for lcb",
"SequenceEntry(entry.genome_nr, entry.start, entry.end, entry.strand, seq) separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb) return separated class Merger: def",
"elif len(alignment.lcbs) == 1 and new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) # if not checked",
"seq_one.find(n_stretch, interval_end, seq_end) n_stretch_idx_two = seq_two.find(n_stretch, interval_end, seq_end) seq_end = min(seq_end, (n_stretch_idx_one if",
"= lcb.get_entry(new_genome_nr) consensus_entry = lcb.get_entry(consensus_genome_nr) prepend = False append = False use_prev =",
"small and only created by splitting or aligning of new genome (consensus is",
"= set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k])) for k in entries[0].gaps])) for entry in entries[1:]: rm_gaps",
"new_entry.strand != neighbour_new_entry.strand: to_reverse_complement = True if append or prepend: if to_reverse_complement: new_entry.reverse_complement()",
"len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb - 1].entries[entry].genome_nr \\ or alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb -",
"# check if can be prepended to next entry and if that starts",
"two_first_one_second = self._get_realign_regions(entry_two.gaps, entry_one.gaps) if len(two_first_one_second) > 0: seq_two, seq_one = self._realign(entry_two.sequence, entry_one.sequence,",
"and next_new_entry.sequence[-1] == \"-\"): next_gap = True neighbour_new_entry = None # if both,",
"yet add it as last lcb and finish break else: break return new_alignment",
"next_lcb if neighbour_new_entry.strand == \"+\": prepend = True else: append = True if",
"\\ or alignment.lcbs[lcb].entries[entry].start - alignment.lcbs[lcb - 1].entries[entry].end != 1 \\ or (alignment.lcbs[lcb].entries[entry].strand ==",
"or hit do not start at \"0\" seq_one_list = [] seq_two_list = []",
"lcbs[i] new_entry = lcb.get_entry(new_genome_nr) consensus_entry = lcb.get_entry(consensus_genome_nr) prepend = False append = False",
"old one #if border_aln_length > 0: # print(aln_seq_one) # print(aln_seq_two) seq_one = aln_seq_one.join([seq_one[:seq_start],",
"!= 1 \\ or (alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb - 1].entries[entry].strand) != strand: # if",
"0: seq_one_list.append(\"-\" * inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one = match.aln[0] if seq_rec_one.id == \"seq1\":",
"next_lcb.get_entry(new_genome_nr) if next_new_entry is not None and (next_new_entry.start - new_entry.end) == 1: use_next",
"[(i[1] - i[0]) <= border_aln_length for i in interval # check border length",
"\"+\": append = True else: prepend = True elif use_next: neighbour_new_entry = next_new_entry",
"seq_rec_one.id == \"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) # add last sequence parts",
"is None and new_entry is not None and len(new_entry.sequence) <= block_length: nr_gaps =",
"seq_one = self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two",
"all conditions stop and do not merge this lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break else: i",
"* seq_len) seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else: return None, None class SingletonAligner: def",
"align_result is not None: # seq_one equals hit seq_two equals query # only",
"ones for lcb in alignment.get_sorted_lcbs(0): if len(lcb.entries) == 1: realigned.add_lcb(lcb) else: entry_one =",
"sorted(lcb.entries, key=lambda entry: entry.genome_nr) new_alignment = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): new_alignment.add_genome(genome,",
"blocklength) LCBs by splitting, but append/prepend sequence merged_split_lcbs = [] for i in",
"seq_two_nogap, processor) if aln_seq_one is not None: max_length = len(aln_seq_one) else: # no",
"sequence parts if hit or query do not include sequence ends if match.hit_end",
"= entries alignment.lcbs[:] = [lcb for lcb in alignment.lcbs if len(lcb.entries) > 0]",
"prepend: if to_reverse_complement: new_entry.reverse_complement() sequence = neighbour_new_entry.sequence neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length += nr_gaps",
"= interval[max_index][0] - index_offset interval_end = interval[max_index][1] - index_offset # border_aln_length not set",
"for start in region_starts: regions.append([(start, gaps_for_start[start]), (ends_dict[start], start)]) return regions def _realign(self, seq_one,",
"border_aln_length is not None align only sequences at block border up to given",
"seq_two # get regions to realign for updated entries with second entry first",
"merge this lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break else: i += 1 if i == len(alignment.lcbs[lcb].entries):",
"item, count in collections.Counter(location_list).items() if count > 1] regions = [] for start",
"in realign_regions: max_index, max_seq_length = max( enumerate([interval[0][1] - interval[0][0], interval[1][1] - interval[1][0]]), key=lambda",
"return alignment else: raise ParameterError(\"remove_genome\", rm_genome, \"between 0 and \" + str(len(alignment.genomes)) +",
"1000: #https://github.com/biopython/biopython/pull/782 alignments = pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5, -0.1, #default one_alignment_only=True) if len(alignments) >",
"1].entries[0].strand for entry in range(0, len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb - 1].entries[entry].genome_nr \\",
"seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" * inter_hit_len) inter_query_len = next_hspfrag.query_start - hspfrag.query_end if inter_query_len > 0:",
"seq_two, seq_one = self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence =",
"start at \"0\" seq_one_list = [] seq_two_list = [] if match.hit_start > 0:",
"= len(seq_two) - match.query_end seq_one_list.append(\"-\" * seq_len) seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else: return",
"2: raise ConsensusXMFAInputError() lcbs = alignment.get_sorted_lcbs(new_genome_nr) # do not create small (less bp",
"one #if border_aln_length > 0: # print(aln_seq_one) # print(aln_seq_two) seq_one = aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]])",
"\"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else: return None, None class SingletonAligner: def genome_count_split(self, alignment): if len(alignment.genomes)",
"''.join( [entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i + 1][0]] for i in range(len(gap_ranges) - 1)]) if",
"match.query_end < len(seq_two): seq_len = len(seq_two) - match.query_end seq_one_list.append(\"-\" * seq_len) seq_two_list.append(seq_two[match.query_end:]) return",
"if (prev_new_entry.strand == \"+\" and prev_new_entry.sequence[-1] == \"-\") \\ or ( prev_new_entry.strand ==",
"\" + str(len(alignment.genomes)) + \" (number of genomes in XMFA)\") def merge(self, alignment):",
"range(num_tuple): if tuple_list[idx][0] < last_ok_end: #current start smaller than last end -> exclude",
"= {end: start for start, end in gaps_for_end.items()} location_list = [start for start,",
"* n_stretch_length n_stretch_idx = seq_one.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start =",
"align only sequences at block border up to given length def realign(self, alignment,",
"that ends with a gap if len(merged_split_lcbs) > 0: prev_lcb = merged_split_lcbs[-1] prev_new_entry",
"len(alignment.lcbs) > 1: # if more than one lcb is unchecked try to",
"= next_hspfrag.query_start - hspfrag.query_end if inter_query_len > 0: seq_one_list.append(\"-\" * inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else:",
"entry in entries: entry.sequence = ''.join( [entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i + 1][0]] for i",
"entry_one.gaps) if len(two_first_one_second) > 0: seq_two, seq_one = self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second, processor, border_aln_length)",
"prev_new_entry.end) == 1: use_prev = True if (prev_new_entry.strand == \"+\" and prev_new_entry.sequence[-1] ==",
"hit has highest score per definition of blat match = align_result[0][0] # add",
"alignment): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() single_alignment_1 = Alignment(alignment.xmfa_file) single_alignment_2 = Alignment(alignment.xmfa_file)",
"match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) # add sequences between aligned intervals to sequences if hspfrag_idx",
"new_alignment = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): new_alignment.add_genome(genome, nr) for order in",
"rm_genome: entry.genome_nr -= 1 elif len(entries) == 1: # if only one entry",
"alignment.lcbs: if len(lcb.entries) == 1: if lcb.entries[0].strand == \"-\": lcb.reverse_complement_entries() if lcb.entries[0].genome_nr ==",
"equals query # only one query and first hit has highest score per",
"an entry does not fulfill all conditions stop and do not merge this",
"only sequences at block border up to given length def realign(self, alignment, processor,",
"> (i+1): next_lcb = lcbs[i + 1] next_new_entry = next_lcb.get_entry(new_genome_nr) if next_new_entry is",
"entries left in LCB? if len(entries) > 1: # if more than one",
"ParameterError(\"remove_genome\", rm_genome, \"between 0 and \" + str(len(alignment.genomes)) + \" (number of genomes",
"entry.genome_nr > rm_genome: entry.genome_nr -= 1 elif len(entries) == 1: # if only",
"(next_new_entry.strand == \"-\" and next_new_entry.sequence[-1] == \"-\"): next_gap = True neighbour_new_entry = None",
"to realign one_first_two_second = self._get_realign_regions(entry_one.gaps, entry_two.gaps) if len(one_first_two_second) > 0: seq_one, seq_two =",
"alignment.genomes.items(): separated.add_genome(genome, nr) for lcb in alignment.lcbs: if lcb.length <= length: for entry",
"max( enumerate([interval[0][1] - interval[0][0], interval[1][1] - interval[1][0]]), key=lambda p: p[1]) # get length",
"prev_new_entry.strand == \"-\" and prev_new_entry.sequence[0] == \"-\"): prev_gap = True # check if",
"n_stretch_length)) n_stretch_idx = seq_two.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start = max(seq_start,",
"# go through lcbs, skip one-entry ones for lcb in alignment.get_sorted_lcbs(0): if len(lcb.entries)",
"+ 1, max_genome + 1): alignment.genomes[nr - 1] = alignment.genomes[nr] del alignment.genomes[max_genome] return",
"\"-\"): next_gap = True neighbour_new_entry = None # if both, choose the one",
"interval break if max_length > 0 and max_length < ( seq_end - seq_start",
"to_reverse_complement: new_entry.reverse_complement() sequence = neighbour_new_entry.sequence neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length += nr_gaps neighbour_new_entry.end =",
"for item, count in collections.Counter(location_list).items() if count > 1] regions = [] for",
"alignment): for lcb in alignment.lcbs: lcb.entries = sorted(lcb.entries, key=lambda entry: entry.genome_nr) new_alignment =",
"prev_gap = False next_gap = False to_reverse_complement = False next_new_entry = None prev_new_entry",
"-1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) n_stretch_idx = seq_two.rfind(n_stretch, seq_start, interval_start) if",
"range(len(lcbs)): lcb = lcbs[i] new_entry = lcb.get_entry(new_genome_nr) consensus_entry = lcb.get_entry(consensus_genome_nr) prepend = False",
"seq_end) seq_end = min(seq_end, (n_stretch_idx_one if n_stretch_idx_one > -1 else seq_end), (n_stretch_idx_two if",
"- hspfrag.query_end if inter_query_len > 0: seq_one_list.append(\"-\" * inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one =",
"alignments = pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5, -0.1, #default one_alignment_only=True) if len(alignments) > 0: max_score",
"Separator: def separate_lcbs(self, alignment, length): separated = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items():",
"regions = [] for start in region_starts: regions.append([(start, gaps_for_start[start]), (ends_dict[start], start)]) return regions",
"intervals to sequences if hspfrag_idx < (hspfrag_key_num - 1): next_hspfrag = match[hspfrag_keys[hspfrag_idx +",
"start)]) return regions def _realign(self, seq_one, seq_two, realign_regions, processor, border_aln_length): # if border_aln_length",
"block short_border_intervals = [(i[1] - i[0]) <= border_aln_length for i in interval #",
"= seq_one entry_two.sequence = seq_two # get regions to realign for updated entries",
"if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) # find N-stretch",
"set( itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for k in entry.gaps])) rm_gaps = sorted(list(rm_gaps)) # make intervals",
"not start at \"0\" seq_one_list = [] seq_two_list = [] if match.hit_start >",
"entries = [entry for entry in lcb.entries if entry.genome_nr != rm_genome] # did",
"and only created by splitting or aligning of new genome (consensus is None)",
"len(seq_two))] # end of block interval_start = interval[max_index][0] - index_offset interval_end = interval[max_index][1]",
"alignment else: raise ParameterError(\"remove_genome\", rm_genome, \"between 0 and \" + str(len(alignment.genomes)) + \"",
"= alignment.genomes[1] single_alignment_2.genomes[2] = alignment.genomes[2] pairlcbs = [] for lcb in alignment.lcbs: if",
"include sequence ends if match.hit_end < len(seq_one): seq_len = len(seq_one) - match.hit_end seq_one_list.append(seq_one[match.hit_end:])",
"seq_two.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length))",
"= (\"-\" * nr_gaps) + neighbour_consensus_entry.sequence # entry should not be merged or",
"{end: start for start, end in gaps_for_end.items()} location_list = [start for start, end",
"if len(entries) > 1: # if more than one entry left search for",
"Bio import pairwise2 from seqseqpan.base import * class Separator: def separate_lcbs(self, alignment, length):",
"2: raise ConsensusXMFAInputError() single_alignment_1 = Alignment(alignment.xmfa_file) single_alignment_2 = Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] = alignment.genomes[1] single_alignment_2.genomes[2]",
"set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k])) for k in entries[0].gaps])) for entry in entries[1:]: rm_gaps &=",
"in sequences # find N-stretch between start and interval and start sub-sequence after",
"= LCB() new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb) return realigned def _get_realign_regions(self, gaps_for_start, gaps_for_end): ends_dict =",
"1.5) # get surrounding sequences seq_start = interval_start - max_seq_length seq_end = interval_end",
"= genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return alignment class Remover: def remove(self, alignment, rm_genome): if len(alignment.genomes)",
"min(new_entry.start, neighbour_new_entry.start) if append: neighbour_new_entry.sequence = sequence + new_entry.sequence if neighbour_consensus_entry is not",
"else: merged_split_lcbs.append(lcb) merged = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): merged.add_genome(genome, nr) for",
"[item for item in alignments if item[4] == max_length])() aln_seq_one = alignments[0][0] aln_seq_two",
"ok -> store end return exclude_idx align_result = processor.external_blat(seq_one, seq_two) if align_result is",
"entry.start, entry.end, entry.strand, seq) separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb) return separated class Merger: def merge_lcbs(self,",
"neighbour_new_entry = None # if both, choose the one with gap at start",
"to sequences if hspfrag_idx < (hspfrag_key_num - 1): next_hspfrag = match[hspfrag_keys[hspfrag_idx + 1]]",
"entry_one = lcb.entries[0] entry_two = lcb.entries[1] # get regions to realign one_first_two_second =",
"block_length: nr_gaps = len(new_entry.sequence) # check if can be appended to previous entry",
"hspfrag_idx in range(hspfrag_key_num): hspfrag_key = hspfrag_keys[hspfrag_idx] hspfrag = match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) # add",
"(hspfrag_key_num - 1): next_hspfrag = match[hspfrag_keys[hspfrag_idx + 1]] inter_hit_len = next_hspfrag.hit_start - hspfrag.hit_end",
"entry_two.gaps) if len(one_first_two_second) > 0: seq_one, seq_two = self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second, processor, border_aln_length)",
"length realign_regions = sorted(realign_regions) index_offset = 0 for interval in realign_regions: max_index, max_seq_length",
"\"-\": lcb.reverse_complement_entries() if lcb.entries[0].genome_nr == 1: single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr == 2: single_alignment_2.add_lcb(lcb) else:",
"else: separated.add_lcb(lcb) return separated class Merger: def merge_lcbs(self, alignment, consensus_genome_nr, new_genome_nr, block_length): if",
"None and (next_new_entry.start - new_entry.end) == 1: use_next = True if (next_new_entry.strand ==",
"skip one-entry ones for lcb in alignment.get_sorted_lcbs(0): if len(lcb.entries) == 1: realigned.add_lcb(lcb) else:",
"[] for lcb in alignment.lcbs: if len(lcb.entries) == 1: if lcb.entries[0].strand == \"-\":",
"seq_two) if align_result is not None: # seq_one equals hit seq_two equals query",
"for lcb in alignment.get_sorted_lcbs(0): if len(lcb.entries) == 1: realigned.add_lcb(lcb) else: entry_one = lcb.entries[0]",
"seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) # add last sequence parts if hit or query do not",
"# do not go over boundaries of sequences! seq_start = max(seq_start, 0) min_orig_seq_length",
"alignment.genomes.items(): realigned.add_genome(genome, nr) # go through lcbs, skip one-entry ones for lcb in",
"realign for updated entries with second entry first two_first_one_second = self._get_realign_regions(entry_two.gaps, entry_one.gaps) if",
"print(seq_two[seq_start:seq_end]) seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\", \"\") if not (seq_one_nogap ==",
"max_length) return seq_one, seq_two def _external_blat(self, seq_one, seq_two, processor): def _check_tuple_overlap(tuple_list): num_tuple =",
"== \"-\": lcb.reverse_complement_entries() if lcb.entries[0].genome_nr == 1: single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr == 2: single_alignment_2.add_lcb(lcb)",
"of genome to remove? if len(entries) < len(lcb.entries): # are there any entries",
"= self._get_realign_regions(entry_two.gaps, entry_one.gaps) if len(two_first_one_second) > 0: seq_two, seq_one = self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second,",
"- 1): next_hspfrag = match[hspfrag_keys[hspfrag_idx + 1]] inter_hit_len = next_hspfrag.hit_start - hspfrag.hit_end if",
"# tuples with intervals if len(gap_ranges) > 0: if gap_ranges[0][0] != 0: gap_ranges",
"in gaps_for_end.items()} location_list = [start for start, end in gaps_for_start.items()] + list(ends_dict.keys()) region_starts",
"do external blat alignment aln_seq_one, aln_seq_two = self._external_blat(seq_one_nogap, seq_two_nogap, processor) if aln_seq_one is",
"( prev_new_entry.strand == \"-\" and prev_new_entry.sequence[0] == \"-\"): prev_gap = True # check",
"entry left replace all gaps in sequence entries[0].sequence = entries[0].sequence.replace(\"-\", \"\") if entries[0].genome_nr",
"not (seq_one_nogap == '' or seq_two_nogap == ''): # else: do nothing for",
"positions for faster join() gap_ranges = [] for k, g in itertools.groupby(enumerate(rm_gaps), lambda",
"not None: neighbour_consensus_entry.sequence = (\"-\" * nr_gaps) + neighbour_consensus_entry.sequence # entry should not",
"end of block or ((i[1] - index_offset) == len(seq_two))] # end of block",
"at start or end of block if border_aln_length == 0 or any(short_border_intervals): #",
"left replace all gaps in sequence entries[0].sequence = entries[0].sequence.replace(\"-\", \"\") if entries[0].genome_nr >",
"x[1]): group = list(map(itemgetter(1), g)) gap_ranges.append((group[0], group[-1])) # tuples with intervals if len(gap_ranges)",
"lcb in range(1, len(alignment.lcbs)): j += 1 if alignment.lcbs[lcb].get_entry(order) is not None: i",
"else: break alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)] # continue with unchecked lcbs # if only",
"if all entries have an unequal strand reverse complement this lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length",
"!= rm_genome] # did LCB include entry of genome to remove? if len(entries)",
"entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1 elif len(entries) ==",
"new entry is small and only created by splitting or aligning of new",
"aligning of new genome (consensus is None) if consensus_entry is None and new_entry",
"len(seq_two)) seq_end = min(seq_end, min_orig_seq_length) # N-stretches in sequences # find N-stretch between",
"not None: i = 0 if len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb - 1].entries): strand =",
"if len(two_first_one_second) > 0: seq_two, seq_one = self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second, processor, border_aln_length) entry_one.sequence",
"if genome_names_one.sort() != genome_names_two.sort(): print(\"ERROR: Can only join alignments from same set of",
"check whether it is already checked or not elif len(alignment.lcbs) == 1 and",
"'N' * n_stretch_length n_stretch_idx = seq_one.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start",
"checked or not elif len(alignment.lcbs) == 1 and new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) #",
"does not fulfill all conditions stop and do not merge this lcb new_alignment.add_lcb(alignment.lcbs[lcb])",
"max_length])() aln_seq_one = alignments[0][0] aln_seq_two = alignments[0][1] else: # no alignment, do nothing",
"# add starting sequences, in case query or hit do not start at",
"interval[max_index][0] - index_offset interval_end = interval[max_index][1] - index_offset # border_aln_length not set OR",
"of blat match = align_result[0][0] # add starting sequences, in case query or",
"min(seq_end, (n_stretch_idx_one if n_stretch_idx_one > -1 else seq_end), (n_stretch_idx_two if n_stretch_idx_two > -1",
"alignment, do nothing for current interval break if max_length > 0 and max_length",
"entry.gaps[k])) for k in entry.gaps])) rm_gaps = sorted(list(rm_gaps)) # make intervals of consecutive",
"neighbour_lcb.length += nr_gaps neighbour_new_entry.end = max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start = min(new_entry.start, neighbour_new_entry.start) if append:",
"hspfrag.query_end if inter_query_len > 0: seq_one_list.append(\"-\" * inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one = match.aln[0]",
"if i == len(alignment.lcbs[lcb].entries): if not strand: # if all entries have an",
"# if all entries have an unequal strand reverse complement this lcb alignment.lcbs[lcb].reverse_complement_entries()",
"#current start smaller than last end -> exclude exclude_idx.append(idx) else: last_ok_end = tuple_list[idx][1]",
"for entry in range(0, len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb - 1].entries[entry].genome_nr \\ or",
"= False next_new_entry = None prev_new_entry = None # check if new entry",
"seq_two_list.append(\"-\" * match.hit_start) if match.query_start > 0: seq_one_list.append(\"-\" * match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented:",
"sorted(list(rm_gaps)) # make intervals of consecutive gap positions for faster join() gap_ranges =",
"return seq_one, seq_two def _external_blat(self, seq_one, seq_two, processor): def _check_tuple_overlap(tuple_list): num_tuple = len(tuple_list)",
"for nr, genome in alignment.genomes.items(): new_alignment.add_genome(genome, nr) for order in alignment.genomes: if len(alignment.lcbs)",
"match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" * seq_len) if match.query_end < len(seq_two): seq_len = len(seq_two) -",
"+= alignment.lcbs[lcb].length for pos in range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end",
"if gap_ranges[0][0] != 0: gap_ranges = [(-1, -1)] + gap_ranges if gap_ranges[-1] !=",
"twice if gaps present) else: for entry in entries: if entry.genome_nr > rm_genome:",
"= True if neighbour_new_entry is not None: if new_entry.strand != neighbour_new_entry.strand: to_reverse_complement =",
"already checked or not elif len(alignment.lcbs) == 1 and new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0])",
"if len(alignment.genomes) >= rm_genome > -1: for lcb in alignment.lcbs: entries = [entry",
"rare cases fragments are overlapping! exclude_keys = _check_tuple_overlap(match.hit_range_all) exclude_keys = exclude_keys + _check_tuple_overlap(match.query_range_all)",
"pairlcbs.append(lcb) alignment.lcbs = pairlcbs return alignment, single_alignment_1, single_alignment_2 def join(self, alignment, alignment_two): if",
"start, end in gaps_for_end.items()} location_list = [start for start, end in gaps_for_start.items()] +",
"alignments[0][1] else: # no alignment, do nothing for current interval break else: #",
"2} for lcb in alignment_two.lcbs: for entry in lcb.entries: entry.genome_nr = genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb)",
"x in alignments]) alignments = (lambda max_length=max_length: [item for item in alignments if",
"for pos in range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb])",
"block or ((i[1] - index_offset) == len(seq_one)) # end of block or ((i[1]",
"strand: # if all entries have an unequal strand reverse complement this lcb",
"genomes in XMFA)\") def merge(self, alignment): for lcb in alignment.lcbs: lcb.entries = sorted(lcb.entries,",
"== alignment.lcbs[lcb - 1].entries[entry].strand) != strand: # if an entry does not fulfill",
"realign(self, alignment, processor, border_aln_length=0): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() realigned = Alignment(alignment.xmfa_file)",
"print(\"ERROR: Can only join alignments from same set of genomes.\") if alignment.genomes[1].file_path !=",
"in really rare cases fragments are overlapping! exclude_keys = _check_tuple_overlap(match.hit_range_all) exclude_keys = exclude_keys",
"match.hit_start) if match.query_start > 0: seq_one_list.append(\"-\" * match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented: # in",
"alignment.lcbs[:] = [lcb for lcb in alignment.lcbs if len(lcb.entries) > 0] max_genome =",
"max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start = min(new_entry.start, neighbour_new_entry.start) if append: neighbour_new_entry.sequence = sequence + new_entry.sequence",
"pos in range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb]) else:",
"= [] #overlap_detected = False for idx in range(num_tuple): if tuple_list[idx][0] < last_ok_end:",
"nr (avoid looping through entries twice if gaps present) else: for entry in",
"alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length for pos in range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end",
"query do not include sequence ends if match.hit_end < len(seq_one): seq_len = len(seq_one)",
"elif lcb.entries[0].genome_nr == 2: single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb) alignment.lcbs = pairlcbs return alignment, single_alignment_1,",
"None and len(new_entry.sequence) <= block_length: nr_gaps = len(new_entry.sequence) # check if can be",
"k, g in itertools.groupby(enumerate(rm_gaps), lambda x: x[0] - x[1]): group = list(map(itemgetter(1), g))",
"= alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb]) else: break alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)] # continue with unchecked",
"match.query_start > 0: seq_one_list.append(\"-\" * match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented: # in really rare",
"in alignment.genomes.items(): merged.add_genome(genome, nr) for lcb in merged_split_lcbs: merged.add_lcb(lcb) return merged class Realigner:",
"== 0 or any(short_border_intervals): # check if interval only 'N' - if yes:",
"entries[0].gaps])) for entry in entries[1:]: rm_gaps &= set( itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for k in",
"for genome in alignment.genomes.values()] genome_names_two = [genome.file_path for genome in alignment_two.genomes.values()] if genome_names_one.sort()",
"len(aln_seq_one) else: # no alignment, do nothing for current interval break if max_length",
"= [(-1, -1)] + gap_ranges if gap_ranges[-1] != lcb.length: gap_ranges = gap_ranges +",
"LCB? if len(entries) > 1: # if more than one entry left search",
"# end of block interval_start = interval[max_index][0] - index_offset interval_end = interval[max_index][1] -",
"\\ or (alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb - 1].entries[entry].strand) != strand: # if an entry",
"= hspfrag_keys[hspfrag_idx] hspfrag = match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) # add sequences between aligned intervals",
"+ list(ends_dict.keys()) region_starts = [item for item, count in collections.Counter(location_list).items() if count >",
"in alignments if item[2] == max_score])() max_length = min([x[4] for x in alignments])",
"seq_one, seq_two, processor): def _check_tuple_overlap(tuple_list): num_tuple = len(tuple_list) last_ok_end = -1 exclude_idx =",
"* nr_gaps) + neighbour_consensus_entry.sequence # entry should not be merged or could be",
"lcb.get_entry(new_genome_nr) consensus_entry = lcb.get_entry(consensus_genome_nr) prepend = False append = False use_prev = False",
"seq_end = interval_end + max_seq_length # do not go over boundaries of sequences!",
"= 0 for interval in realign_regions: max_index, max_seq_length = max( enumerate([interval[0][1] - interval[0][0],",
"# if not checked yet add it as last lcb and finish break",
"interval if (seq_end - seq_start) < 1000: #https://github.com/biopython/biopython/pull/782 alignments = pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5,",
"sequences between aligned intervals to sequences if hspfrag_idx < (hspfrag_key_num - 1): next_hspfrag",
"j += 1 if alignment.lcbs[lcb].get_entry(order) is not None: i = 0 if len(alignment.lcbs[lcb].entries)",
"[start for start, end in gaps_for_start.items()] + list(ends_dict.keys()) region_starts = [item for item,",
"= 10 n_stretch = 'N' * n_stretch_length n_stretch_idx = seq_one.rfind(n_stretch, seq_start, interval_start) if",
"- seq_start) < 1000: #https://github.com/biopython/biopython/pull/782 alignments = pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5, -0.1, #default one_alignment_only=True)",
"(prev_new_entry.strand == \"+\" and prev_new_entry.sequence[-1] == \"-\") \\ or ( prev_new_entry.strand == \"-\"",
"+ 1][0]] for i in range(len(gap_ranges) - 1)]) if entry.genome_nr > rm_genome: entry.genome_nr",
"class Merger: def merge_lcbs(self, alignment, consensus_genome_nr, new_genome_nr, block_length): if len(alignment.genomes) > 2: raise",
"rm_genome] # did LCB include entry of genome to remove? if len(entries) <",
"if item[2] == max_score])() max_length = min([x[4] for x in alignments]) alignments =",
"lcb.length)] for entry in entries: entry.sequence = ''.join( [entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i + 1][0]]",
"(i+1): next_lcb = lcbs[i + 1] next_new_entry = next_lcb.get_entry(new_genome_nr) if next_new_entry is not",
"= [genome.file_path for genome in alignment.genomes.values()] genome_names_two = [genome.file_path for genome in alignment_two.genomes.values()]",
"only one query and first hit has highest score per definition of blat",
"with a gap if len(merged_split_lcbs) > 0: prev_lcb = merged_split_lcbs[-1] prev_new_entry = prev_lcb.get_entry(new_genome_nr)",
"= min(new_entry.start, neighbour_new_entry.start) if append: neighbour_new_entry.sequence = sequence + new_entry.sequence if neighbour_consensus_entry is",
"= False prev_gap = False next_gap = False to_reverse_complement = False next_new_entry =",
"match.aln[0] if seq_rec_one.id == \"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) # add last",
"if only one entry left replace all gaps in sequence entries[0].sequence = entries[0].sequence.replace(\"-\",",
"collections.Counter(location_list).items() if count > 1] regions = [] for start in region_starts: regions.append([(start,",
"and end and end sub-sequence before nearest stretch n_stretch_idx_one = seq_one.find(n_stretch, interval_end, seq_end)",
"min_orig_seq_length = min(len(seq_one), len(seq_two)) seq_end = min(seq_end, min_orig_seq_length) # N-stretches in sequences #",
"> 0: prev_lcb = merged_split_lcbs[-1] prev_new_entry = prev_lcb.get_entry(new_genome_nr) if prev_new_entry is not None",
"[item for item in alignments if item[2] == max_score])() max_length = min([x[4] for",
"not None and (next_new_entry.start - new_entry.end) == 1: use_next = True if (next_new_entry.strand",
"seq_start, interval_start) if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) #",
"# get regions to realign for updated entries with second entry first two_first_one_second",
"> 0: seq_one, seq_two = self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second, processor, border_aln_length) entry_one.sequence = seq_one",
"any entries left in LCB? if len(entries) > 1: # if more than",
"= True elif use_next: neighbour_new_entry = next_new_entry neighbour_lcb = next_lcb if neighbour_new_entry.strand ==",
"= next_lcb.get_entry(new_genome_nr) if next_new_entry is not None and (next_new_entry.start - new_entry.end) == 1:",
"max_score])() max_length = min([x[4] for x in alignments]) alignments = (lambda max_length=max_length: [item",
"than old one #if border_aln_length > 0: # print(aln_seq_one) # print(aln_seq_two) seq_one =",
"last_ok_end = -1 exclude_idx = [] #overlap_detected = False for idx in range(num_tuple):",
"looping through entries twice if gaps present) else: for entry in entries: if",
"for lcb in merged_split_lcbs: merged.add_lcb(lcb) return merged class Realigner: # local realignment around",
"# if more than one entry left search for gaps that are present",
"entry.sequence.replace(\"-\", \"\") new_entry = SequenceEntry(entry.genome_nr, entry.start, entry.end, entry.strand, seq) separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb) return",
"import pairwise2 from seqseqpan.base import * class Separator: def separate_lcbs(self, alignment, length): separated",
"aln_seq_one is not None: max_length = len(aln_seq_one) else: # no alignment, do nothing",
"nr, genome in alignment.genomes.items(): new_alignment.add_genome(genome, nr) for order in alignment.genomes: if len(alignment.lcbs) >",
"= (lambda max_length=max_length: [item for item in alignments if item[4] == max_length])() aln_seq_one",
"for nr, genome in alignment.genomes.items(): realigned.add_genome(genome, nr) # go through lcbs, skip one-entry",
"= math.ceil(max_seq_length * 1.5) # get surrounding sequences seq_start = interval_start - max_seq_length",
"second entry first two_first_one_second = self._get_realign_regions(entry_two.gaps, entry_one.gaps) if len(two_first_one_second) > 0: seq_two, seq_one",
"1][0]] for i in range(len(gap_ranges) - 1)]) if entry.genome_nr > rm_genome: entry.genome_nr -=",
"raise ConsensusXMFAInputError() realigned = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): realigned.add_genome(genome, nr) #",
"both, choose the one with gap at start or end if (not next_gap)",
"+= nr_gaps neighbour_new_entry.end = max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start = min(new_entry.start, neighbour_new_entry.start) if append: neighbour_new_entry.sequence",
"1: use_prev = True if (prev_new_entry.strand == \"+\" and prev_new_entry.sequence[-1] == \"-\") \\",
"is not None: if new_entry.strand != neighbour_new_entry.strand: to_reverse_complement = True if append or",
"prepend = True elif use_next: neighbour_new_entry = next_new_entry neighbour_lcb = next_lcb if neighbour_new_entry.strand",
"False for idx in range(num_tuple): if tuple_list[idx][0] < last_ok_end: #current start smaller than",
"stop and do not merge this lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break else: i += 1",
"sequences at block border up to given length realign_regions = sorted(realign_regions) index_offset =",
"index_offset interval_end = interval[max_index][1] - index_offset # border_aln_length not set OR small sequence",
"don't want to think about cases with more than 2 genomes now.\") genome_names_one",
"merged_split_lcbs[-1] prev_new_entry = prev_lcb.get_entry(new_genome_nr) if prev_new_entry is not None and (new_entry.start - prev_new_entry.end)",
"= lcb.entries[1] # get regions to realign one_first_two_second = self._get_realign_regions(entry_one.gaps, entry_two.gaps) if len(one_first_two_second)",
"realign_regions = sorted(realign_regions) index_offset = 0 for interval in realign_regions: max_index, max_seq_length =",
"if i[0] == 0 # start of block or ((i[1] - index_offset) ==",
"_external_blat(self, seq_one, seq_two, processor): def _check_tuple_overlap(tuple_list): num_tuple = len(tuple_list) last_ok_end = -1 exclude_idx",
"at start or end of block short_border_intervals = [(i[1] - i[0]) <= border_aln_length",
"# no alignment, do nothing for current interval break if max_length > 0",
"lcb.entries[1] # get regions to realign one_first_two_second = self._get_realign_regions(entry_one.gaps, entry_two.gaps) if len(one_first_two_second) >",
"for current interval break else: # do external blat alignment aln_seq_one, aln_seq_two =",
"this lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length for pos in range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence +=",
"if item[4] == max_length])() aln_seq_one = alignments[0][0] aln_seq_two = alignments[0][1] else: # no",
"2: raise ConsensusXMFAInputError() realigned = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): realigned.add_genome(genome, nr)",
"next entry and if that starts with a gap if len(lcbs) > (i+1):",
"exclude_keys = exclude_keys + _check_tuple_overlap(match.query_range_all) hspfrag_keys = list(set(range(len(match.hit_range_all))) - set(exclude_keys)) hspfrag_key_num = len(hspfrag_keys)",
"lcb = lcbs[i] new_entry = lcb.get_entry(new_genome_nr) consensus_entry = lcb.get_entry(consensus_genome_nr) prepend = False append",
"gaps_for_end.items()} location_list = [start for start, end in gaps_for_start.items()] + list(ends_dict.keys()) region_starts =",
"realign_regions: max_index, max_seq_length = max( enumerate([interval[0][1] - interval[0][0], interval[1][1] - interval[1][0]]), key=lambda p:",
"given length realign_regions = sorted(realign_regions) index_offset = 0 for interval in realign_regions: max_index,",
"or ((i[1] - index_offset) == len(seq_one)) # end of block or ((i[1] -",
"join alignments from same set of genomes.\") if alignment.genomes[1].file_path != alignment_two.genomes[1].file_path: genome_nr_dict =",
"max_score = max([x[2] for x in alignments]) alignments = (lambda max_score=max_score: [item for",
"set(exclude_keys)) hspfrag_key_num = len(hspfrag_keys) for hspfrag_idx in range(hspfrag_key_num): hspfrag_key = hspfrag_keys[hspfrag_idx] hspfrag =",
"Alignment(alignment.xmfa_file) single_alignment_1.genomes[1] = alignment.genomes[1] single_alignment_2.genomes[2] = alignment.genomes[2] pairlcbs = [] for lcb in",
"> 0] max_genome = len(alignment.genomes) for nr in range(rm_genome + 1, max_genome +",
"1): next_hspfrag = match[hspfrag_keys[hspfrag_idx + 1]] inter_hit_len = next_hspfrag.hit_start - hspfrag.hit_end if inter_hit_len",
"is not None: new_alignment.add_lcb(alignment.lcbs[0]) for lcb in range(1, len(alignment.lcbs)): j += 1 if",
"gap if len(lcbs) > (i+1): next_lcb = lcbs[i + 1] next_new_entry = next_lcb.get_entry(new_genome_nr)",
"break alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)] # continue with unchecked lcbs # if only one",
"alignments = (lambda max_score=max_score: [item for item in alignments if item[2] == max_score])()",
"alignment.genomes[1] single_alignment_2.genomes[2] = alignment.genomes[2] pairlcbs = [] for lcb in alignment.lcbs: if len(lcb.entries)",
"alignment, processor, border_aln_length=0): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() realigned = Alignment(alignment.xmfa_file) for",
"seq_two_nogap == ''): # else: do nothing for current interval if (seq_end -",
"and prev_new_entry.sequence[-1] == \"-\") \\ or ( prev_new_entry.strand == \"-\" and prev_new_entry.sequence[0] ==",
"end of block interval_start = interval[max_index][0] - index_offset interval_end = interval[max_index][1] - index_offset",
"remove(self, alignment, rm_genome): if len(alignment.genomes) >= rm_genome > -1: for lcb in alignment.lcbs:",
"block border up to given length realign_regions = sorted(realign_regions) index_offset = 0 for",
"entries have an unequal strand reverse complement this lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length",
"between aligned intervals to sequences if hspfrag_idx < (hspfrag_key_num - 1): next_hspfrag =",
"= 'N' * n_stretch_length n_stretch_idx = seq_one.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1:",
"-0.5, -0.1, #default one_alignment_only=True) if len(alignments) > 0: max_score = max([x[2] for x",
"False use_next = False prev_gap = False next_gap = False to_reverse_complement = False",
"(next_new_entry.start - new_entry.end) == 1: use_next = True if (next_new_entry.strand == \"+\" and",
"* match.hit_start) if match.query_start > 0: seq_one_list.append(\"-\" * match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented: #",
"are overlapping! exclude_keys = _check_tuple_overlap(match.hit_range_all) exclude_keys = exclude_keys + _check_tuple_overlap(match.query_range_all) hspfrag_keys = list(set(range(len(match.hit_range_all)))",
"!= neighbour_new_entry.strand: to_reverse_complement = True if append or prepend: if to_reverse_complement: new_entry.reverse_complement() sequence",
"= False next_gap = False to_reverse_complement = False next_new_entry = None prev_new_entry =",
"= len(new_entry.sequence) # check if can be appended to previous entry and if",
"of block or ((i[1] - index_offset) == len(seq_two))] # end of block interval_start",
"genome_names_two = [genome.file_path for genome in alignment_two.genomes.values()] if genome_names_one.sort() != genome_names_two.sort(): print(\"ERROR: Can",
"start of block or ((i[1] - index_offset) == len(seq_one)) # end of block",
"self._get_realign_regions(entry_one.gaps, entry_two.gaps) if len(one_first_two_second) > 0: seq_one, seq_two = self._realign(entry_one.sequence, entry_two.sequence, one_first_two_second, processor,",
"with intervals if len(gap_ranges) > 0: if gap_ranges[0][0] != 0: gap_ranges = [(-1,",
"len(alignment.lcbs[lcb - 1].entries): strand = alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb - 1].entries[0].strand for entry in",
"in entries[0].gaps])) for entry in entries[1:]: rm_gaps &= set( itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for k",
"and new_entry is not None and len(new_entry.sequence) <= block_length: nr_gaps = len(new_entry.sequence) #",
"sequences # if border_aln_length is not None align only sequences at block border",
"end of block if border_aln_length == 0 or any(short_border_intervals): # check if interval",
"in alignment.genomes: if len(alignment.lcbs) > 1: # if more than one lcb is",
"prev_new_entry is not None and (new_entry.start - prev_new_entry.end) == 1: use_prev = True",
"entry_one.sequence = seq_one entry_two.sequence = seq_two new_lcb = LCB() new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb) return",
"> 0: if gap_ranges[0][0] != 0: gap_ranges = [(-1, -1)] + gap_ranges if",
"== '' or seq_two_nogap == ''): # else: do nothing for current interval",
"to given length def realign(self, alignment, processor, border_aln_length=0): if len(alignment.genomes) > 2: raise",
"- 1)]) if entry.genome_nr > rm_genome: entry.genome_nr -= 1 # if no gaps",
"interval and end and end sub-sequence before nearest stretch n_stretch_idx_one = seq_one.find(n_stretch, interval_end,",
"new_entry = lcb.get_entry(new_genome_nr) consensus_entry = lcb.get_entry(consensus_genome_nr) prepend = False append = False use_prev",
"else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) # add last sequence parts if hit or query do",
"#default one_alignment_only=True) if len(alignments) > 0: max_score = max([x[2] for x in alignments])",
"lcb.entries[0] entry_two = lcb.entries[1] # get regions to realign one_first_two_second = self._get_realign_regions(entry_one.gaps, entry_two.gaps)",
"can be prepended to next entry and if that starts with a gap",
"= True else: prepend = True elif use_next: neighbour_new_entry = next_new_entry neighbour_lcb =",
"* match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented: # in really rare cases fragments are overlapping!",
"= prev_lcb.get_entry(new_genome_nr) if prev_new_entry is not None and (new_entry.start - prev_new_entry.end) == 1:",
"for entry in lcb.entries if entry.genome_nr != rm_genome] # did LCB include entry",
"for x in alignments]) alignments = (lambda max_score=max_score: [item for item in alignments",
"in range(num_tuple): if tuple_list[idx][0] < last_ok_end: #current start smaller than last end ->",
"= 0 if alignment.lcbs[0].get_entry(order) is not None: new_alignment.add_lcb(alignment.lcbs[0]) for lcb in range(1, len(alignment.lcbs)):",
"> 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" * inter_hit_len) inter_query_len = next_hspfrag.query_start - hspfrag.query_end if inter_query_len",
"= min(len(seq_one), len(seq_two)) seq_end = min(seq_end, min_orig_seq_length) # N-stretches in sequences # find",
"check if new entry is small and only created by splitting or aligning",
"[] #overlap_detected = False for idx in range(num_tuple): if tuple_list[idx][0] < last_ok_end: #current",
"-1 else seq_end), (n_stretch_idx_two if n_stretch_idx_two > -1 else seq_end) ) #if border_aln_length",
"not None: new_alignment.add_lcb(alignment.lcbs[0]) for lcb in range(1, len(alignment.lcbs)): j += 1 if alignment.lcbs[lcb].get_entry(order)",
"Remover: def remove(self, alignment, rm_genome): if len(alignment.genomes) >= rm_genome > -1: for lcb",
"None: # seq_one equals hit seq_two equals query # only one query and",
"alignment, alignment_two): if len(alignment.genomes) > 2: print(\"ERROR: I don't want to think about",
"genome_names_one = [genome.file_path for genome in alignment.genomes.values()] genome_names_two = [genome.file_path for genome in",
"genome in alignment.genomes.items(): merged.add_genome(genome, nr) for lcb in merged_split_lcbs: merged.add_lcb(lcb) return merged class",
"key=lambda p: p[1]) # get length of gaps at start or end of",
"tuples with intervals if len(gap_ranges) > 0: if gap_ranges[0][0] != 0: gap_ranges =",
"alignment, rm_genome): if len(alignment.genomes) >= rm_genome > -1: for lcb in alignment.lcbs: entries",
"separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb) return separated class Merger: def merge_lcbs(self, alignment, consensus_genome_nr, new_genome_nr, block_length):",
"''): # else: do nothing for current interval if (seq_end - seq_start) <",
"intervals if len(gap_ranges) > 0: if gap_ranges[0][0] != 0: gap_ranges = [(-1, -1)]",
"pairwise2 from seqseqpan.base import * class Separator: def separate_lcbs(self, alignment, length): separated =",
"= False to_reverse_complement = False next_new_entry = None prev_new_entry = None # check",
"entry.genome_nr -= 1 # if no gaps found only reduce genome nr (avoid",
"= seq_one.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx +",
"over boundaries of sequences! seq_start = max(seq_start, 0) min_orig_seq_length = min(len(seq_one), len(seq_two)) seq_end",
"two_first_one_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two new_lcb = LCB() new_lcb.add_entries([entry_one,",
"should not be merged or could be neither appended nor prepended # add",
"not strand: # if all entries have an unequal strand reverse complement this",
"only reduce genome nr (avoid looping through entries twice if gaps present) else:",
"< len(lcb.entries): # are there any entries left in LCB? if len(entries) >",
"prepend = False append = False use_prev = False use_next = False prev_gap",
"no alignment, do nothing for current interval break else: # do external blat",
"in alignment.genomes.items(): new_alignment.add_genome(genome, nr) for order in alignment.genomes: if len(alignment.lcbs) > 1: #",
"= merged_split_lcbs[-1] prev_new_entry = prev_lcb.get_entry(new_genome_nr) if prev_new_entry is not None and (new_entry.start -",
"interval_end, seq_end) n_stretch_idx_two = seq_two.find(n_stretch, interval_end, seq_end) seq_end = min(seq_end, (n_stretch_idx_one if n_stretch_idx_one",
"new_alignment.add_genome(genome, nr) for order in alignment.genomes: if len(alignment.lcbs) > 1: # if more",
"interval # check border length if i[0] == 0 # start of block",
"through entries twice if gaps present) else: for entry in entries: if entry.genome_nr",
"at block border up to given length def realign(self, alignment, processor, border_aln_length=0): if",
"in LCB? if len(entries) > 1: # if more than one entry left",
"# if only one lcb left check whether it is already checked or",
"entry in entries[1:]: rm_gaps &= set( itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for k in entry.gaps])) rm_gaps",
"aln_seq_one = alignments[0][0] aln_seq_two = alignments[0][1] else: # no alignment, do nothing for",
"go through lcbs, skip one-entry ones for lcb in alignment.get_sorted_lcbs(0): if len(lcb.entries) ==",
"n_stretch_idx = seq_two.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx",
"one_first_two_second, processor, border_aln_length) entry_one.sequence = seq_one entry_two.sequence = seq_two # get regions to",
"for order in alignment.genomes: if len(alignment.lcbs) > 1: # if more than one",
"# end of block or ((i[1] - index_offset) == len(seq_two))] # end of",
"genome_nr_dict = {1: 2, 2: 1} else: genome_nr_dict = {1: 1, 2: 2}",
"seq_two_list = [] if match.hit_start > 0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" * match.hit_start) if match.query_start",
"are present in all remaining entries rm_gaps = set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k])) for k",
"-= 1 else: for entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr -=",
"around overlapping or consecutive gaps in two sequences # if border_aln_length is not",
"border_aln_length > 0: # print(aln_seq_one) # print(aln_seq_two) seq_one = aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two =",
"lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break else: i += 1 if i == len(alignment.lcbs[lcb].entries): if not",
"nr) # go through lcbs, skip one-entry ones for lcb in alignment.get_sorted_lcbs(0): if",
"rm_genome): if len(alignment.genomes) >= rm_genome > -1: for lcb in alignment.lcbs: entries =",
"= [(i[1] - i[0]) <= border_aln_length for i in interval # check border",
"region_starts: regions.append([(start, gaps_for_start[start]), (ends_dict[start], start)]) return regions def _realign(self, seq_one, seq_two, realign_regions, processor,",
"< ( seq_end - seq_start ): # only use new alignment if better",
"length of gaps at start or end of block short_border_intervals = [(i[1] -",
"check if can be appended to previous entry and if that ends with",
"hspfrag.hit_end if inter_hit_len > 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\" * inter_hit_len) inter_query_len = next_hspfrag.query_start -",
"for lcb in alignment.lcbs: entries = [entry for entry in lcb.entries if entry.genome_nr",
"neighbour_new_entry.sequence = sequence + new_entry.sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence += (\"-\"",
"genome in alignment_two.genomes.values()] if genome_names_one.sort() != genome_names_two.sort(): print(\"ERROR: Can only join alignments from",
"if entry.genome_nr > rm_genome: entry.genome_nr -= 1 lcb.entries[:] = entries alignment.lcbs[:] = [lcb",
"in interval # check border length if i[0] == 0 # start of",
"entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1 lcb.entries[:] = entries",
"= neighbour_new_entry.sequence neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length += nr_gaps neighbour_new_entry.end = max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start",
"= False for idx in range(num_tuple): if tuple_list[idx][0] < last_ok_end: #current start smaller",
"-= 1 elif len(entries) == 1: # if only one entry left replace",
"seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) # find N-stretch between interval and end",
"did LCB include entry of genome to remove? if len(entries) < len(lcb.entries): #",
"not merge this lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break else: i += 1 if i ==",
"new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length for pos in range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end =",
"import * class Separator: def separate_lcbs(self, alignment, length): separated = Alignment(alignment.xmfa_file) for nr,",
"g)) gap_ranges.append((group[0], group[-1])) # tuples with intervals if len(gap_ranges) > 0: if gap_ranges[0][0]",
"sequence = neighbour_new_entry.sequence neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length += nr_gaps neighbour_new_entry.end = max(new_entry.end, neighbour_new_entry.end)",
"lcbs # if only one lcb left check whether it is already checked",
"not create small (less bp than blocklength) LCBs by splitting, but append/prepend sequence",
"between interval and end and end sub-sequence before nearest stretch n_stretch_idx_one = seq_one.find(n_stretch,",
"- 1].entries): strand = alignment.lcbs[lcb].entries[0].strand == alignment.lcbs[lcb - 1].entries[0].strand for entry in range(0,",
"if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() lcbs = alignment.get_sorted_lcbs(new_genome_nr) # do not create",
"# start of block or ((i[1] - index_offset) == len(seq_one)) # end of",
"found only reduce genome nr (avoid looping through entries twice if gaps present)",
"j = 0 if alignment.lcbs[0].get_entry(order) is not None: new_alignment.add_lcb(alignment.lcbs[0]) for lcb in range(1,",
"entry in range(0, len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb - 1].entries[entry].genome_nr \\ or alignment.lcbs[lcb].entries[entry].start",
"alignments = (lambda max_length=max_length: [item for item in alignments if item[4] == max_length])()",
"== \"-\"): prev_gap = True # check if can be prepended to next",
"if alignment.lcbs[lcb].get_entry(order) is not None: i = 0 if len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb -",
"entry.sequence = ''.join( [entry.sequence[(gap_ranges[i][1] + 1):gap_ranges[i + 1][0]] for i in range(len(gap_ranges) -",
"and end sub-sequence before nearest stretch n_stretch_idx_one = seq_one.find(n_stretch, interval_end, seq_end) n_stretch_idx_two =",
"genome in alignment.genomes.values()] genome_names_two = [genome.file_path for genome in alignment_two.genomes.values()] if genome_names_one.sort() !=",
"seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) n_stretch_idx = seq_two.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx",
"len(alignment.lcbs[lcb].entries): if not strand: # if all entries have an unequal strand reverse",
"entry of genome to remove? if len(entries) < len(lcb.entries): # are there any",
"alignment, consensus_genome_nr, new_genome_nr, block_length): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() lcbs = alignment.get_sorted_lcbs(new_genome_nr)",
"reverse complement this lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length for pos in range(0, len(new_alignment.lcbs[-1].entries)):",
"if len(entries) < len(lcb.entries): # are there any entries left in LCB? if",
"+ 1]] inter_hit_len = next_hspfrag.hit_start - hspfrag.hit_end if inter_hit_len > 0: seq_one_list.append(seq_one[hspfrag.hit_end:next_hspfrag.hit_start]) seq_two_list.append(\"-\"",
"fulfill all conditions stop and do not merge this lcb new_alignment.add_lcb(alignment.lcbs[lcb]) break else:",
"realigned.add_genome(genome, nr) # go through lcbs, skip one-entry ones for lcb in alignment.get_sorted_lcbs(0):",
"interval[1][1] - interval[1][0]]), key=lambda p: p[1]) # get length of gaps at start",
"n_stretch = 'N' * max_seq_length if not (seq_one[interval_start:interval_end] == n_stretch or seq_two[interval_start:interval_end] ==",
"pairwise2.align.globalxs(seq_one_nogap.upper(), seq_two_nogap.upper(), -0.5, -0.1, #default one_alignment_only=True) if len(alignments) > 0: max_score = max([x[2]",
"else: seq_rec_one = match.aln[0] if seq_rec_one.id == \"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq))",
"for nr in range(rm_genome + 1, max_genome + 1): alignment.genomes[nr - 1] =",
"len(gap_ranges) > 0: if gap_ranges[0][0] != 0: gap_ranges = [(-1, -1)] + gap_ranges",
"return realigned def _get_realign_regions(self, gaps_for_start, gaps_for_end): ends_dict = {end: start for start, end",
"seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" * seq_len) if match.query_end < len(seq_two): seq_len = len(seq_two) - match.query_end",
"in range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb]) else: break",
"# if no gaps found only reduce genome nr (avoid looping through entries",
"== 1 and new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) # if not checked yet add",
"(\"-\" * nr_gaps) elif prepend: neighbour_new_entry.sequence = new_entry.sequence + sequence if neighbour_consensus_entry is",
"- 1].entries[0].strand for entry in range(0, len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb - 1].entries[entry].genome_nr",
"if hit or query do not include sequence ends if match.hit_end < len(seq_one):",
"raise ParameterError(\"remove_genome\", rm_genome, \"between 0 and \" + str(len(alignment.genomes)) + \" (number of",
"if new entry is small and only created by splitting or aligning of",
"cases fragments are overlapping! exclude_keys = _check_tuple_overlap(match.hit_range_all) exclude_keys = exclude_keys + _check_tuple_overlap(match.query_range_all) hspfrag_keys",
"-1 else seq_end) ) #if border_aln_length > 0: # print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end]) seq_one_nogap",
"- index_offset) == len(seq_two))] # end of block interval_start = interval[max_index][0] - index_offset",
"len(alignment.lcbs) == 1 and new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) # if not checked yet",
"seq_two new_lcb = LCB() new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb) return realigned def _get_realign_regions(self, gaps_for_start, gaps_for_end):",
"= alignments[0][1] else: # no alignment, do nothing for current interval break else:",
"None and (new_entry.start - prev_new_entry.end) == 1: use_prev = True if (prev_new_entry.strand ==",
"self._external_blat(seq_one_nogap, seq_two_nogap, processor) if aln_seq_one is not None: max_length = len(aln_seq_one) else: #",
"None: max_length = len(aln_seq_one) else: # no alignment, do nothing for current interval",
"single_alignment_2.genomes[2] = alignment.genomes[2] pairlcbs = [] for lcb in alignment.lcbs: if len(lcb.entries) ==",
"return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else: return None, None class SingletonAligner: def genome_count_split(self, alignment): if",
"True elif use_next: neighbour_new_entry = next_new_entry neighbour_lcb = next_lcb if neighbour_new_entry.strand == \"+\":",
"align_result[0][0] # add starting sequences, in case query or hit do not start",
"alignment.lcbs[lcb - 1].entries[entry].end != 1 \\ or (alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb - 1].entries[entry].strand) !=",
"with unchecked lcbs # if only one lcb left check whether it is",
"entry_two]) realigned.add_lcb(new_lcb) return realigned def _get_realign_regions(self, gaps_for_start, gaps_for_end): ends_dict = {end: start for",
"= seq_two new_lcb = LCB() new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb) return realigned def _get_realign_regions(self, gaps_for_start,",
"interval[max_index][1] - index_offset # border_aln_length not set OR small sequence at start or",
"in range(0, len(alignment.lcbs[lcb].entries)): if alignment.lcbs[lcb].entries[entry].genome_nr != alignment.lcbs[lcb - 1].entries[entry].genome_nr \\ or alignment.lcbs[lcb].entries[entry].start -",
"> -1 else seq_end) ) #if border_aln_length > 0: # print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end])",
"try to merge alignment.lcbs = alignment.get_sorted_lcbs(order) j = 0 if alignment.lcbs[0].get_entry(order) is not",
"alignment, single_alignment_1, single_alignment_2 def join(self, alignment, alignment_two): if len(alignment.genomes) > 2: print(\"ERROR: I",
"starts with a gap if len(lcbs) > (i+1): next_lcb = lcbs[i + 1]",
"= match[hspfrag_keys[hspfrag_idx + 1]] inter_hit_len = next_hspfrag.hit_start - hspfrag.hit_end if inter_hit_len > 0:",
"query and first hit has highest score per definition of blat match =",
"in all remaining entries rm_gaps = set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k])) for k in entries[0].gaps]))",
"realignment around overlapping or consecutive gaps in two sequences # if border_aln_length is",
"sequence + new_entry.sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence += (\"-\" * nr_gaps)",
"gap_ranges if gap_ranges[-1] != lcb.length: gap_ranges = gap_ranges + [(lcb.length, lcb.length)] for entry",
"2: 2} for lcb in alignment_two.lcbs: for entry in lcb.entries: entry.genome_nr = genome_nr_dict[entry.genome_nr]",
"if match.query_start > 0: seq_one_list.append(\"-\" * match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented: # in really",
"max_seq_length # do not go over boundaries of sequences! seq_start = max(seq_start, 0)",
"# print(aln_seq_one) # print(aln_seq_two) seq_one = aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two = aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset",
"-1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) # find N-stretch between interval and",
"== \"+\" and prev_new_entry.sequence[-1] == \"-\") \\ or ( prev_new_entry.strand == \"-\" and",
"interval in realign_regions: max_index, max_seq_length = max( enumerate([interval[0][1] - interval[0][0], interval[1][1] - interval[1][0]]),",
"- max_length) return seq_one, seq_two def _external_blat(self, seq_one, seq_two, processor): def _check_tuple_overlap(tuple_list): num_tuple",
"at start or end if (not next_gap) and use_prev: neighbour_new_entry = prev_new_entry neighbour_lcb",
"alignment, do nothing for current interval break else: # do external blat alignment",
"equals hit seq_two equals query # only one query and first hit has",
"p: p[1]) # get length of gaps at start or end of block",
"lcb.entries: seq = entry.sequence.replace(\"-\", \"\") new_entry = SequenceEntry(entry.genome_nr, entry.start, entry.end, entry.strand, seq) separated.add_lcb_entries(new_entry)",
"max(seq_start, (n_stretch_idx + n_stretch_length)) n_stretch_idx = seq_two.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1:",
"rm_gaps = set(itertools.chain.from_iterable( [list(range(k, entries[0].gaps[k])) for k in entries[0].gaps])) for entry in entries[1:]:",
"len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence += alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb]) else: break alignment.lcbs[:] =",
"N-stretch between interval and end and end sub-sequence before nearest stretch n_stretch_idx_one =",
"or ((i[1] - index_offset) == len(seq_two))] # end of block interval_start = interval[max_index][0]",
"interval[1][0]]), key=lambda p: p[1]) # get length of gaps at start or end",
"\"\") new_entry = SequenceEntry(entry.genome_nr, entry.start, entry.end, entry.strand, seq) separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb) return separated",
"new_entry.reverse_complement() sequence = neighbour_new_entry.sequence neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length += nr_gaps neighbour_new_entry.end = max(new_entry.end,",
"gaps in two sequences # if border_aln_length is not None align only sequences",
"or seq_two_nogap == ''): # else: do nothing for current interval if (seq_end",
"elif prepend: neighbour_new_entry.sequence = new_entry.sequence + sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence",
"neither appended nor prepended # add LCBs to alignment as it is else:",
"seq_one_list.append(\"-\" * match.query_start) seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented: # in really rare cases fragments are",
"processor): def _check_tuple_overlap(tuple_list): num_tuple = len(tuple_list) last_ok_end = -1 exclude_idx = [] #overlap_detected",
"for lcb in range(1, len(alignment.lcbs)): j += 1 if alignment.lcbs[lcb].get_entry(order) is not None:",
"gap_ranges = [(-1, -1)] + gap_ranges if gap_ranges[-1] != lcb.length: gap_ranges = gap_ranges",
"bp than blocklength) LCBs by splitting, but append/prepend sequence merged_split_lcbs = [] for",
"alignment.get_sorted_lcbs(order) j = 0 if alignment.lcbs[0].get_entry(order) is not None: new_alignment.add_lcb(alignment.lcbs[0]) for lcb in",
"realigned def _get_realign_regions(self, gaps_for_start, gaps_for_end): ends_dict = {end: start for start, end in",
"> 2: raise ConsensusXMFAInputError() lcbs = alignment.get_sorted_lcbs(new_genome_nr) # do not create small (less",
"inter_query_len = next_hspfrag.query_start - hspfrag.query_end if inter_query_len > 0: seq_one_list.append(\"-\" * inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start])",
"\"+\": prepend = True else: append = True if neighbour_new_entry is not None:",
"seq_start = interval_start - max_seq_length seq_end = interval_end + max_seq_length # do not",
"if entries[0].genome_nr > rm_genome: entries[0].genome_nr -= 1 else: for entry in entries: if",
"sequence if neighbour_consensus_entry is not None: neighbour_consensus_entry.sequence = (\"-\" * nr_gaps) + neighbour_consensus_entry.sequence",
"= True # check if can be prepended to next entry and if",
"+ gap_ranges if gap_ranges[-1] != lcb.length: gap_ranges = gap_ranges + [(lcb.length, lcb.length)] for",
"+ n_stretch_length)) # find N-stretch between interval and end and end sub-sequence before",
"i[0] == 0 # start of block or ((i[1] - index_offset) == len(seq_one))",
"-0.1, #default one_alignment_only=True) if len(alignments) > 0: max_score = max([x[2] for x in",
"# do external blat alignment aln_seq_one, aln_seq_two = self._external_blat(seq_one_nogap, seq_two_nogap, processor) if aln_seq_one",
"- set(exclude_keys)) hspfrag_key_num = len(hspfrag_keys) for hspfrag_idx in range(hspfrag_key_num): hspfrag_key = hspfrag_keys[hspfrag_idx] hspfrag",
"do not create small (less bp than blocklength) LCBs by splitting, but append/prepend",
"and max_length < ( seq_end - seq_start ): # only use new alignment",
"start and interval and start sub-sequence after nearest stretch n_stretch_length = 10 n_stretch",
"(alignment.lcbs[lcb].entries[entry].strand == alignment.lcbs[lcb - 1].entries[entry].strand) != strand: # if an entry does not",
"= max(seq_start, 0) min_orig_seq_length = min(len(seq_one), len(seq_two)) seq_end = min(seq_end, min_orig_seq_length) # N-stretches",
"if len(gap_ranges) > 0: if gap_ranges[0][0] != 0: gap_ranges = [(-1, -1)] +",
"next_hspfrag.query_start - hspfrag.query_end if inter_query_len > 0: seq_one_list.append(\"-\" * inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one",
"present) else: for entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1",
"1 # if no gaps found only reduce genome nr (avoid looping through",
"start in region_starts: regions.append([(start, gaps_for_start[start]), (ends_dict[start], start)]) return regions def _realign(self, seq_one, seq_two,",
"[genome.file_path for genome in alignment_two.genomes.values()] if genome_names_one.sort() != genome_names_two.sort(): print(\"ERROR: Can only join",
"hit or query do not include sequence ends if match.hit_end < len(seq_one): seq_len",
"entry in lcb.entries if entry.genome_nr != rm_genome] # did LCB include entry of",
"alignment.genomes[nr - 1] = alignment.genomes[nr] del alignment.genomes[max_genome] return alignment else: raise ParameterError(\"remove_genome\", rm_genome,",
"check if interval only 'N' - if yes: do not realign n_stretch =",
"starting sequences, in case query or hit do not start at \"0\" seq_one_list",
"be prepended to next entry and if that starts with a gap if",
"1: use_next = True if (next_new_entry.strand == \"+\" and next_new_entry.sequence[0] == \"-\")\\ or",
"def genome_count_split(self, alignment): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() single_alignment_1 = Alignment(alignment.xmfa_file) single_alignment_2",
"neighbour_new_entry.strand == \"+\": prepend = True else: append = True if neighbour_new_entry is",
"max_length=max_length: [item for item in alignments if item[4] == max_length])() aln_seq_one = alignments[0][0]",
"#if border_aln_length > 0: # print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end]) seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap",
"gaps_for_start[start]), (ends_dict[start], start)]) return regions def _realign(self, seq_one, seq_two, realign_regions, processor, border_aln_length): #",
"else: for entry in entries: if entry.genome_nr > rm_genome: entry.genome_nr -= 1 elif",
"= alignment.get_sorted_lcbs(order) j = 0 if alignment.lcbs[0].get_entry(order) is not None: new_alignment.add_lcb(alignment.lcbs[0]) for lcb",
"lcb.entries if entry.genome_nr != rm_genome] # did LCB include entry of genome to",
"if count > 1] regions = [] for start in region_starts: regions.append([(start, gaps_for_start[start]),",
"consecutive gap positions for faster join() gap_ranges = [] for k, g in",
"append = False use_prev = False use_next = False prev_gap = False next_gap",
"LCBs by splitting, but append/prepend sequence merged_split_lcbs = [] for i in range(len(lcbs)):",
"nr) for lcb in merged_split_lcbs: merged.add_lcb(lcb) return merged class Realigner: # local realignment",
"): # only use new alignment if better than old one #if border_aln_length",
"start sub-sequence after nearest stretch n_stretch_length = 10 n_stretch = 'N' * n_stretch_length",
"1] next_new_entry = next_lcb.get_entry(new_genome_nr) if next_new_entry is not None and (next_new_entry.start - new_entry.end)",
"in alignment.lcbs: if len(lcb.entries) == 1: if lcb.entries[0].strand == \"-\": lcb.reverse_complement_entries() if lcb.entries[0].genome_nr",
"inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one = match.aln[0] if seq_rec_one.id == \"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else:",
"1, max_genome + 1): alignment.genomes[nr - 1] = alignment.genomes[nr] del alignment.genomes[max_genome] return alignment",
"not realign n_stretch = 'N' * max_seq_length if not (seq_one[interval_start:interval_end] == n_stretch or",
"score per definition of blat match = align_result[0][0] # add starting sequences, in",
"in range(hspfrag_key_num): hspfrag_key = hspfrag_keys[hspfrag_idx] hspfrag = match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) # add sequences",
"\"-\"): prev_gap = True # check if can be prepended to next entry",
"more than one entry left search for gaps that are present in all",
"< len(seq_two): seq_len = len(seq_two) - match.query_end seq_one_list.append(\"-\" * seq_len) seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(),",
"lcb in alignment.lcbs if len(lcb.entries) > 0] max_genome = len(alignment.genomes) for nr in",
"= list(set(range(len(match.hit_range_all))) - set(exclude_keys)) hspfrag_key_num = len(hspfrag_keys) for hspfrag_idx in range(hspfrag_key_num): hspfrag_key =",
"0) min_orig_seq_length = min(len(seq_one), len(seq_two)) seq_end = min(seq_end, min_orig_seq_length) # N-stretches in sequences",
"alignment, length): separated = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): separated.add_genome(genome, nr) for",
"False prev_gap = False next_gap = False to_reverse_complement = False next_new_entry = None",
"seq_two_list.append(seq_two[0:match.query_start]) if match.is_fragmented: # in really rare cases fragments are overlapping! exclude_keys =",
"if n_stretch_idx_two > -1 else seq_end) ) #if border_aln_length > 0: # print(seq_one[seq_start:seq_end])",
"enumerate([interval[0][1] - interval[0][0], interval[1][1] - interval[1][0]]), key=lambda p: p[1]) # get length of",
"choose the one with gap at start or end if (not next_gap) and",
"get length of gaps at start or end of block short_border_intervals = [(i[1]",
"alignment.lcbs = alignment.get_sorted_lcbs(order) j = 0 if alignment.lcbs[0].get_entry(order) is not None: new_alignment.add_lcb(alignment.lcbs[0]) for",
"index_offset += ((seq_end - seq_start) - max_length) return seq_one, seq_two def _external_blat(self, seq_one,",
"class Remover: def remove(self, alignment, rm_genome): if len(alignment.genomes) >= rm_genome > -1: for",
"all gaps in sequence entries[0].sequence = entries[0].sequence.replace(\"-\", \"\") if entries[0].genome_nr > rm_genome: entries[0].genome_nr",
"# border_aln_length not set OR small sequence at start or end of block",
"max_length < ( seq_end - seq_start ): # only use new alignment if",
"for item in alignments if item[4] == max_length])() aln_seq_one = alignments[0][0] aln_seq_two =",
"alignments from same set of genomes.\") if alignment.genomes[1].file_path != alignment_two.genomes[1].file_path: genome_nr_dict = {1:",
"= {1: 2, 2: 1} else: genome_nr_dict = {1: 1, 2: 2} for",
"prepended # add LCBs to alignment as it is else: merged_split_lcbs.append(lcb) merged =",
"only created by splitting or aligning of new genome (consensus is None) if",
"-= 1 # if no gaps found only reduce genome nr (avoid looping",
"remove? if len(entries) < len(lcb.entries): # are there any entries left in LCB?",
"strand: # if an entry does not fulfill all conditions stop and do",
"item in alignments if item[2] == max_score])() max_length = min([x[4] for x in",
"[lcb for lcb in alignment.lcbs if len(lcb.entries) > 0] max_genome = len(alignment.genomes) for",
"n_stretch_length)) # find N-stretch between interval and end and end sub-sequence before nearest",
"align_result = processor.external_blat(seq_one, seq_two) if align_result is not None: # seq_one equals hit",
"elif len(entries) == 1: # if only one entry left replace all gaps",
"if match.is_fragmented: # in really rare cases fragments are overlapping! exclude_keys = _check_tuple_overlap(match.hit_range_all)",
"only one entry left replace all gaps in sequence entries[0].sequence = entries[0].sequence.replace(\"-\", \"\")",
"len(alignment.genomes) > 2: raise ConsensusXMFAInputError() realigned = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items():",
"append or prepend: if to_reverse_complement: new_entry.reverse_complement() sequence = neighbour_new_entry.sequence neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length",
"in alignment.genomes.items(): separated.add_genome(genome, nr) for lcb in alignment.lcbs: if lcb.length <= length: for",
"if border_aln_length == 0 or any(short_border_intervals): # check if interval only 'N' -",
"max_seq_length seq_end = interval_end + max_seq_length # do not go over boundaries of",
"match.hit_start > 0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" * match.hit_start) if match.query_start > 0: seq_one_list.append(\"-\" *",
"overlapping! exclude_keys = _check_tuple_overlap(match.hit_range_all) exclude_keys = exclude_keys + _check_tuple_overlap(match.query_range_all) hspfrag_keys = list(set(range(len(match.hit_range_all))) -",
"single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr == 2: single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb) alignment.lcbs = pairlcbs return alignment,",
"min(len(seq_one), len(seq_two)) seq_end = min(seq_end, min_orig_seq_length) # N-stretches in sequences # find N-stretch",
"entries twice if gaps present) else: for entry in entries: if entry.genome_nr >",
"len(two_first_one_second) > 0: seq_two, seq_one = self._realign(entry_two.sequence, entry_one.sequence, two_first_one_second, processor, border_aln_length) entry_one.sequence =",
"class Realigner: # local realignment around overlapping or consecutive gaps in two sequences",
"len(seq_one)) # end of block or ((i[1] - index_offset) == len(seq_two))] # end",
"g in itertools.groupby(enumerate(rm_gaps), lambda x: x[0] - x[1]): group = list(map(itemgetter(1), g)) gap_ranges.append((group[0],",
"i += 1 if i == len(alignment.lcbs[lcb].entries): if not strand: # if all",
"!= lcb.length: gap_ranges = gap_ranges + [(lcb.length, lcb.length)] for entry in entries: entry.sequence",
"- prev_new_entry.end) == 1: use_prev = True if (prev_new_entry.strand == \"+\" and prev_new_entry.sequence[-1]",
"neighbour_new_entry.sequence neighbour_consensus_entry = neighbour_lcb.get_entry(consensus_genome_nr) neighbour_lcb.length += nr_gaps neighbour_new_entry.end = max(new_entry.end, neighbour_new_entry.end) neighbour_new_entry.start =",
"inter_query_len > 0: seq_one_list.append(\"-\" * inter_query_len) seq_two_list.append(seq_two[hspfrag.query_end:next_hspfrag.query_start]) else: seq_rec_one = match.aln[0] if seq_rec_one.id",
"if entry.genome_nr > rm_genome: entry.genome_nr -= 1 elif len(entries) == 1: # if",
"given length def realign(self, alignment, processor, border_aln_length=0): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError()",
"if seq_rec_one.id == \"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) # add last sequence",
"entries with second entry first two_first_one_second = self._get_realign_regions(entry_two.gaps, entry_one.gaps) if len(two_first_one_second) > 0:",
"do not include sequence ends if match.hit_end < len(seq_one): seq_len = len(seq_one) -",
"== \"+\": prepend = True else: append = True if neighbour_new_entry is not",
"unchecked lcbs # if only one lcb left check whether it is already",
"# add LCBs to alignment as it is else: merged_split_lcbs.append(lcb) merged = Alignment(alignment.xmfa_file)",
"interval_end, seq_end) seq_end = min(seq_end, (n_stretch_idx_one if n_stretch_idx_one > -1 else seq_end), (n_stretch_idx_two",
"genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return alignment class Remover: def remove(self, alignment, rm_genome): if len(alignment.genomes) >=",
"seq_two, processor): def _check_tuple_overlap(tuple_list): num_tuple = len(tuple_list) last_ok_end = -1 exclude_idx = []",
"complement this lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length for pos in range(0, len(new_alignment.lcbs[-1].entries)): new_alignment.lcbs[-1].entries[pos].sequence",
"== 1: use_prev = True if (prev_new_entry.strand == \"+\" and prev_new_entry.sequence[-1] == \"-\")",
"lcb.entries = sorted(lcb.entries, key=lambda entry: entry.genome_nr) new_alignment = Alignment(alignment.xmfa_file) for nr, genome in",
"no alignment, do nothing for current interval break if max_length > 0 and",
"= seq_one.find(n_stretch, interval_end, seq_end) n_stretch_idx_two = seq_two.find(n_stretch, interval_end, seq_end) seq_end = min(seq_end, (n_stretch_idx_one",
"if len(alignments) > 0: max_score = max([x[2] for x in alignments]) alignments =",
"def separate_lcbs(self, alignment, length): separated = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): separated.add_genome(genome,",
"# add sequences between aligned intervals to sequences if hspfrag_idx < (hspfrag_key_num -",
"seq_one_list = [] seq_two_list = [] if match.hit_start > 0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" *",
"think about cases with more than 2 genomes now.\") genome_names_one = [genome.file_path for",
"#overlap_detected = False for idx in range(num_tuple): if tuple_list[idx][0] < last_ok_end: #current start",
"left in LCB? if len(entries) > 1: # if more than one entry",
"new_alignment.add_lcb(alignment.lcbs[0]) for lcb in range(1, len(alignment.lcbs)): j += 1 if alignment.lcbs[lcb].get_entry(order) is not",
"for start, end in gaps_for_start.items()] + list(ends_dict.keys()) region_starts = [item for item, count",
"if hspfrag_idx < (hspfrag_key_num - 1): next_hspfrag = match[hspfrag_keys[hspfrag_idx + 1]] inter_hit_len =",
"+ max_seq_length # do not go over boundaries of sequences! seq_start = max(seq_start,",
"than one lcb is unchecked try to merge alignment.lcbs = alignment.get_sorted_lcbs(order) j =",
"regions.append([(start, gaps_for_start[start]), (ends_dict[start], start)]) return regions def _realign(self, seq_one, seq_two, realign_regions, processor, border_aln_length):",
"n_stretch_idx > -1: seq_start = max(seq_start, (n_stretch_idx + n_stretch_length)) n_stretch_idx = seq_two.rfind(n_stretch, seq_start,",
"go over boundaries of sequences! seq_start = max(seq_start, 0) min_orig_seq_length = min(len(seq_one), len(seq_two))",
"= [] for lcb in alignment.lcbs: if len(lcb.entries) == 1: if lcb.entries[0].strand ==",
"do nothing for current interval break else: # do external blat alignment aln_seq_one,",
"with a gap if len(lcbs) > (i+1): next_lcb = lcbs[i + 1] next_new_entry",
"not be merged or could be neither appended nor prepended # add LCBs",
"order in alignment.genomes: if len(alignment.lcbs) > 1: # if more than one lcb",
"- interval[1][0]]), key=lambda p: p[1]) # get length of gaps at start or",
"index_offset = 0 for interval in realign_regions: max_index, max_seq_length = max( enumerate([interval[0][1] -",
"in lcb.entries: seq = entry.sequence.replace(\"-\", \"\") new_entry = SequenceEntry(entry.genome_nr, entry.start, entry.end, entry.strand, seq)",
"entry and if that starts with a gap if len(lcbs) > (i+1): next_lcb",
"seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\", \"\") if not (seq_one_nogap == ''",
"realigned.add_lcb(new_lcb) return realigned def _get_realign_regions(self, gaps_for_start, gaps_for_end): ends_dict = {end: start for start,",
"alignment.lcbs[0].get_entry(order) is not None: new_alignment.add_lcb(alignment.lcbs[0]) for lcb in range(1, len(alignment.lcbs)): j += 1",
"strand reverse complement this lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length for pos in range(0,",
"= [genome.file_path for genome in alignment_two.genomes.values()] if genome_names_one.sort() != genome_names_two.sort(): print(\"ERROR: Can only",
"# if both, choose the one with gap at start or end if",
"alignment if better than old one #if border_aln_length > 0: # print(aln_seq_one) #",
"border_aln_length not set OR small sequence at start or end of block if",
"if can be prepended to next entry and if that starts with a",
"sub-sequence before nearest stretch n_stretch_idx_one = seq_one.find(n_stretch, interval_end, seq_end) n_stretch_idx_two = seq_two.find(n_stretch, interval_end,",
"None: if new_entry.strand != neighbour_new_entry.strand: to_reverse_complement = True if append or prepend: if",
"(avoid looping through entries twice if gaps present) else: for entry in entries:",
"with gap at start or end if (not next_gap) and use_prev: neighbour_new_entry =",
"append/prepend sequence merged_split_lcbs = [] for i in range(len(lcbs)): lcb = lcbs[i] new_entry",
"for genome in alignment_two.genomes.values()] if genome_names_one.sort() != genome_names_two.sort(): print(\"ERROR: Can only join alignments",
"next_new_entry = next_lcb.get_entry(new_genome_nr) if next_new_entry is not None and (next_new_entry.start - new_entry.end) ==",
"block border up to given length def realign(self, alignment, processor, border_aln_length=0): if len(alignment.genomes)",
"else: new_alignment.add_lcb(alignment.lcbs[lcb]) else: break alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)] # continue with unchecked lcbs #",
"lcb left check whether it is already checked or not elif len(alignment.lcbs) ==",
"interval_start - max_seq_length seq_end = interval_end + max_seq_length # do not go over",
"processor, border_aln_length): # if border_aln_length is not None align only sequences at block",
"seq_two_list.append(\"-\" * seq_len) if match.query_end < len(seq_two): seq_len = len(seq_two) - match.query_end seq_one_list.append(\"-\"",
"+= alignment.lcbs[lcb].entries[pos].sequence new_alignment.lcbs[-1].entries[pos].end = alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb]) else: break alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)] #",
"alignment.get_sorted_lcbs(0): if len(lcb.entries) == 1: realigned.add_lcb(lcb) else: entry_one = lcb.entries[0] entry_two = lcb.entries[1]",
"consensus_genome_nr, new_genome_nr, block_length): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() lcbs = alignment.get_sorted_lcbs(new_genome_nr) #",
"block if border_aln_length == 0 or any(short_border_intervals): # check if interval only 'N'",
"if alignment.lcbs[0].get_entry(order) is not None: new_alignment.add_lcb(alignment.lcbs[0]) for lcb in range(1, len(alignment.lcbs)): j +=",
"\"\") if not (seq_one_nogap == '' or seq_two_nogap == ''): # else: do",
"- max_seq_length seq_end = interval_end + max_seq_length # do not go over boundaries",
"(n_stretch_idx + n_stretch_length)) n_stretch_idx = seq_two.rfind(n_stretch, seq_start, interval_start) if n_stretch_idx > -1: seq_start",
"do nothing for current interval if (seq_end - seq_start) < 1000: #https://github.com/biopython/biopython/pull/782 alignments",
"None prev_new_entry = None # check if new entry is small and only",
"import itertools from operator import itemgetter import math from Bio import pairwise2 from",
"query # only one query and first hit has highest score per definition",
"parts if hit or query do not include sequence ends if match.hit_end <",
"new alignment if better than old one #if border_aln_length > 0: # print(aln_seq_one)",
"entry.genome_nr) new_alignment = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): new_alignment.add_genome(genome, nr) for order",
"left search for gaps that are present in all remaining entries rm_gaps =",
"interval only 'N' - if yes: do not realign n_stretch = 'N' *",
"highest score per definition of blat match = align_result[0][0] # add starting sequences,",
"use_next = True if (next_new_entry.strand == \"+\" and next_new_entry.sequence[0] == \"-\")\\ or (next_new_entry.strand",
"# add last sequence parts if hit or query do not include sequence",
"entry first two_first_one_second = self._get_realign_regions(entry_two.gaps, entry_one.gaps) if len(two_first_one_second) > 0: seq_two, seq_one =",
"rm_genome, \"between 0 and \" + str(len(alignment.genomes)) + \" (number of genomes in",
"lcb.length: gap_ranges = gap_ranges + [(lcb.length, lcb.length)] for entry in entries: entry.sequence =",
"only sequences at block border up to given length realign_regions = sorted(realign_regions) index_offset",
"rm_gaps = sorted(list(rm_gaps)) # make intervals of consecutive gap positions for faster join()",
"entry_two.sequence = seq_two # get regions to realign for updated entries with second",
"\"-\" and next_new_entry.sequence[-1] == \"-\"): next_gap = True neighbour_new_entry = None # if",
"n_stretch or seq_two[interval_start:interval_end] == n_stretch): max_seq_length = math.ceil(max_seq_length * 1.5) # get surrounding",
"nr, genome in alignment.genomes.items(): separated.add_genome(genome, nr) for lcb in alignment.lcbs: if lcb.length <=",
"- x[1]): group = list(map(itemgetter(1), g)) gap_ranges.append((group[0], group[-1])) # tuples with intervals if",
"for i in interval # check border length if i[0] == 0 #",
"check if can be prepended to next entry and if that starts with",
"add starting sequences, in case query or hit do not start at \"0\"",
"alignment_two.lcbs: for entry in lcb.entries: entry.genome_nr = genome_nr_dict[entry.genome_nr] alignment.add_lcb(lcb) return alignment class Remover:",
"seqseqpan.base import * class Separator: def separate_lcbs(self, alignment, length): separated = Alignment(alignment.xmfa_file) for",
"seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\", \"\") if not (seq_one_nogap == '' or seq_two_nogap",
"LCB() new_lcb.add_entries([entry_one, entry_two]) realigned.add_lcb(new_lcb) return realigned def _get_realign_regions(self, gaps_for_start, gaps_for_end): ends_dict = {end:",
"def realign(self, alignment, processor, border_aln_length=0): if len(alignment.genomes) > 2: raise ConsensusXMFAInputError() realigned =",
"location_list = [start for start, end in gaps_for_start.items()] + list(ends_dict.keys()) region_starts = [item",
"lcb in alignment.lcbs: entries = [entry for entry in lcb.entries if entry.genome_nr !=",
"next_lcb = lcbs[i + 1] next_new_entry = next_lcb.get_entry(new_genome_nr) if next_new_entry is not None",
"= interval[max_index][1] - index_offset # border_aln_length not set OR small sequence at start",
"an unequal strand reverse complement this lcb alignment.lcbs[lcb].reverse_complement_entries() new_alignment.lcbs[-1].length += alignment.lcbs[lcb].length for pos",
"cases with more than 2 genomes now.\") genome_names_one = [genome.file_path for genome in",
"alignment.lcbs[lcb].entries[pos].end else: new_alignment.add_lcb(alignment.lcbs[lcb]) else: break alignment.lcbs[:] = alignment.lcbs[j:len(alignment.lcbs)] # continue with unchecked lcbs",
"'N' - if yes: do not realign n_stretch = 'N' * max_seq_length if",
"(new_entry.start - prev_new_entry.end) == 1: use_prev = True if (prev_new_entry.strand == \"+\" and",
"list(ends_dict.keys()) region_starts = [item for item, count in collections.Counter(location_list).items() if count > 1]",
"!= alignment_two.genomes[1].file_path: genome_nr_dict = {1: 2, 2: 1} else: genome_nr_dict = {1: 1,",
"nothing for current interval break else: # do external blat alignment aln_seq_one, aln_seq_two",
"else: return None, None class SingletonAligner: def genome_count_split(self, alignment): if len(alignment.genomes) > 2:",
"== len(seq_one)) # end of block or ((i[1] - index_offset) == len(seq_two))] #",
"0: # print(seq_one[seq_start:seq_end]) # print(seq_two[seq_start:seq_end]) seq_one_nogap = seq_one[seq_start:seq_end].replace(\"-\", \"\") seq_two_nogap = seq_two[seq_start:seq_end].replace(\"-\", \"\")",
"entry.genome_nr -= 1 elif len(entries) == 1: # if only one entry left",
"lcb.entries[0].genome_nr == 1: single_alignment_1.add_lcb(lcb) elif lcb.entries[0].genome_nr == 2: single_alignment_2.add_lcb(lcb) else: pairlcbs.append(lcb) alignment.lcbs =",
"len(alignment.genomes) for nr in range(rm_genome + 1, max_genome + 1): alignment.genomes[nr - 1]",
"- new_entry.end) == 1: use_next = True if (next_new_entry.strand == \"+\" and next_new_entry.sequence[0]",
"= sorted(lcb.entries, key=lambda entry: entry.genome_nr) new_alignment = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items():",
"do not start at \"0\" seq_one_list = [] seq_two_list = [] if match.hit_start",
"is not None: i = 0 if len(alignment.lcbs[lcb].entries) == len(alignment.lcbs[lcb - 1].entries): strand",
"next_gap = False to_reverse_complement = False next_new_entry = None prev_new_entry = None #",
"left check whether it is already checked or not elif len(alignment.lcbs) == 1",
"= match.aln[0] if seq_rec_one.id == \"seq1\": seq_one_list.append(str(match.aln[0].seq)) seq_two_list.append(str(match.aln[1].seq)) else: seq_one_list.append(str(match.aln[1].seq)) seq_two_list.append(str(match.aln[0].seq)) # add",
"end of block short_border_intervals = [(i[1] - i[0]) <= border_aln_length for i in",
"entry_one.sequence = seq_one entry_two.sequence = seq_two # get regions to realign for updated",
"seq_len = len(seq_two) - match.query_end seq_one_list.append(\"-\" * seq_len) seq_two_list.append(seq_two[match.query_end:]) return \"\".join(seq_one_list).upper(), \"\".join(seq_two_list).upper() else:",
"new_entry = SequenceEntry(entry.genome_nr, entry.start, entry.end, entry.strand, seq) separated.add_lcb_entries(new_entry) else: separated.add_lcb(lcb) return separated class",
"use_next = False prev_gap = False next_gap = False to_reverse_complement = False next_new_entry",
"neighbour_consensus_entry.sequence # entry should not be merged or could be neither appended nor",
"+ 1):gap_ranges[i + 1][0]] for i in range(len(gap_ranges) - 1)]) if entry.genome_nr >",
"seq_one[seq_end:]]) seq_two = aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset += ((seq_end - seq_start) - max_length) return",
"gap_ranges + [(lcb.length, lcb.length)] for entry in entries: entry.sequence = ''.join( [entry.sequence[(gap_ranges[i][1] +",
"it is else: merged_split_lcbs.append(lcb) merged = Alignment(alignment.xmfa_file) for nr, genome in alignment.genomes.items(): merged.add_genome(genome,",
"# find N-stretch between interval and end and end sub-sequence before nearest stretch",
"i == len(alignment.lcbs[lcb].entries): if not strand: # if all entries have an unequal",
"for hspfrag_idx in range(hspfrag_key_num): hspfrag_key = hspfrag_keys[hspfrag_idx] hspfrag = match[hspfrag_key] seq_one_list.append(str(hspfrag.hit.seq)) seq_two_list.append(str(hspfrag.query.seq)) #",
"tuple is ok -> store end return exclude_idx align_result = processor.external_blat(seq_one, seq_two) if",
"join(self, alignment, alignment_two): if len(alignment.genomes) > 2: print(\"ERROR: I don't want to think",
"not None and (new_entry.start - prev_new_entry.end) == 1: use_prev = True if (prev_new_entry.strand",
"seq_two_list.append(str(match.aln[0].seq)) # add last sequence parts if hit or query do not include",
"do not go over boundaries of sequences! seq_start = max(seq_start, 0) min_orig_seq_length =",
"and first hit has highest score per definition of blat match = align_result[0][0]",
"(lambda max_length=max_length: [item for item in alignments if item[4] == max_length])() aln_seq_one =",
"rm_gaps &= set( itertools.chain.from_iterable([list(range(k, entry.gaps[k])) for k in entry.gaps])) rm_gaps = sorted(list(rm_gaps)) #",
"ends if match.hit_end < len(seq_one): seq_len = len(seq_one) - match.hit_end seq_one_list.append(seq_one[match.hit_end:]) seq_two_list.append(\"-\" *",
"find N-stretch between start and interval and start sub-sequence after nearest stretch n_stretch_length",
"[entry for entry in lcb.entries if entry.genome_nr != rm_genome] # did LCB include",
"entry.genome_nr != rm_genome] # did LCB include entry of genome to remove? if",
"((i[1] - index_offset) == len(seq_one)) # end of block or ((i[1] - index_offset)",
"new_alignment.lcbs[-1].entries[0].genome_nr != alignment.lcbs[0].entries[0].genome_nr: new_alignment.add_lcb(alignment.lcbs[0]) # if not checked yet add it as last",
"one-entry ones for lcb in alignment.get_sorted_lcbs(0): if len(lcb.entries) == 1: realigned.add_lcb(lcb) else: entry_one",
"surrounding sequences seq_start = interval_start - max_seq_length seq_end = interval_end + max_seq_length #",
"not (seq_one[interval_start:interval_end] == n_stretch or seq_two[interval_start:interval_end] == n_stretch): max_seq_length = math.ceil(max_seq_length * 1.5)",
"print(aln_seq_two) seq_one = aln_seq_one.join([seq_one[:seq_start], seq_one[seq_end:]]) seq_two = aln_seq_two.join([seq_two[:seq_start], seq_two[seq_end:]]) index_offset += ((seq_end -",
"seq_end), (n_stretch_idx_two if n_stretch_idx_two > -1 else seq_end) ) #if border_aln_length > 0:",
"True neighbour_new_entry = None # if both, choose the one with gap at",
"start for start, end in gaps_for_end.items()} location_list = [start for start, end in",
"= [] seq_two_list = [] if match.hit_start > 0: seq_one_list.append(seq_one[0:match.hit_start]) seq_two_list.append(\"-\" * match.hit_start)",
"0: prev_lcb = merged_split_lcbs[-1] prev_new_entry = prev_lcb.get_entry(new_genome_nr) if prev_new_entry is not None and",
"x[0] - x[1]): group = list(map(itemgetter(1), g)) gap_ranges.append((group[0], group[-1])) # tuples with intervals",
"end return exclude_idx align_result = processor.external_blat(seq_one, seq_two) if align_result is not None: #",
"at \"0\" seq_one_list = [] seq_two_list = [] if match.hit_start > 0: seq_one_list.append(seq_one[0:match.hit_start])",
"= [entry for entry in lcb.entries if entry.genome_nr != rm_genome] # did LCB",
"range(1, len(alignment.lcbs)): j += 1 if alignment.lcbs[lcb].get_entry(order) is not None: i = 0"
] |
[
"it's read in, so ### the memory lines up better? output[i,:] = self.data[:,data_index]",
"length of the timeseries Outputs: site_indices: the list of sites with active capacity",
"the memory lines up better? output[i,:] = self.data[:,data_index] * total_cap return site_indices, output",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. # #",
"and to permit persons to whom the Software is #furnished to do so,",
"number of site indices mapped. The first in each pair is the site",
"map_data[:,0] elif len(self.params_to_site) > 0: # No data map is provided, but params_to_site",
"not (len(self.params_to_site) == self.data.shape[1]): raise mureilexception.ConfigException('In model ' + self.config['section'] + ', no",
"variable_cost, carbon, other \"\"\" vom = self.period_configs[state_handle['curr_period']]['vom'] * 1e-6 num_sites = len(site_indices) vble_cost",
"self.site_to_data[self.params_to_site[i]] = i else: # No list of sites is provided. Just map",
"= self.site_to_data[site] ### TODO - it may be expensive to have self.data this",
"read in, so ### the memory lines up better? output[i,:] = self.data[:,data_index] *",
"self.config['detail_type'] + ' with site capacities (MW): ' + ( string.join(map('({:d}: {:.2f}) '.format,",
"no params to site, so assume # all data are used and map",
"len(site_indices) vble_cost = numpy.zeros(num_sites) carbon = numpy.zeros(num_sites) for i in range(num_sites): vble_cost[i] =",
"tech_type: string - the generic technology type, to report in get_details() as technology.",
"one timeseries per site, in MW. \"\"\" offer_price = self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity =",
"def set_data(self, data): \"\"\"Set the data dict with the data series required for",
"notice and this permission notice shall be included in all #copies or substantial",
"carbon = numpy.zeros(num_sites) for i in range(num_sites): vble_cost[i] = numpy.sum(schedule[i,:]) * vom return",
"data map, but no params to site, so assume # all data are",
"the maximum index in the data array is ' + str(max_data), {}) def",
"IN THE #SOFTWARE. # # \"\"\"Module for a variable generator using the txmultigeneratormultisite",
"technology type, to report in get_details() as technology. detail_type: string - a specific",
"of sites with active capacity output: a set of timeseries, corresponding to site_indices",
"ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"specific name, e.g. 'onshore_wind_vic', for printing in an output string data_name: string -",
"* 1e-6 num_sites = len(site_indices) vble_cost = numpy.zeros(num_sites) carbon = numpy.zeros(num_sites) for i",
"a list of keys for each type of data required, for example ts_wind,",
"ts_wind_map which holds an n x 2 array where n is the number",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION",
"to the following conditions: # #The above copyright notice and this permission notice",
"in TxMultiGeneratorBase, for the variable generators. \"\"\" site_indices, supply = self.calculate_outputs(state_handle, len(supply_request)) vble_cost,",
"output[i,:] = self.data[:,data_index] * total_cap return site_indices, output def calculate_variable_costs(self, state_handle, site_indices, schedule):",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE",
"list of tuples of format (name, conversion function, default), e.g. ('capex', float, 2.0).",
"= data[self.config['data_name']] self.site_to_data = {} if len(self.config['data_map_name']) > 0: map_data = data[self.config['data_map_name']] for",
"self.data.shape[1]): raise mureilexception.ConfigException('In model ' + self.config['section'] + ', no data map is",
"properties of the generator. \"\"\" flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] = self.config['tech_type'] flags['dispatch'] =",
"of the timeseries Outputs: site_indices: the list of sites with active capacity output:",
"ts_length)) for i in range(num_sites): site = site_indices[i] total_cap = sum([tup[0] for tup",
"this is not provided, a 1:1 is assumed. data_ts_length: the length of the",
"data map is provided, but params_to_site is. If the # lengths agree, map",
"(data_index >= max_data): raise mureilexception.ConfigException('data_index ' + str(data_index) + ' was requested by",
"per site (interpreted as same for all timesteps) quantity: the offer quantity, one",
"copy import numpy import string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple implementation of a",
"for i in range(0, map_data.shape[0]): self.site_to_data[map_data[i, 0]] = map_data[i, 1] if len(self.params_to_site) ==",
"indices of each site with active capacity. All lists of sites below will",
"def calculate_outputs(self, state_handle, ts_length): \"\"\"Calculate the maximum outputs, before scheduling. Inputs: state_handle ts_length:",
"have self.data this way - ### would it help to transpose it when",
"base class. \"\"\" from tools import configurablebase, mureilexception from generator import txmultigeneratormultisite from",
"name of the data array holding the timeseries capacity factor data, e.g. ts_wind.",
"txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [ ('tech_type', None, 'generic_variable'), ('detail_type', None, 'generic_variable'), ('data_name', None, None), ('data_map_name',",
"= data[self.config['data_map_name']] for i in range(0, map_data.shape[0]): self.site_to_data[map_data[i, 0]] = map_data[i, 1] if",
"Outputs: site_indices: the list of sites with active capacity output: a set of",
"factor data, e.g. ts_wind. data_map_name: string - the name of the data array",
"= site_indices[i] total_cap = sum([tup[0] for tup in cap_list[site]]) data_index = self.site_to_data[site] ###",
"generator. \"\"\" flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] = self.config['tech_type'] flags['dispatch'] = 'semischeduled' return flags",
"numbers. self.params_to_site = range(self.data.shape[1]) for i in range(0, self.data.shape[1]): self.site_to_data[i] = i #",
"cap_list[site]]) data_index = self.site_to_data[site] ### TODO - it may be expensive to have",
"the SRMC. This is the VOM for variable generators. \"\"\" return self.period_configs[period]['vom'] def",
"this way - ### would it help to transpose it when it's read",
"substantial portions of the Software. # #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"example ts_wind, ts_demand. Outputs: data_type: list of strings - each a key name",
"* vom return vble_cost, carbon, {} def calculate_outputs_and_costs(self, state_handle, supply_request, max_supply=[], price=[]): \"\"\"Implement",
"+ str(data_index) + ' was requested by the model in section ' +",
"self.site_to_data.itervalues(): if (data_index < 0) or (data_index >= max_data): raise mureilexception.ConfigException('data_index ' +",
"TxMultiGeneratorBase, for the variable generator. \"\"\" return self.config['detail_type'] + ' with site capacities",
"vom = self.period_configs[state_handle['curr_period']]['vom'] * 1e-6 num_sites = len(site_indices) vble_cost = numpy.zeros(num_sites) carbon =",
"i in range(0, map_data.shape[0]): self.site_to_data[map_data[i, 0]] = map_data[i, 1] if len(self.params_to_site) == 0:",
"len(self.params_to_site) == 0: # We have a data map, but no params to",
"= self.get_site_indices(state_handle) num_sites = len(site_indices) output = numpy.zeros((num_sites, ts_length)) for i in range(num_sites):",
"the data 1:1. if not (len(self.params_to_site) == self.data.shape[1]): raise mureilexception.ConfigException('In model ' +",
"= sum([tup[0] for tup in cap_list[site]]) data_index = self.site_to_data[site] ### TODO - it",
"it may be expensive to have self.data this way - ### would it",
"FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"get_config_spec(self): \"\"\"Return a list of tuples of format (name, conversion function, default), e.g.",
"max_data): raise mureilexception.ConfigException('data_index ' + str(data_index) + ' was requested by the model",
"' so no automatic mapping is possible.', {}) for i in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]]",
"capacity factor data, e.g. ts_wind. data_map_name: string - the name of the data",
"of charge, to any person obtaining a copy #of this software and associated",
"#copies of the Software, and to permit persons to whom the Software is",
"each pair is the site index and the second the index into the",
"the timeseries Outputs: site_indices: the list of sites with active capacity output: a",
"= self.calculate_variable_costs(state_handle, site_indices, supply) return supply, vble_cost, carbon, other def get_simple_desc_string(self, results, state_handle):",
"' but the maximum index in the data array is ' + str(max_data),",
"is provided, but params_to_site is. If the # lengths agree, map the site",
"+ str(self.data.shape[1]) + ' and the provided params_to_site list is ' + str(len(self.params_to_site))",
"carbon, other \"\"\" vom = self.period_configs[state_handle['curr_period']]['vom'] * 1e-6 num_sites = len(site_indices) vble_cost =",
"(len(self.params_to_site) == self.data.shape[1]): raise mureilexception.ConfigException('In model ' + self.config['section'] + ', no data",
"dispatch offer as the SRMC. This is the VOM for variable generators. \"\"\"",
"the identifying indices of each site with active capacity. All lists of sites",
"output: a set of timeseries, corresponding to site_indices \"\"\" cap_list = state_handle['capacity'] site_indices",
"granted, free of charge, to any person obtaining a copy #of this software",
"capacities (MW): ' + ( string.join(map('({:d}: {:.2f}) '.format, results['site_indices'], results['capacity']))) def get_full_desc_string(self, results,",
"\"\"\" return self.period_configs[period]['vom'] def get_offers_semischeduled(self, state_handle, ts_length): \"\"\"Get offers for this semi-scheduled generator.",
"capacity output: a set of timeseries, corresponding to site_indices \"\"\" cap_list = state_handle['capacity']",
"self.site_to_data = {} if len(self.config['data_map_name']) > 0: map_data = data[self.config['data_map_name']] for i in",
"defined in TxMultiGeneratorBase, for the variable generator. \"\"\" return self.config['detail_type'] + ' with",
"or if no default value, e.g. ('name', None, None) Configuration: as for txmultigenerator.TxMultiGeneratorBase,",
"\"\"\"Calculate the dispatch offer as the SRMC. This is the VOM for variable",
"this semi-scheduled generator. Outputs: site_indices: the identifying indices of each site with active",
"e.g. ts_wind_map which holds an n x 2 array where n is the",
"None, 'generic_variable'), ('detail_type', None, 'generic_variable'), ('data_name', None, None), ('data_map_name', None, ''), ('data_ts_length', int,",
"charge, to any person obtaining a copy #of this software and associated documentation",
"The scheduled output, a set of timeseries Outputs: variable_cost, carbon, other \"\"\" vom",
"#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT",
"len(self.config['data_map_name']) > 0: data_types.append(self.config['data_map_name']) return data_types def set_data(self, data): \"\"\"Set the data dict",
"= self.calculate_outputs(state_handle, len(supply_request)) vble_cost, carbon, other = self.calculate_variable_costs(state_handle, site_indices, supply) return supply, vble_cost,",
"site capacities (MW): ' + ( string.join(map('({:d}: {:.2f}) '.format, results['site_indices'], results['capacity']))) def get_full_desc_string(self,",
"the Software. # #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"n is the number of site indices mapped. The first in each pair",
"dict - with keys matching those requested by get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data",
"generators. \"\"\" return self.period_configs[period]['vom'] def get_offers_semischeduled(self, state_handle, ts_length): \"\"\"Get offers for this semi-scheduled",
"' with site capacities (MW): ' + ( string.join(map('({:d}: {:.2f}) '.format, results['site_indices'], results['capacity'])))",
"n x 2 array where n is the number of site indices mapped.",
"from master import interfacesflowmaster import copy import numpy import string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch):",
"required for the generator. Inputs: data: dict - with keys matching those requested",
"in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] = i else: # No list of sites is provided.",
"costs. \"\"\" def get_details(self): \"\"\"Return a list of flags indicating the properties of",
"of Melbourne 2013 # # # #Permission is hereby granted, free of charge,",
"without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"the Software without restriction, including without limitation the rights #to use, copy, modify,",
"table. If this is not provided, a 1:1 is assumed. data_ts_length: the length",
"== 0: # We have a data map, but no params to site,",
"\"\"\" site_indices, supply = self.calculate_outputs(state_handle, len(supply_request)) vble_cost, carbon, other = self.calculate_variable_costs(state_handle, site_indices, supply)",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE",
"the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies",
"data are used and map 1:1 to this. self.params_to_site = map_data[:,0] elif len(self.params_to_site)",
"a copy #of this software and associated documentation files (the \"Software\"), to deal",
"indicating the properties of the generator. \"\"\" flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] = self.config['tech_type']",
"transpose it when it's read in, so ### the memory lines up better?",
"\"\"\" flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] = self.config['tech_type'] flags['dispatch'] = 'semischeduled' return flags def",
"* total_cap return site_indices, output def calculate_variable_costs(self, state_handle, site_indices, schedule): \"\"\"Calculate variable costs",
"vble_cost, carbon, other def get_simple_desc_string(self, results, state_handle): \"\"\"Implement get_simple_desc_string as defined in TxMultiGeneratorBase,",
"Software. # #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"the generator. \"\"\" flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] = self.config['tech_type'] flags['dispatch'] = 'semischeduled' return",
"if no default value, e.g. ('name', None, None) Configuration: as for txmultigenerator.TxMultiGeneratorBase, plus:",
"if len(self.config['data_map_name']) > 0: map_data = data[self.config['data_map_name']] for i in range(0, map_data.shape[0]): self.site_to_data[map_data[i,",
"data is width ' + str(self.data.shape[1]) + ' and the provided params_to_site list",
"self.data[:,data_index] * total_cap return site_indices, output def calculate_variable_costs(self, state_handle, site_indices, schedule): \"\"\"Calculate variable",
"generator. Outputs: site_indices: the identifying indices of each site with active capacity. All",
"calculate_outputs_and_costs as defined in TxMultiGeneratorBase, for the variable generators. \"\"\" site_indices, supply =",
"variable generator. \"\"\" return self.config['detail_type'] + ' with site capacities (MW): ' +",
"is hereby granted, free of charge, to any person obtaining a copy #of",
"site_indices = self.get_site_indices(state_handle) num_sites = len(site_indices) output = numpy.zeros((num_sites, ts_length)) for i in",
"data map is provided, the data is width ' + str(self.data.shape[1]) + '",
"scheduling. Inputs: state_handle ts_length: an integer - the length of the timeseries Outputs:",
"in cap_list[site]]) data_index = self.site_to_data[site] ### TODO - it may be expensive to",
"FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"# \"\"\"Module for a variable generator using the txmultigeneratormultisite base class. \"\"\" from",
"the data required for this generator. \"\"\" data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if len(self.config['data_map_name'])",
"vom return vble_cost, carbon, {} def calculate_outputs_and_costs(self, state_handle, supply_request, max_supply=[], price=[]): \"\"\"Implement calculate_outputs_and_costs",
"same for all timesteps) quantity: the offer quantity, one timeseries per site, in",
"data: dict - with keys matching those requested by get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data)",
"below will correspond with this list. offer_price: the offer price, one per site",
"site, in MW. \"\"\" offer_price = self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity = self.calculate_outputs(state_handle, ts_length) return",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER",
"typically provided globally. \"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [ ('tech_type', None, 'generic_variable'), ('detail_type', None,",
"if len(self.config['data_map_name']) > 0: data_types.append(self.config['data_map_name']) return data_types def set_data(self, data): \"\"\"Set the data",
"is width ' + str(self.data.shape[1]) + ' and the provided params_to_site list is",
"flags['technology'] = self.config['tech_type'] flags['dispatch'] = 'semischeduled' return flags def get_config_spec(self): \"\"\"Return a list",
"Inputs: data: dict - with keys matching those requested by get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self,",
"\"\"\"Calculate the maximum outputs, before scheduling. Inputs: state_handle ts_length: an integer - the",
"keys for each type of data required, for example ts_wind, ts_demand. Outputs: data_type:",
"numpy import string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple implementation of a variable generator,",
"offer quantity, one timeseries per site, in MW. \"\"\" offer_price = self.calculate_dispatch_offer(state_handle['curr_period']) site_indices,",
"= map_data[i, 1] if len(self.params_to_site) == 0: # We have a data map,",
"num_sites = len(site_indices) vble_cost = numpy.zeros(num_sites) carbon = numpy.zeros(num_sites) for i in range(num_sites):",
"string - the generic technology type, to report in get_details() as technology. detail_type:",
"providing per-unit capital costs. \"\"\" def get_details(self): \"\"\"Return a list of flags indicating",
"the list of sites with active capacity output: a set of timeseries, corresponding",
"to permit persons to whom the Software is #furnished to do so, subject",
"a key name describing the data required for this generator. \"\"\" data_types =",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE",
"of sites below will correspond with this list. offer_price: the offer price, one",
"will correspond with this list. offer_price: the offer price, one per site (interpreted",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE.",
"i in range(num_sites): vble_cost[i] = numpy.sum(schedule[i,:]) * vom return vble_cost, carbon, {} def",
"\"\"\" def get_details(self): \"\"\"Return a list of flags indicating the properties of the",
"site index list to the data 1:1. if not (len(self.params_to_site) == self.data.shape[1]): raise",
"maximum outputs, before scheduling. Inputs: state_handle ts_length: an integer - the length of",
"= numpy.zeros(num_sites) carbon = numpy.zeros(num_sites) for i in range(num_sites): vble_cost[i] = numpy.sum(schedule[i,:]) *",
"\"\"\"Set the data dict with the data series required for the generator. Inputs:",
"costs and carbon based on schedule. Inputs: state_handle site_indices schedule: The scheduled output,",
"data_types def set_data(self, data): \"\"\"Set the data dict with the data series required",
"= numpy.sum(schedule[i,:]) * vom return vble_cost, carbon, {} def calculate_outputs_and_costs(self, state_handle, supply_request, max_supply=[],",
"provided. Just map to ordinal numbers. self.params_to_site = range(self.data.shape[1]) for i in range(0,",
"distribute, sublicense, and/or sell #copies of the Software, and to permit persons to",
"site_indices, supply) return supply, vble_cost, carbon, other def get_simple_desc_string(self, results, state_handle): \"\"\"Implement get_simple_desc_string",
"in section ' + self.config['section'] + ' but the maximum index in the",
"generator import txmultigeneratormultisite from master import interfacesflowmaster import copy import numpy import string",
"site_indices, schedule): \"\"\"Calculate variable costs and carbon based on schedule. Inputs: state_handle site_indices",
"- the name of the data array holding the timeseries capacity factor data,",
"in MW. \"\"\" offer_price = self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity = self.calculate_outputs(state_handle, ts_length) return site_indices,",
"Software, and to permit persons to whom the Software is #furnished to do",
"data table. If this is not provided, a 1:1 is assumed. data_ts_length: the",
"return self.period_configs[period]['vom'] def get_offers_semischeduled(self, state_handle, ts_length): \"\"\"Get offers for this semi-scheduled generator. Outputs:",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. #",
"- ### would it help to transpose it when it's read in, so",
"# #The above copyright notice and this permission notice shall be included in",
"and associated documentation files (the \"Software\"), to deal #in the Software without restriction,",
"but no params to site, so assume # all data are used and",
"\"Software\"), to deal #in the Software without restriction, including without limitation the rights",
"copyright notice and this permission notice shall be included in all #copies or",
"len(self.params_to_site) > 0: # No data map is provided, but params_to_site is. If",
"list of sites with active capacity output: a set of timeseries, corresponding to",
"to deal #in the Software without restriction, including without limitation the rights #to",
"of the Software, and to permit persons to whom the Software is #furnished",
"map to ordinal numbers. self.params_to_site = range(self.data.shape[1]) for i in range(0, self.data.shape[1]): self.site_to_data[i]",
"configurablebase, mureilexception from generator import txmultigeneratormultisite from master import interfacesflowmaster import copy import",
"capacity. All lists of sites below will correspond with this list. offer_price: the",
"restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute,",
"list. offer_price: the offer price, one per site (interpreted as same for all",
"a set of timeseries, corresponding to site_indices \"\"\" cap_list = state_handle['capacity'] site_indices =",
"string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple implementation of a variable generator, providing per-unit",
"this generator. \"\"\" data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if len(self.config['data_map_name']) > 0: data_types.append(self.config['data_map_name']) return",
"import configurablebase, mureilexception from generator import txmultigeneratormultisite from master import interfacesflowmaster import copy",
"ordinal numbers. self.params_to_site = range(self.data.shape[1]) for i in range(0, self.data.shape[1]): self.site_to_data[i] = i",
"' + str(data_index) + ' was requested by the model in section '",
"OR OTHER DEALINGS IN THE #SOFTWARE. # # \"\"\"Module for a variable generator",
"in, so ### the memory lines up better? output[i,:] = self.data[:,data_index] * total_cap",
"outputs, before scheduling. Inputs: state_handle ts_length: an integer - the length of the",
"of sites is provided. Just map to ordinal numbers. self.params_to_site = range(self.data.shape[1]) for",
"data[self.config['data_name']] self.site_to_data = {} if len(self.config['data_map_name']) > 0: map_data = data[self.config['data_map_name']] for i",
"up better? output[i,:] = self.data[:,data_index] * total_cap return site_indices, output def calculate_variable_costs(self, state_handle,",
"OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"of the generator. \"\"\" flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] = self.config['tech_type'] flags['dispatch'] = 'semischeduled'",
"this software and associated documentation files (the \"Software\"), to deal #in the Software",
"timeseries, corresponding to site_indices \"\"\" cap_list = state_handle['capacity'] site_indices = self.get_site_indices(state_handle) num_sites =",
"# # Copyright (C) University of Melbourne 2013 # # # #Permission is",
"tools import configurablebase, mureilexception from generator import txmultigeneratormultisite from master import interfacesflowmaster import",
"get_data_types(self): \"\"\"Return a list of keys for each type of data required, for",
"data_type: list of strings - each a key name describing the data required",
"timeseries capacity factor data, e.g. ts_wind. data_map_name: string - the name of the",
"\"\"\"Return a list of tuples of format (name, conversion function, default), e.g. ('capex',",
"str(max_data), {}) def calculate_dispatch_offer(self, period, param=None): \"\"\"Calculate the dispatch offer as the SRMC.",
"supply = self.calculate_outputs(state_handle, len(supply_request)) vble_cost, carbon, other = self.calculate_variable_costs(state_handle, site_indices, supply) return supply,",
"DEALINGS IN THE #SOFTWARE. # # \"\"\"Module for a variable generator using the",
"not provided, a 1:1 is assumed. data_ts_length: the length of the data timeseries,",
"the name of the data array holding the timeseries capacity factor data, e.g.",
"array holding the timeseries capacity factor data, e.g. ts_wind. data_map_name: string - the",
"OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"active capacity. All lists of sites below will correspond with this list. offer_price:",
"name describing the data required for this generator. \"\"\" data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name'])",
"an output string data_name: string - the name of the data array holding",
"conditions: # #The above copyright notice and this permission notice shall be included",
"site_indices \"\"\" cap_list = state_handle['capacity'] site_indices = self.get_site_indices(state_handle) num_sites = len(site_indices) output =",
"\"\"\" cap_list = state_handle['capacity'] site_indices = self.get_site_indices(state_handle) num_sites = len(site_indices) output = numpy.zeros((num_sites,",
"persons to whom the Software is #furnished to do so, subject to the",
"of tuples of format (name, conversion function, default), e.g. ('capex', float, 2.0). Put",
"if no conversion required, or if no default value, e.g. ('name', None, None)",
"len(self.config['data_map_name']) > 0: map_data = data[self.config['data_map_name']] for i in range(0, map_data.shape[0]): self.site_to_data[map_data[i, 0]]",
"to ordinal numbers. self.params_to_site = range(self.data.shape[1]) for i in range(0, self.data.shape[1]): self.site_to_data[i] =",
"None if no conversion required, or if no default value, e.g. ('name', None,",
"the data table. If this is not provided, a 1:1 is assumed. data_ts_length:",
"the data is width ' + str(self.data.shape[1]) + ' and the provided params_to_site",
"other def get_simple_desc_string(self, results, state_handle): \"\"\"Implement get_simple_desc_string as defined in TxMultiGeneratorBase, for the",
"raise mureilexception.ConfigException('In model ' + self.config['section'] + ', no data map is provided,",
"get_offers_semischeduled(self, state_handle, ts_length): \"\"\"Get offers for this semi-scheduled generator. Outputs: site_indices: the identifying",
"key name describing the data required for this generator. \"\"\" data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self)",
"params_to_site list is ' + str(len(self.params_to_site)) + ' so no automatic mapping is",
"< 0) or (data_index >= max_data): raise mureilexception.ConfigException('data_index ' + str(data_index) + '",
"data array is ' + str(max_data), {}) def calculate_dispatch_offer(self, period, param=None): \"\"\"Calculate the",
"data_name: string - the name of the data array holding the timeseries capacity",
"\"\"\"A simple implementation of a variable generator, providing per-unit capital costs. \"\"\" def",
"or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED \"AS IS\",",
"1:1. if not (len(self.params_to_site) == self.data.shape[1]): raise mureilexception.ConfigException('In model ' + self.config['section'] +",
"expensive to have self.data this way - ### would it help to transpose",
"#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the",
"an n x 2 array where n is the number of site indices",
"site indices mapped. The first in each pair is the site index and",
"state_handle, ts_length): \"\"\"Get offers for this semi-scheduled generator. Outputs: site_indices: the identifying indices",
"of site indices mapped. The first in each pair is the site index",
"range(num_sites): vble_cost[i] = numpy.sum(schedule[i,:]) * vom return vble_cost, carbon, {} def calculate_outputs_and_costs(self, state_handle,",
"software and associated documentation files (the \"Software\"), to deal #in the Software without",
"+ str(len(self.params_to_site)) + ' so no automatic mapping is possible.', {}) for i",
"to whom the Software is #furnished to do so, subject to the following",
"OTHER DEALINGS IN THE #SOFTWARE. # # \"\"\"Module for a variable generator using",
"DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"data_types.append(self.config['data_name']) if len(self.config['data_map_name']) > 0: data_types.append(self.config['data_map_name']) return data_types def set_data(self, data): \"\"\"Set the",
"other \"\"\" vom = self.period_configs[state_handle['curr_period']]['vom'] * 1e-6 num_sites = len(site_indices) vble_cost = numpy.zeros(num_sites)",
"the variable generators. \"\"\" site_indices, supply = self.calculate_outputs(state_handle, len(supply_request)) vble_cost, carbon, other =",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"the dispatch offer as the SRMC. This is the VOM for variable generators.",
"None, None), ('data_map_name', None, ''), ('data_ts_length', int, None) ] def get_data_types(self): \"\"\"Return a",
"Software is #furnished to do so, subject to the following conditions: # #The",
"and map 1:1 to this. self.params_to_site = map_data[:,0] elif len(self.params_to_site) > 0: #",
"\"\"\"Module for a variable generator using the txmultigeneratormultisite base class. \"\"\" from tools",
"Outputs: data_type: list of strings - each a key name describing the data",
"this permission notice shall be included in all #copies or substantial portions of",
"of the data array holding the timeseries capacity factor data, e.g. ts_wind. data_map_name:",
"#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY,",
"data_types.append(self.config['data_map_name']) return data_types def set_data(self, data): \"\"\"Set the data dict with the data",
"ts_length) return site_indices, offer_price, quantity def calculate_outputs(self, state_handle, ts_length): \"\"\"Calculate the maximum outputs,",
"any person obtaining a copy #of this software and associated documentation files (the",
"mapped. The first in each pair is the site index and the second",
"for the variable generator. \"\"\" return self.config['detail_type'] + ' with site capacities (MW):",
"x 2 array where n is the number of site indices mapped. The",
"the generic technology type, to report in get_details() as technology. detail_type: string -",
"supply) return supply, vble_cost, carbon, other def get_simple_desc_string(self, results, state_handle): \"\"\"Implement get_simple_desc_string as",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software,",
"TODO - it may be expensive to have self.data this way - ###",
"index list to the data 1:1. if not (len(self.params_to_site) == self.data.shape[1]): raise mureilexception.ConfigException('In",
"state_handle, supply_request, max_supply=[], price=[]): \"\"\"Implement calculate_outputs_and_costs as defined in TxMultiGeneratorBase, for the variable",
"#furnished to do so, subject to the following conditions: # #The above copyright",
"data_index in self.site_to_data.itervalues(): if (data_index < 0) or (data_index >= max_data): raise mureilexception.ConfigException('data_index",
"0: # We have a data map, but no params to site, so",
"TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple implementation of a variable generator, providing per-unit capital costs.",
"in TxMultiGeneratorBase, for the variable generator. \"\"\" return self.config['detail_type'] + ' with site",
"+ ( string.join(map('({:d}: {:.2f}) '.format, results['site_indices'], results['capacity']))) def get_full_desc_string(self, results, state_handle): \"\"\"Implement get_full_desc_string",
"map, but no params to site, so assume # all data are used",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR",
"data): \"\"\"Set the data dict with the data series required for the generator.",
"data timeseries, typically provided globally. \"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [ ('tech_type', None, 'generic_variable'),",
"carbon, {} def calculate_outputs_and_costs(self, state_handle, supply_request, max_supply=[], price=[]): \"\"\"Implement calculate_outputs_and_costs as defined in",
"num_sites = len(site_indices) output = numpy.zeros((num_sites, ts_length)) for i in range(num_sites): site =",
"an integer - the length of the timeseries Outputs: site_indices: the list of",
"implementation of a variable generator, providing per-unit capital costs. \"\"\" def get_details(self): \"\"\"Return",
"person obtaining a copy #of this software and associated documentation files (the \"Software\"),",
"the site index and the second the index into the data table. If",
"keys matching those requested by get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data = data[self.config['data_name']] self.site_to_data",
"a set of timeseries Outputs: variable_cost, carbon, other \"\"\" vom = self.period_configs[state_handle['curr_period']]['vom'] *",
"THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"self.period_configs[state_handle['curr_period']]['vom'] * 1e-6 num_sites = len(site_indices) vble_cost = numpy.zeros(num_sites) carbon = numpy.zeros(num_sites) for",
"' and the provided params_to_site list is ' + str(len(self.params_to_site)) + ' so",
"string - the name of the data array e.g. ts_wind_map which holds an",
"generator. \"\"\" data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if len(self.config['data_map_name']) > 0: data_types.append(self.config['data_map_name']) return data_types",
"vble_cost, carbon, other = self.calculate_variable_costs(state_handle, site_indices, supply) return supply, vble_cost, carbon, other def",
"within the # self.data matrix. max_data = self.data.shape[1] for data_index in self.site_to_data.itervalues(): if",
"- it may be expensive to have self.data this way - ### would",
"this list. offer_price: the offer price, one per site (interpreted as same for",
"permission notice shall be included in all #copies or substantial portions of the",
"the # self.data matrix. max_data = self.data.shape[1] for data_index in self.site_to_data.itervalues(): if (data_index",
"= txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if len(self.config['data_map_name']) > 0: data_types.append(self.config['data_map_name']) return data_types def set_data(self, data):",
"1:1 is assumed. data_ts_length: the length of the data timeseries, typically provided globally.",
"data_ts_length: the length of the data timeseries, typically provided globally. \"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self)",
"where n is the number of site indices mapped. The first in each",
"+ ' was requested by the model in section ' + self.config['section'] +",
"each site with active capacity. All lists of sites below will correspond with",
"array where n is the number of site indices mapped. The first in",
"{:.2f}) '.format, results['site_indices'], results['capacity']))) def get_full_desc_string(self, results, state_handle): \"\"\"Implement get_full_desc_string as defined in",
"of format (name, conversion function, default), e.g. ('capex', float, 2.0). Put None if",
"self.data.shape[1]): self.site_to_data[i] = i # Check that all of the values in site_to_data",
"offer_price: the offer price, one per site (interpreted as same for all timesteps)",
"is possible.', {}) for i in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] = i else: # No",
"# # # Copyright (C) University of Melbourne 2013 # # # #Permission",
"range(num_sites): site = site_indices[i] total_cap = sum([tup[0] for tup in cap_list[site]]) data_index =",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"= txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] = self.config['tech_type'] flags['dispatch'] = 'semischeduled' return flags def get_config_spec(self): \"\"\"Return",
"i in range(num_sites): site = site_indices[i] total_cap = sum([tup[0] for tup in cap_list[site]])",
"#copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED \"AS",
"the # lengths agree, map the site index list to the data 1:1.",
"the name of the data array e.g. ts_wind_map which holds an n x",
"the number of site indices mapped. The first in each pair is the",
"describing the data required for this generator. \"\"\" data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if",
"in self.site_to_data.itervalues(): if (data_index < 0) or (data_index >= max_data): raise mureilexception.ConfigException('data_index '",
"tuples of format (name, conversion function, default), e.g. ('capex', float, 2.0). Put None",
"def get_details(self): \"\"\"Return a list of flags indicating the properties of the generator.",
"def calculate_dispatch_offer(self, period, param=None): \"\"\"Calculate the dispatch offer as the SRMC. This is",
"generator. Inputs: data: dict - with keys matching those requested by get_data_types. \"\"\"",
"= 'semischeduled' return flags def get_config_spec(self): \"\"\"Return a list of tuples of format",
"lists of sites below will correspond with this list. offer_price: the offer price,",
"length of the data timeseries, typically provided globally. \"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [",
"that all of the values in site_to_data are within the # self.data matrix.",
"- the length of the timeseries Outputs: site_indices: the list of sites with",
"param=None): \"\"\"Calculate the dispatch offer as the SRMC. This is the VOM for",
"OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. # # \"\"\"Module for",
"self.data this way - ### would it help to transpose it when it's",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF",
"== self.data.shape[1]): raise mureilexception.ConfigException('In model ' + self.config['section'] + ', no data map",
"TxMultiGeneratorBase, for the variable generators. \"\"\" site_indices, supply = self.calculate_outputs(state_handle, len(supply_request)) vble_cost, carbon,",
"generator, providing per-unit capital costs. \"\"\" def get_details(self): \"\"\"Return a list of flags",
"hereby granted, free of charge, to any person obtaining a copy #of this",
"= numpy.zeros((num_sites, ts_length)) for i in range(num_sites): site = site_indices[i] total_cap = sum([tup[0]",
"map is provided, the data is width ' + str(self.data.shape[1]) + ' and",
"calculate_outputs_and_costs(self, state_handle, supply_request, max_supply=[], price=[]): \"\"\"Implement calculate_outputs_and_costs as defined in TxMultiGeneratorBase, for the",
"so, subject to the following conditions: # #The above copyright notice and this",
"quantity, one timeseries per site, in MW. \"\"\" offer_price = self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity",
"per-unit capital costs. \"\"\" def get_details(self): \"\"\"Return a list of flags indicating the",
"NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION",
"printing in an output string data_name: string - the name of the data",
"of the Software. # #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"\"\"\" data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if len(self.config['data_map_name']) > 0: data_types.append(self.config['data_map_name']) return data_types def",
"is. If the # lengths agree, map the site index list to the",
"to site, so assume # all data are used and map 1:1 to",
"conversion required, or if no default value, e.g. ('name', None, None) Configuration: as",
"Copyright (C) University of Melbourne 2013 # # # #Permission is hereby granted,",
"do so, subject to the following conditions: # #The above copyright notice and",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN",
"for a variable generator using the txmultigeneratormultisite base class. \"\"\" from tools import",
"for txmultigenerator.TxMultiGeneratorBase, plus: tech_type: string - the generic technology type, to report in",
"all of the values in site_to_data are within the # self.data matrix. max_data",
"publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons",
"numpy.zeros(num_sites) for i in range(num_sites): vble_cost[i] = numpy.sum(schedule[i,:]) * vom return vble_cost, carbon,",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS",
"if len(self.params_to_site) == 0: # We have a data map, but no params",
"limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"### would it help to transpose it when it's read in, so ###",
"+ ', no data map is provided, the data is width ' +",
"site_indices schedule: The scheduled output, a set of timeseries Outputs: variable_cost, carbon, other",
"for the generator. Inputs: data: dict - with keys matching those requested by",
"carbon, other def get_simple_desc_string(self, results, state_handle): \"\"\"Implement get_simple_desc_string as defined in TxMultiGeneratorBase, for",
"i # Check that all of the values in site_to_data are within the",
"it when it's read in, so ### the memory lines up better? output[i,:]",
"- with keys matching those requested by get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data =",
"ts_length): \"\"\"Get offers for this semi-scheduled generator. Outputs: site_indices: the identifying indices of",
"as technology. detail_type: string - a specific name, e.g. 'onshore_wind_vic', for printing in",
"' + self.config['section'] + ' but the maximum index in the data array",
"a data map, but no params to site, so assume # all data",
"return site_indices, output def calculate_variable_costs(self, state_handle, site_indices, schedule): \"\"\"Calculate variable costs and carbon",
"the length of the data timeseries, typically provided globally. \"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) +",
"which holds an n x 2 array where n is the number of",
"'generic_variable'), ('data_name', None, None), ('data_map_name', None, ''), ('data_ts_length', int, None) ] def get_data_types(self):",
"def get_config_spec(self): \"\"\"Return a list of tuples of format (name, conversion function, default),",
"class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple implementation of a variable generator, providing per-unit capital",
"range(self.data.shape[1]) for i in range(0, self.data.shape[1]): self.site_to_data[i] = i # Check that all",
"period, param=None): \"\"\"Calculate the dispatch offer as the SRMC. This is the VOM",
"in range(num_sites): site = site_indices[i] total_cap = sum([tup[0] for tup in cap_list[site]]) data_index",
"the variable generator. \"\"\" return self.config['detail_type'] + ' with site capacities (MW): '",
"self.params_to_site = range(self.data.shape[1]) for i in range(0, self.data.shape[1]): self.site_to_data[i] = i # Check",
"schedule): \"\"\"Calculate variable costs and carbon based on schedule. Inputs: state_handle site_indices schedule:",
"sites with active capacity output: a set of timeseries, corresponding to site_indices \"\"\"",
"files (the \"Software\"), to deal #in the Software without restriction, including without limitation",
"return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [ ('tech_type', None, 'generic_variable'), ('detail_type', None, 'generic_variable'), ('data_name', None, None),",
"= map_data[:,0] elif len(self.params_to_site) > 0: # No data map is provided, but",
"= numpy.zeros(num_sites) for i in range(num_sites): vble_cost[i] = numpy.sum(schedule[i,:]) * vom return vble_cost,",
"# # # #Permission is hereby granted, free of charge, to any person",
"(the \"Software\"), to deal #in the Software without restriction, including without limitation the",
"from tools import configurablebase, mureilexception from generator import txmultigeneratormultisite from master import interfacesflowmaster",
"pair is the site index and the second the index into the data",
"so assume # all data are used and map 1:1 to this. self.params_to_site",
"when it's read in, so ### the memory lines up better? output[i,:] =",
"= self.data.shape[1] for data_index in self.site_to_data.itervalues(): if (data_index < 0) or (data_index >=",
"index into the data table. If this is not provided, a 1:1 is",
"1:1 to this. self.params_to_site = map_data[:,0] elif len(self.params_to_site) > 0: # No data",
"the maximum outputs, before scheduling. Inputs: state_handle ts_length: an integer - the length",
"<filename>generator/txmultivariablegenerator.py # # # Copyright (C) University of Melbourne 2013 # # #",
"data series required for the generator. Inputs: data: dict - with keys matching",
"txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data = data[self.config['data_name']] self.site_to_data = {} if len(self.config['data_map_name']) > 0: map_data",
"one per site (interpreted as same for all timesteps) quantity: the offer quantity,",
"active capacity output: a set of timeseries, corresponding to site_indices \"\"\" cap_list =",
"is #furnished to do so, subject to the following conditions: # #The above",
"#Permission is hereby granted, free of charge, to any person obtaining a copy",
"permit persons to whom the Software is #furnished to do so, subject to",
"+ self.config['section'] + ' but the maximum index in the data array is",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED,",
"no conversion required, or if no default value, e.g. ('name', None, None) Configuration:",
"max_supply=[], price=[]): \"\"\"Implement calculate_outputs_and_costs as defined in TxMultiGeneratorBase, for the variable generators. \"\"\"",
"the Software is #furnished to do so, subject to the following conditions: #",
"'.format, results['site_indices'], results['capacity']))) def get_full_desc_string(self, results, state_handle): \"\"\"Implement get_full_desc_string as defined in TxMultiGeneratorBase,",
"in get_details() as technology. detail_type: string - a specific name, e.g. 'onshore_wind_vic', for",
"provided, a 1:1 is assumed. data_ts_length: the length of the data timeseries, typically",
"a specific name, e.g. 'onshore_wind_vic', for printing in an output string data_name: string",
"without restriction, including without limitation the rights #to use, copy, modify, merge, publish,",
"plus: tech_type: string - the generic technology type, to report in get_details() as",
"get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data = data[self.config['data_name']] self.site_to_data = {} if len(self.config['data_map_name']) >",
"+ ' but the maximum index in the data array is ' +",
"All lists of sites below will correspond with this list. offer_price: the offer",
"EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS",
"state_handle ts_length: an integer - the length of the timeseries Outputs: site_indices: the",
"+ ' and the provided params_to_site list is ' + str(len(self.params_to_site)) + '",
"rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of",
"name of the data array e.g. ts_wind_map which holds an n x 2",
"for all timesteps) quantity: the offer quantity, one timeseries per site, in MW.",
"based on schedule. Inputs: state_handle site_indices schedule: The scheduled output, a set of",
"= {} if len(self.config['data_map_name']) > 0: map_data = data[self.config['data_map_name']] for i in range(0,",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND",
"generators. \"\"\" site_indices, supply = self.calculate_outputs(state_handle, len(supply_request)) vble_cost, carbon, other = self.calculate_variable_costs(state_handle, site_indices,",
"offer_price = self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity = self.calculate_outputs(state_handle, ts_length) return site_indices, offer_price, quantity def",
"copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and",
"len(site_indices) output = numpy.zeros((num_sites, ts_length)) for i in range(num_sites): site = site_indices[i] total_cap",
"section ' + self.config['section'] + ' but the maximum index in the data",
"to this. self.params_to_site = map_data[:,0] elif len(self.params_to_site) > 0: # No data map",
"= self.calculate_outputs(state_handle, ts_length) return site_indices, offer_price, quantity def calculate_outputs(self, state_handle, ts_length): \"\"\"Calculate the",
"\"\"\"Calculate variable costs and carbon based on schedule. Inputs: state_handle site_indices schedule: The",
"matching those requested by get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data = data[self.config['data_name']] self.site_to_data =",
"the site index list to the data 1:1. if not (len(self.params_to_site) == self.data.shape[1]):",
"The first in each pair is the site index and the second the",
"Put None if no conversion required, or if no default value, e.g. ('name',",
"first in each pair is the site index and the second the index",
"globally. \"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [ ('tech_type', None, 'generic_variable'), ('detail_type', None, 'generic_variable'), ('data_name',",
"each a key name describing the data required for this generator. \"\"\" data_types",
"import numpy import string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple implementation of a variable",
"flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] = self.config['tech_type'] flags['dispatch'] = 'semischeduled' return flags def get_config_spec(self):",
"\"\"\" from tools import configurablebase, mureilexception from generator import txmultigeneratormultisite from master import",
"e.g. 'onshore_wind_vic', for printing in an output string data_name: string - the name",
"' + self.config['section'] + ', no data map is provided, the data is",
"schedule. Inputs: state_handle site_indices schedule: The scheduled output, a set of timeseries Outputs:",
"#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A",
"float, 2.0). Put None if no conversion required, or if no default value,",
"None, ''), ('data_ts_length', int, None) ] def get_data_types(self): \"\"\"Return a list of keys",
"= len(site_indices) output = numpy.zeros((num_sites, ts_length)) for i in range(num_sites): site = site_indices[i]",
"' + ( string.join(map('({:d}: {:.2f}) '.format, results['site_indices'], results['capacity']))) def get_full_desc_string(self, results, state_handle): \"\"\"Implement",
"map 1:1 to this. self.params_to_site = map_data[:,0] elif len(self.params_to_site) > 0: # No",
"= range(self.data.shape[1]) for i in range(0, self.data.shape[1]): self.site_to_data[i] = i # Check that",
"state_handle['capacity'] site_indices = self.get_site_indices(state_handle) num_sites = len(site_indices) output = numpy.zeros((num_sites, ts_length)) for i",
"site_indices, supply = self.calculate_outputs(state_handle, len(supply_request)) vble_cost, carbon, other = self.calculate_variable_costs(state_handle, site_indices, supply) return",
"default), e.g. ('capex', float, 2.0). Put None if no conversion required, or if",
"state_handle): \"\"\"Implement get_full_desc_string as defined in TxMultiGeneratorBase, for the variable generator. \"\"\" return",
"' was requested by the model in section ' + self.config['section'] + '",
"\"\"\"Implement get_full_desc_string as defined in TxMultiGeneratorBase, for the variable generator. \"\"\" return self.get_simple_desc_string(results,",
"including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense,",
"- a specific name, e.g. 'onshore_wind_vic', for printing in an output string data_name:",
"self.data.shape[1] for data_index in self.site_to_data.itervalues(): if (data_index < 0) or (data_index >= max_data):",
"interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple implementation of a variable generator, providing per-unit capital costs. \"\"\"",
"\"\"\"Return a list of keys for each type of data required, for example",
"the data series required for the generator. Inputs: data: dict - with keys",
"in range(num_sites): vble_cost[i] = numpy.sum(schedule[i,:]) * vom return vble_cost, carbon, {} def calculate_outputs_and_costs(self,",
"return vble_cost, carbon, {} def calculate_outputs_and_costs(self, state_handle, supply_request, max_supply=[], price=[]): \"\"\"Implement calculate_outputs_and_costs as",
"('tech_type', None, 'generic_variable'), ('detail_type', None, 'generic_variable'), ('data_name', None, None), ('data_map_name', None, ''), ('data_ts_length',",
"OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"vble_cost[i] = numpy.sum(schedule[i,:]) * vom return vble_cost, carbon, {} def calculate_outputs_and_costs(self, state_handle, supply_request,",
"for this generator. \"\"\" data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if len(self.config['data_map_name']) > 0: data_types.append(self.config['data_map_name'])",
"cap_list = state_handle['capacity'] site_indices = self.get_site_indices(state_handle) num_sites = len(site_indices) output = numpy.zeros((num_sites, ts_length))",
"ts_wind, ts_demand. Outputs: data_type: list of strings - each a key name describing",
"the index into the data table. If this is not provided, a 1:1",
"self.period_configs[period]['vom'] def get_offers_semischeduled(self, state_handle, ts_length): \"\"\"Get offers for this semi-scheduled generator. Outputs: site_indices:",
"associated documentation files (the \"Software\"), to deal #in the Software without restriction, including",
"variable generator, providing per-unit capital costs. \"\"\" def get_details(self): \"\"\"Return a list of",
"txmultigeneratormultisite base class. \"\"\" from tools import configurablebase, mureilexception from generator import txmultigeneratormultisite",
"> 0: # No data map is provided, but params_to_site is. If the",
"(interpreted as same for all timesteps) quantity: the offer quantity, one timeseries per",
"# all data are used and map 1:1 to this. self.params_to_site = map_data[:,0]",
"list of keys for each type of data required, for example ts_wind, ts_demand.",
"sum([tup[0] for tup in cap_list[site]]) data_index = self.site_to_data[site] ### TODO - it may",
"all timesteps) quantity: the offer quantity, one timeseries per site, in MW. \"\"\"",
"correspond with this list. offer_price: the offer price, one per site (interpreted as",
"MW. \"\"\" offer_price = self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity = self.calculate_outputs(state_handle, ts_length) return site_indices, offer_price,",
"this. self.params_to_site = map_data[:,0] elif len(self.params_to_site) > 0: # No data map is",
"state_handle): \"\"\"Implement get_simple_desc_string as defined in TxMultiGeneratorBase, for the variable generator. \"\"\" return",
"University of Melbourne 2013 # # # #Permission is hereby granted, free of",
"= state_handle['capacity'] site_indices = self.get_site_indices(state_handle) num_sites = len(site_indices) output = numpy.zeros((num_sites, ts_length)) for",
"0: data_types.append(self.config['data_map_name']) return data_types def set_data(self, data): \"\"\"Set the data dict with the",
"#SOFTWARE. # # \"\"\"Module for a variable generator using the txmultigeneratormultisite base class.",
"e.g. ('name', None, None) Configuration: as for txmultigenerator.TxMultiGeneratorBase, plus: tech_type: string - the",
"None) ] def get_data_types(self): \"\"\"Return a list of keys for each type of",
"(data_index < 0) or (data_index >= max_data): raise mureilexception.ConfigException('data_index ' + str(data_index) +",
"# self.data matrix. max_data = self.data.shape[1] for data_index in self.site_to_data.itervalues(): if (data_index <",
"mureilexception.ConfigException('data_index ' + str(data_index) + ' was requested by the model in section",
"for i in range(num_sites): site = site_indices[i] total_cap = sum([tup[0] for tup in",
"of timeseries Outputs: variable_cost, carbon, other \"\"\" vom = self.period_configs[state_handle['curr_period']]['vom'] * 1e-6 num_sites",
"1e-6 num_sites = len(site_indices) vble_cost = numpy.zeros(num_sites) carbon = numpy.zeros(num_sites) for i in",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR",
"(C) University of Melbourne 2013 # # # #Permission is hereby granted, free",
"ts_length): \"\"\"Calculate the maximum outputs, before scheduling. Inputs: state_handle ts_length: an integer -",
"of flags indicating the properties of the generator. \"\"\" flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology']",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING",
"required, for example ts_wind, ts_demand. Outputs: data_type: list of strings - each a",
"offer as the SRMC. This is the VOM for variable generators. \"\"\" return",
"tup in cap_list[site]]) data_index = self.site_to_data[site] ### TODO - it may be expensive",
"generator using the txmultigeneratormultisite base class. \"\"\" from tools import configurablebase, mureilexception from",
"string - a specific name, e.g. 'onshore_wind_vic', for printing in an output string",
"data_index = self.site_to_data[site] ### TODO - it may be expensive to have self.data",
"import txmultigeneratormultisite from master import interfacesflowmaster import copy import numpy import string class",
"technology. detail_type: string - a specific name, e.g. 'onshore_wind_vic', for printing in an",
"results['capacity']))) def get_full_desc_string(self, results, state_handle): \"\"\"Implement get_full_desc_string as defined in TxMultiGeneratorBase, for the",
"obtaining a copy #of this software and associated documentation files (the \"Software\"), to",
"#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS",
"list of sites is provided. Just map to ordinal numbers. self.params_to_site = range(self.data.shape[1])",
"capital costs. \"\"\" def get_details(self): \"\"\"Return a list of flags indicating the properties",
"mureilexception.ConfigException('In model ' + self.config['section'] + ', no data map is provided, the",
"as defined in TxMultiGeneratorBase, for the variable generator. \"\"\" return self.config['detail_type'] + '",
"None) Configuration: as for txmultigenerator.TxMultiGeneratorBase, plus: tech_type: string - the generic technology type,",
"self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity = self.calculate_outputs(state_handle, ts_length) return site_indices, offer_price, quantity def calculate_outputs(self, state_handle,",
"] def get_data_types(self): \"\"\"Return a list of keys for each type of data",
"# No list of sites is provided. Just map to ordinal numbers. self.params_to_site",
"state_handle site_indices schedule: The scheduled output, a set of timeseries Outputs: variable_cost, carbon,",
"timesteps) quantity: the offer quantity, one timeseries per site, in MW. \"\"\" offer_price",
"sell #copies of the Software, and to permit persons to whom the Software",
"None, None) Configuration: as for txmultigenerator.TxMultiGeneratorBase, plus: tech_type: string - the generic technology",
"import copy import numpy import string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple implementation of",
"list of strings - each a key name describing the data required for",
"int, None) ] def get_data_types(self): \"\"\"Return a list of keys for each type",
"total_cap return site_indices, output def calculate_variable_costs(self, state_handle, site_indices, schedule): \"\"\"Calculate variable costs and",
"master import interfacesflowmaster import copy import numpy import string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A",
"output string data_name: string - the name of the data array holding the",
"This is the VOM for variable generators. \"\"\" return self.period_configs[period]['vom'] def get_offers_semischeduled(self, state_handle,",
"the provided params_to_site list is ' + str(len(self.params_to_site)) + ' so no automatic",
"scheduled output, a set of timeseries Outputs: variable_cost, carbon, other \"\"\" vom =",
"\"\"\" return self.config['detail_type'] + ' with site capacities (MW): ' + ( string.join(map('({:d}:",
"map_data = data[self.config['data_map_name']] for i in range(0, map_data.shape[0]): self.site_to_data[map_data[i, 0]] = map_data[i, 1]",
"numpy.zeros((num_sites, ts_length)) for i in range(num_sites): site = site_indices[i] total_cap = sum([tup[0] for",
"but params_to_site is. If the # lengths agree, map the site index list",
"' + str(max_data), {}) def calculate_dispatch_offer(self, period, param=None): \"\"\"Calculate the dispatch offer as",
"get_details() as technology. detail_type: string - a specific name, e.g. 'onshore_wind_vic', for printing",
"get_full_desc_string(self, results, state_handle): \"\"\"Implement get_full_desc_string as defined in TxMultiGeneratorBase, for the variable generator.",
"the offer price, one per site (interpreted as same for all timesteps) quantity:",
"no data map is provided, the data is width ' + str(self.data.shape[1]) +",
"the data timeseries, typically provided globally. \"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [ ('tech_type', None,",
"of timeseries, corresponding to site_indices \"\"\" cap_list = state_handle['capacity'] site_indices = self.get_site_indices(state_handle) num_sites",
"numpy.sum(schedule[i,:]) * vom return vble_cost, carbon, {} def calculate_outputs_and_costs(self, state_handle, supply_request, max_supply=[], price=[]):",
"str(len(self.params_to_site)) + ' so no automatic mapping is possible.', {}) for i in",
"map the site index list to the data 1:1. if not (len(self.params_to_site) ==",
"import string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple implementation of a variable generator, providing",
"to transpose it when it's read in, so ### the memory lines up",
"subject to the following conditions: # #The above copyright notice and this permission",
"dict with the data series required for the generator. Inputs: data: dict -",
"corresponding to site_indices \"\"\" cap_list = state_handle['capacity'] site_indices = self.get_site_indices(state_handle) num_sites = len(site_indices)",
"for i in range(0, self.data.shape[1]): self.site_to_data[i] = i # Check that all of",
"on schedule. Inputs: state_handle site_indices schedule: The scheduled output, a set of timeseries",
"> 0: map_data = data[self.config['data_map_name']] for i in range(0, map_data.shape[0]): self.site_to_data[map_data[i, 0]] =",
"with site capacities (MW): ' + ( string.join(map('({:d}: {:.2f}) '.format, results['site_indices'], results['capacity']))) def",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"is not provided, a 1:1 is assumed. data_ts_length: the length of the data",
"1] if len(self.params_to_site) == 0: # We have a data map, but no",
"as for txmultigenerator.TxMultiGeneratorBase, plus: tech_type: string - the generic technology type, to report",
"' + str(self.data.shape[1]) + ' and the provided params_to_site list is ' +",
"the model in section ' + self.config['section'] + ' but the maximum index",
"TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"by get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data = data[self.config['data_name']] self.site_to_data = {} if len(self.config['data_map_name'])",
"{}) def calculate_dispatch_offer(self, period, param=None): \"\"\"Calculate the dispatch offer as the SRMC. This",
"return self.config['detail_type'] + ' with site capacities (MW): ' + ( string.join(map('({:d}: {:.2f})",
"so ### the memory lines up better? output[i,:] = self.data[:,data_index] * total_cap return",
"class. \"\"\" from tools import configurablebase, mureilexception from generator import txmultigeneratormultisite from master",
"in range(0, map_data.shape[0]): self.site_to_data[map_data[i, 0]] = map_data[i, 1] if len(self.params_to_site) == 0: #",
"index in the data array is ' + str(max_data), {}) def calculate_dispatch_offer(self, period,",
"site (interpreted as same for all timesteps) quantity: the offer quantity, one timeseries",
"using the txmultigeneratormultisite base class. \"\"\" from tools import configurablebase, mureilexception from generator",
"str(data_index) + ' was requested by the model in section ' + self.config['section']",
"Inputs: state_handle ts_length: an integer - the length of the timeseries Outputs: site_indices:",
"are within the # self.data matrix. max_data = self.data.shape[1] for data_index in self.site_to_data.itervalues():",
"the offer quantity, one timeseries per site, in MW. \"\"\" offer_price = self.calculate_dispatch_offer(state_handle['curr_period'])",
"import interfacesflowmaster import copy import numpy import string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple",
"('data_map_name', None, ''), ('data_ts_length', int, None) ] def get_data_types(self): \"\"\"Return a list of",
"e.g. ('capex', float, 2.0). Put None if no conversion required, or if no",
"in each pair is the site index and the second the index into",
"for variable generators. \"\"\" return self.period_configs[period]['vom'] def get_offers_semischeduled(self, state_handle, ts_length): \"\"\"Get offers for",
"site_indices, output def calculate_variable_costs(self, state_handle, site_indices, schedule): \"\"\"Calculate variable costs and carbon based",
"string.join(map('({:d}: {:.2f}) '.format, results['site_indices'], results['capacity']))) def get_full_desc_string(self, results, state_handle): \"\"\"Implement get_full_desc_string as defined",
"the second the index into the data table. If this is not provided,",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT",
"WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"requested by the model in section ' + self.config['section'] + ' but the",
"quantity: the offer quantity, one timeseries per site, in MW. \"\"\" offer_price =",
"be expensive to have self.data this way - ### would it help to",
"offers for this semi-scheduled generator. Outputs: site_indices: the identifying indices of each site",
"= self.data[:,data_index] * total_cap return site_indices, output def calculate_variable_costs(self, state_handle, site_indices, schedule): \"\"\"Calculate",
"USE OR OTHER DEALINGS IN THE #SOFTWARE. # # \"\"\"Module for a variable",
"params to site, so assume # all data are used and map 1:1",
"to do so, subject to the following conditions: # #The above copyright notice",
"have a data map, but no params to site, so assume # all",
"whom the Software is #furnished to do so, subject to the following conditions:",
"documentation files (the \"Software\"), to deal #in the Software without restriction, including without",
"agree, map the site index list to the data 1:1. if not (len(self.params_to_site)",
"If the # lengths agree, map the site index list to the data",
"is ' + str(len(self.params_to_site)) + ' so no automatic mapping is possible.', {})",
"2013 # # # #Permission is hereby granted, free of charge, to any",
"params_to_site is. If the # lengths agree, map the site index list to",
"+ self.config['section'] + ', no data map is provided, the data is width",
"get_simple_desc_string(self, results, state_handle): \"\"\"Implement get_simple_desc_string as defined in TxMultiGeneratorBase, for the variable generator.",
"model in section ' + self.config['section'] + ' but the maximum index in",
"of strings - each a key name describing the data required for this",
"total_cap = sum([tup[0] for tup in cap_list[site]]) data_index = self.site_to_data[site] ### TODO -",
"default value, e.g. ('name', None, None) Configuration: as for txmultigenerator.TxMultiGeneratorBase, plus: tech_type: string",
"site = site_indices[i] total_cap = sum([tup[0] for tup in cap_list[site]]) data_index = self.site_to_data[site]",
"# # \"\"\"Module for a variable generator using the txmultigeneratormultisite base class. \"\"\"",
"self.get_site_indices(state_handle) num_sites = len(site_indices) output = numpy.zeros((num_sites, ts_length)) for i in range(num_sites): site",
"the data array holding the timeseries capacity factor data, e.g. ts_wind. data_map_name: string",
"as the SRMC. This is the VOM for variable generators. \"\"\" return self.period_configs[period]['vom']",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF",
"width ' + str(self.data.shape[1]) + ' and the provided params_to_site list is '",
"sites is provided. Just map to ordinal numbers. self.params_to_site = range(self.data.shape[1]) for i",
"to have self.data this way - ### would it help to transpose it",
"VOM for variable generators. \"\"\" return self.period_configs[period]['vom'] def get_offers_semischeduled(self, state_handle, ts_length): \"\"\"Get offers",
"timeseries Outputs: site_indices: the list of sites with active capacity output: a set",
"', no data map is provided, the data is width ' + str(self.data.shape[1])",
"self.site_to_data[i] = i # Check that all of the values in site_to_data are",
"for data_index in self.site_to_data.itervalues(): if (data_index < 0) or (data_index >= max_data): raise",
"in the data array is ' + str(max_data), {}) def calculate_dispatch_offer(self, period, param=None):",
"\"\"\"Implement get_simple_desc_string as defined in TxMultiGeneratorBase, for the variable generator. \"\"\" return self.config['detail_type']",
"+ [ ('tech_type', None, 'generic_variable'), ('detail_type', None, 'generic_variable'), ('data_name', None, None), ('data_map_name', None,",
"string - the name of the data array holding the timeseries capacity factor",
"ts_length: an integer - the length of the timeseries Outputs: site_indices: the list",
"TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"generic technology type, to report in get_details() as technology. detail_type: string - a",
"no automatic mapping is possible.', {}) for i in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] = i",
"carbon, other = self.calculate_variable_costs(state_handle, site_indices, supply) return supply, vble_cost, carbon, other def get_simple_desc_string(self,",
"assumed. data_ts_length: the length of the data timeseries, typically provided globally. \"\"\" return",
"each type of data required, for example ts_wind, ts_demand. Outputs: data_type: list of",
"is provided. Just map to ordinal numbers. self.params_to_site = range(self.data.shape[1]) for i in",
"output def calculate_variable_costs(self, state_handle, site_indices, schedule): \"\"\"Calculate variable costs and carbon based on",
"for the variable generators. \"\"\" site_indices, supply = self.calculate_outputs(state_handle, len(supply_request)) vble_cost, carbon, other",
"Inputs: state_handle site_indices schedule: The scheduled output, a set of timeseries Outputs: variable_cost,",
"ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"provided, but params_to_site is. If the # lengths agree, map the site index",
"quantity def calculate_outputs(self, state_handle, ts_length): \"\"\"Calculate the maximum outputs, before scheduling. Inputs: state_handle",
"return site_indices, offer_price, quantity def calculate_outputs(self, state_handle, ts_length): \"\"\"Calculate the maximum outputs, before",
"Outputs: site_indices: the identifying indices of each site with active capacity. All lists",
"provided, the data is width ' + str(self.data.shape[1]) + ' and the provided",
"site with active capacity. All lists of sites below will correspond with this",
"model ' + self.config['section'] + ', no data map is provided, the data",
"ts_wind. data_map_name: string - the name of the data array e.g. ts_wind_map which",
"return flags def get_config_spec(self): \"\"\"Return a list of tuples of format (name, conversion",
"KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"'generic_variable'), ('detail_type', None, 'generic_variable'), ('data_name', None, None), ('data_map_name', None, ''), ('data_ts_length', int, None)",
"raise mureilexception.ConfigException('data_index ' + str(data_index) + ' was requested by the model in",
"a list of tuples of format (name, conversion function, default), e.g. ('capex', float,",
"( string.join(map('({:d}: {:.2f}) '.format, results['site_indices'], results['capacity']))) def get_full_desc_string(self, results, state_handle): \"\"\"Implement get_full_desc_string as",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT",
"for each type of data required, for example ts_wind, ts_demand. Outputs: data_type: list",
"2.0). Put None if no conversion required, or if no default value, e.g.",
"#of this software and associated documentation files (the \"Software\"), to deal #in the",
"of the data array e.g. ts_wind_map which holds an n x 2 array",
"the length of the timeseries Outputs: site_indices: the list of sites with active",
"results, state_handle): \"\"\"Implement get_simple_desc_string as defined in TxMultiGeneratorBase, for the variable generator. \"\"\"",
"Software without restriction, including without limitation the rights #to use, copy, modify, merge,",
"i in range(0, self.data.shape[1]): self.site_to_data[i] = i # Check that all of the",
"of each site with active capacity. All lists of sites below will correspond",
"and the second the index into the data table. If this is not",
"data array holding the timeseries capacity factor data, e.g. ts_wind. data_map_name: string -",
"variable generator using the txmultigeneratormultisite base class. \"\"\" from tools import configurablebase, mureilexception",
"sublicense, and/or sell #copies of the Software, and to permit persons to whom",
"range(0, map_data.shape[0]): self.site_to_data[map_data[i, 0]] = map_data[i, 1] if len(self.params_to_site) == 0: # We",
"list to the data 1:1. if not (len(self.params_to_site) == self.data.shape[1]): raise mureilexception.ConfigException('In model",
"is provided, the data is width ' + str(self.data.shape[1]) + ' and the",
"for tup in cap_list[site]]) data_index = self.site_to_data[site] ### TODO - it may be",
"get_simple_desc_string as defined in TxMultiGeneratorBase, for the variable generator. \"\"\" return self.config['detail_type'] +",
"and the provided params_to_site list is ' + str(len(self.params_to_site)) + ' so no",
"self.data matrix. max_data = self.data.shape[1] for data_index in self.site_to_data.itervalues(): if (data_index < 0)",
"vble_cost, carbon, {} def calculate_outputs_and_costs(self, state_handle, supply_request, max_supply=[], price=[]): \"\"\"Implement calculate_outputs_and_costs as defined",
"get_details(self): \"\"\"Return a list of flags indicating the properties of the generator. \"\"\"",
"return supply, vble_cost, carbon, other def get_simple_desc_string(self, results, state_handle): \"\"\"Implement get_simple_desc_string as defined",
"strings - each a key name describing the data required for this generator.",
"holds an n x 2 array where n is the number of site",
"to the data 1:1. if not (len(self.params_to_site) == self.data.shape[1]): raise mureilexception.ConfigException('In model '",
"data 1:1. if not (len(self.params_to_site) == self.data.shape[1]): raise mureilexception.ConfigException('In model ' + self.config['section']",
"str(self.data.shape[1]) + ' and the provided params_to_site list is ' + str(len(self.params_to_site)) +",
"help to transpose it when it's read in, so ### the memory lines",
"WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"\"\"\"Get offers for this semi-scheduled generator. Outputs: site_indices: the identifying indices of each",
"provided globally. \"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [ ('tech_type', None, 'generic_variable'), ('detail_type', None, 'generic_variable'),",
"range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] = i else: # No list of sites is provided. Just",
"('data_ts_length', int, None) ] def get_data_types(self): \"\"\"Return a list of keys for each",
"interfacesflowmaster import copy import numpy import string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite, interfacesflowmaster.InterfaceSemiScheduledDispatch): \"\"\"A simple implementation",
"the data array is ' + str(max_data), {}) def calculate_dispatch_offer(self, period, param=None): \"\"\"Calculate",
"with active capacity. All lists of sites below will correspond with this list.",
"def calculate_variable_costs(self, state_handle, site_indices, schedule): \"\"\"Calculate variable costs and carbon based on schedule.",
"{}) for i in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] = i else: # No list of",
"{} def calculate_outputs_and_costs(self, state_handle, supply_request, max_supply=[], price=[]): \"\"\"Implement calculate_outputs_and_costs as defined in TxMultiGeneratorBase,",
"as same for all timesteps) quantity: the offer quantity, one timeseries per site,",
"report in get_details() as technology. detail_type: string - a specific name, e.g. 'onshore_wind_vic',",
"data required, for example ts_wind, ts_demand. Outputs: data_type: list of strings - each",
"as defined in TxMultiGeneratorBase, for the variable generators. \"\"\" site_indices, supply = self.calculate_outputs(state_handle,",
"type, to report in get_details() as technology. detail_type: string - a specific name,",
"calculate_variable_costs(self, state_handle, site_indices, schedule): \"\"\"Calculate variable costs and carbon based on schedule. Inputs:",
"txmultigeneratormultisite from master import interfacesflowmaster import copy import numpy import string class TxMultiVariableGeneratorBase(txmultigeneratormultisite.TxMultiGeneratorMultiSite,",
"indices mapped. The first in each pair is the site index and the",
"matrix. max_data = self.data.shape[1] for data_index in self.site_to_data.itervalues(): if (data_index < 0) or",
"'onshore_wind_vic', for printing in an output string data_name: string - the name of",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH",
"\"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data = data[self.config['data_name']] self.site_to_data = {} if len(self.config['data_map_name']) > 0:",
"# Check that all of the values in site_to_data are within the #",
"or (data_index >= max_data): raise mureilexception.ConfigException('data_index ' + str(data_index) + ' was requested",
"state_handle, site_indices, schedule): \"\"\"Calculate variable costs and carbon based on schedule. Inputs: state_handle",
"detail_type: string - a specific name, e.g. 'onshore_wind_vic', for printing in an output",
"flags['dispatch'] = 'semischeduled' return flags def get_config_spec(self): \"\"\"Return a list of tuples of",
"range(0, self.data.shape[1]): self.site_to_data[i] = i # Check that all of the values in",
"are used and map 1:1 to this. self.params_to_site = map_data[:,0] elif len(self.params_to_site) >",
"free of charge, to any person obtaining a copy #of this software and",
"set of timeseries, corresponding to site_indices \"\"\" cap_list = state_handle['capacity'] site_indices = self.get_site_indices(state_handle)",
"string data_name: string - the name of the data array holding the timeseries",
"# #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"map_data[i, 1] if len(self.params_to_site) == 0: # We have a data map, but",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN",
"provided params_to_site list is ' + str(len(self.params_to_site)) + ' so no automatic mapping",
"variable generators. \"\"\" return self.period_configs[period]['vom'] def get_offers_semischeduled(self, state_handle, ts_length): \"\"\"Get offers for this",
"with this list. offer_price: the offer price, one per site (interpreted as same",
"quantity = self.calculate_outputs(state_handle, ts_length) return site_indices, offer_price, quantity def calculate_outputs(self, state_handle, ts_length): \"\"\"Calculate",
"flags indicating the properties of the generator. \"\"\" flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] =",
"def get_offers_semischeduled(self, state_handle, ts_length): \"\"\"Get offers for this semi-scheduled generator. Outputs: site_indices: the",
"the timeseries capacity factor data, e.g. ts_wind. data_map_name: string - the name of",
"a list of flags indicating the properties of the generator. \"\"\" flags =",
"semi-scheduled generator. Outputs: site_indices: the identifying indices of each site with active capacity.",
"deal #in the Software without restriction, including without limitation the rights #to use,",
"included in all #copies or substantial portions of the Software. # #THE SOFTWARE",
"by the model in section ' + self.config['section'] + ' but the maximum",
"None), ('data_map_name', None, ''), ('data_ts_length', int, None) ] def get_data_types(self): \"\"\"Return a list",
"data_map_name: string - the name of the data array e.g. ts_wind_map which holds",
"better? output[i,:] = self.data[:,data_index] * total_cap return site_indices, output def calculate_variable_costs(self, state_handle, site_indices,",
"EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"# # #Permission is hereby granted, free of charge, to any person obtaining",
"list of flags indicating the properties of the generator. \"\"\" flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self)",
"# #Permission is hereby granted, free of charge, to any person obtaining a",
"is the VOM for variable generators. \"\"\" return self.period_configs[period]['vom'] def get_offers_semischeduled(self, state_handle, ts_length):",
"is assumed. data_ts_length: the length of the data timeseries, typically provided globally. \"\"\"",
"mapping is possible.', {}) for i in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] = i else: #",
"required, or if no default value, e.g. ('name', None, None) Configuration: as for",
"THE USE OR OTHER DEALINGS IN THE #SOFTWARE. # # \"\"\"Module for a",
"value, e.g. ('name', None, None) Configuration: as for txmultigenerator.TxMultiGeneratorBase, plus: tech_type: string -",
"for example ts_wind, ts_demand. Outputs: data_type: list of strings - each a key",
"array e.g. ts_wind_map which holds an n x 2 array where n is",
"site_to_data are within the # self.data matrix. max_data = self.data.shape[1] for data_index in",
"of keys for each type of data required, for example ts_wind, ts_demand. Outputs:",
"for this semi-scheduled generator. Outputs: site_indices: the identifying indices of each site with",
"return data_types def set_data(self, data): \"\"\"Set the data dict with the data series",
"If this is not provided, a 1:1 is assumed. data_ts_length: the length of",
"all #copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED",
"before scheduling. Inputs: state_handle ts_length: an integer - the length of the timeseries",
"generator. \"\"\" return self.config['detail_type'] + ' with site capacities (MW): ' + (",
"from generator import txmultigeneratormultisite from master import interfacesflowmaster import copy import numpy import",
"the txmultigeneratormultisite base class. \"\"\" from tools import configurablebase, mureilexception from generator import",
"('capex', float, 2.0). Put None if no conversion required, or if no default",
"the following conditions: # #The above copyright notice and this permission notice shall",
"set of timeseries Outputs: variable_cost, carbon, other \"\"\" vom = self.period_configs[state_handle['curr_period']]['vom'] * 1e-6",
"it help to transpose it when it's read in, so ### the memory",
"conversion function, default), e.g. ('capex', float, 2.0). Put None if no conversion required,",
"series required for the generator. Inputs: data: dict - with keys matching those",
"0: # No data map is provided, but params_to_site is. If the #",
"copy #of this software and associated documentation files (the \"Software\"), to deal #in",
"(name, conversion function, default), e.g. ('capex', float, 2.0). Put None if no conversion",
"self.config['section'] + ', no data map is provided, the data is width '",
"('data_name', None, None), ('data_map_name', None, ''), ('data_ts_length', int, None) ] def get_data_types(self): \"\"\"Return",
"to site_indices \"\"\" cap_list = state_handle['capacity'] site_indices = self.get_site_indices(state_handle) num_sites = len(site_indices) output",
"(MW): ' + ( string.join(map('({:d}: {:.2f}) '.format, results['site_indices'], results['capacity']))) def get_full_desc_string(self, results, state_handle):",
"data dict with the data series required for the generator. Inputs: data: dict",
"[ ('tech_type', None, 'generic_variable'), ('detail_type', None, 'generic_variable'), ('data_name', None, None), ('data_map_name', None, ''),",
"and carbon based on schedule. Inputs: state_handle site_indices schedule: The scheduled output, a",
"\"\"\"Implement calculate_outputs_and_costs as defined in TxMultiGeneratorBase, for the variable generators. \"\"\" site_indices, supply",
"so no automatic mapping is possible.', {}) for i in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] =",
"We have a data map, but no params to site, so assume #",
"state_handle, ts_length): \"\"\"Calculate the maximum outputs, before scheduling. Inputs: state_handle ts_length: an integer",
"timeseries Outputs: variable_cost, carbon, other \"\"\" vom = self.period_configs[state_handle['curr_period']]['vom'] * 1e-6 num_sites =",
"site_indices, quantity = self.calculate_outputs(state_handle, ts_length) return site_indices, offer_price, quantity def calculate_outputs(self, state_handle, ts_length):",
"map_data.shape[0]): self.site_to_data[map_data[i, 0]] = map_data[i, 1] if len(self.params_to_site) == 0: # We have",
"in site_to_data are within the # self.data matrix. max_data = self.data.shape[1] for data_index",
"notice shall be included in all #copies or substantial portions of the Software.",
"of a variable generator, providing per-unit capital costs. \"\"\" def get_details(self): \"\"\"Return a",
"- the name of the data array e.g. ts_wind_map which holds an n",
"list is ' + str(len(self.params_to_site)) + ' so no automatic mapping is possible.',",
"identifying indices of each site with active capacity. All lists of sites below",
"CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"# Copyright (C) University of Melbourne 2013 # # # #Permission is hereby",
"of data required, for example ts_wind, ts_demand. Outputs: data_type: list of strings -",
"self.site_to_data[site] ### TODO - it may be expensive to have self.data this way",
"get_full_desc_string as defined in TxMultiGeneratorBase, for the variable generator. \"\"\" return self.get_simple_desc_string(results, state_handle)",
"site_indices[i] total_cap = sum([tup[0] for tup in cap_list[site]]) data_index = self.site_to_data[site] ### TODO",
"set_data(self, data): \"\"\"Set the data dict with the data series required for the",
"defined in TxMultiGeneratorBase, for the variable generators. \"\"\" site_indices, supply = self.calculate_outputs(state_handle, len(supply_request))",
"self.calculate_outputs(state_handle, len(supply_request)) vble_cost, carbon, other = self.calculate_variable_costs(state_handle, site_indices, supply) return supply, vble_cost, carbon,",
"i else: # No list of sites is provided. Just map to ordinal",
"be included in all #copies or substantial portions of the Software. # #THE",
"self.data = data[self.config['data_name']] self.site_to_data = {} if len(self.config['data_map_name']) > 0: map_data = data[self.config['data_map_name']]",
"# lengths agree, map the site index list to the data 1:1. if",
"\"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [ ('tech_type', None, 'generic_variable'), ('detail_type', None, 'generic_variable'), ('data_name', None,",
"= self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity = self.calculate_outputs(state_handle, ts_length) return site_indices, offer_price, quantity def calculate_outputs(self,",
"schedule: The scheduled output, a set of timeseries Outputs: variable_cost, carbon, other \"\"\"",
"portions of the Software. # #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"= len(site_indices) vble_cost = numpy.zeros(num_sites) carbon = numpy.zeros(num_sites) for i in range(num_sites): vble_cost[i]",
"None, 'generic_variable'), ('data_name', None, None), ('data_map_name', None, ''), ('data_ts_length', int, None) ] def",
"to report in get_details() as technology. detail_type: string - a specific name, e.g.",
"possible.', {}) for i in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] = i else: # No list",
"those requested by get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data = data[self.config['data_name']] self.site_to_data = {}",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR",
"supply_request, max_supply=[], price=[]): \"\"\"Implement calculate_outputs_and_costs as defined in TxMultiGeneratorBase, for the variable generators.",
"following conditions: # #The above copyright notice and this permission notice shall be",
"txmultigenerator.TxMultiGeneratorBase, plus: tech_type: string - the generic technology type, to report in get_details()",
"#in the Software without restriction, including without limitation the rights #to use, copy,",
"lengths agree, map the site index list to the data 1:1. if not",
"with keys matching those requested by get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data = data[self.config['data_name']]",
"Melbourne 2013 # # # #Permission is hereby granted, free of charge, to",
"OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"site_indices: the identifying indices of each site with active capacity. All lists of",
"values in site_to_data are within the # self.data matrix. max_data = self.data.shape[1] for",
"type of data required, for example ts_wind, ts_demand. Outputs: data_type: list of strings",
"data[self.config['data_map_name']] for i in range(0, map_data.shape[0]): self.site_to_data[map_data[i, 0]] = map_data[i, 1] if len(self.params_to_site)",
"def get_simple_desc_string(self, results, state_handle): \"\"\"Implement get_simple_desc_string as defined in TxMultiGeneratorBase, for the variable",
"i in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] = i else: # No list of sites is",
"txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] = self.config['tech_type'] flags['dispatch'] = 'semischeduled' return flags def get_config_spec(self): \"\"\"Return a",
"for i in range(num_sites): vble_cost[i] = numpy.sum(schedule[i,:]) * vom return vble_cost, carbon, {}",
"price, one per site (interpreted as same for all timesteps) quantity: the offer",
"the data array e.g. ts_wind_map which holds an n x 2 array where",
"= i # Check that all of the values in site_to_data are within",
"OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR",
"\"\"\"Return a list of flags indicating the properties of the generator. \"\"\" flags",
"txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if len(self.config['data_map_name']) > 0: data_types.append(self.config['data_map_name']) return data_types def set_data(self, data): \"\"\"Set",
"# No data map is provided, but params_to_site is. If the # lengths",
"the VOM for variable generators. \"\"\" return self.period_configs[period]['vom'] def get_offers_semischeduled(self, state_handle, ts_length): \"\"\"Get",
"- the generic technology type, to report in get_details() as technology. detail_type: string",
"in range(0, self.data.shape[1]): self.site_to_data[i] = i # Check that all of the values",
"of the data timeseries, typically provided globally. \"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [ ('tech_type',",
"sites below will correspond with this list. offer_price: the offer price, one per",
"site_indices, offer_price, quantity def calculate_outputs(self, state_handle, ts_length): \"\"\"Calculate the maximum outputs, before scheduling.",
"in an output string data_name: string - the name of the data array",
"Just map to ordinal numbers. self.params_to_site = range(self.data.shape[1]) for i in range(0, self.data.shape[1]):",
"price=[]): \"\"\"Implement calculate_outputs_and_costs as defined in TxMultiGeneratorBase, for the variable generators. \"\"\" site_indices,",
"format (name, conversion function, default), e.g. ('capex', float, 2.0). Put None if no",
"{} if len(self.config['data_map_name']) > 0: map_data = data[self.config['data_map_name']] for i in range(0, map_data.shape[0]):",
"all data are used and map 1:1 to this. self.params_to_site = map_data[:,0] elif",
"('name', None, None) Configuration: as for txmultigenerator.TxMultiGeneratorBase, plus: tech_type: string - the generic",
"and/or sell #copies of the Software, and to permit persons to whom the",
"with the data series required for the generator. Inputs: data: dict - with",
"map is provided, but params_to_site is. If the # lengths agree, map the",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"self.calculate_outputs(state_handle, ts_length) return site_indices, offer_price, quantity def calculate_outputs(self, state_handle, ts_length): \"\"\"Calculate the maximum",
"name, e.g. 'onshore_wind_vic', for printing in an output string data_name: string - the",
"way - ### would it help to transpose it when it's read in,",
"a variable generator using the txmultigeneratormultisite base class. \"\"\" from tools import configurablebase,",
"Check that all of the values in site_to_data are within the # self.data",
"= self.period_configs[state_handle['curr_period']]['vom'] * 1e-6 num_sites = len(site_indices) vble_cost = numpy.zeros(num_sites) carbon = numpy.zeros(num_sites)",
"results, state_handle): \"\"\"Implement get_full_desc_string as defined in TxMultiGeneratorBase, for the variable generator. \"\"\"",
"'semischeduled' return flags def get_config_spec(self): \"\"\"Return a list of tuples of format (name,",
"SRMC. This is the VOM for variable generators. \"\"\" return self.period_configs[period]['vom'] def get_offers_semischeduled(self,",
"is the number of site indices mapped. The first in each pair is",
"''), ('data_ts_length', int, None) ] def get_data_types(self): \"\"\"Return a list of keys for",
"No list of sites is provided. Just map to ordinal numbers. self.params_to_site =",
"and this permission notice shall be included in all #copies or substantial portions",
"0]] = map_data[i, 1] if len(self.params_to_site) == 0: # We have a data",
"0) or (data_index >= max_data): raise mureilexception.ConfigException('data_index ' + str(data_index) + ' was",
"a variable generator, providing per-unit capital costs. \"\"\" def get_details(self): \"\"\"Return a list",
"second the index into the data table. If this is not provided, a",
"ts_demand. Outputs: data_type: list of strings - each a key name describing the",
"max_data = self.data.shape[1] for data_index in self.site_to_data.itervalues(): if (data_index < 0) or (data_index",
"may be expensive to have self.data this way - ### would it help",
"= i else: # No list of sites is provided. Just map to",
"+ ' so no automatic mapping is possible.', {}) for i in range(len(self.params_to_site)):",
"per site, in MW. \"\"\" offer_price = self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity = self.calculate_outputs(state_handle, ts_length)",
"the Software, and to permit persons to whom the Software is #furnished to",
"OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"e.g. ts_wind. data_map_name: string - the name of the data array e.g. ts_wind_map",
"data) self.data = data[self.config['data_name']] self.site_to_data = {} if len(self.config['data_map_name']) > 0: map_data =",
"Outputs: variable_cost, carbon, other \"\"\" vom = self.period_configs[state_handle['curr_period']]['vom'] * 1e-6 num_sites = len(site_indices)",
"lines up better? output[i,:] = self.data[:,data_index] * total_cap return site_indices, output def calculate_variable_costs(self,",
"requested by get_data_types. \"\"\" txmultigeneratormultisite.TxMultiGeneratorMultiSite.set_data(self, data) self.data = data[self.config['data_name']] self.site_to_data = {} if",
"site_indices: the list of sites with active capacity output: a set of timeseries,",
"#The above copyright notice and this permission notice shall be included in all",
"index and the second the index into the data table. If this is",
"ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"integer - the length of the timeseries Outputs: site_indices: the list of sites",
"simple implementation of a variable generator, providing per-unit capital costs. \"\"\" def get_details(self):",
"flags def get_config_spec(self): \"\"\"Return a list of tuples of format (name, conversion function,",
"maximum index in the data array is ' + str(max_data), {}) def calculate_dispatch_offer(self,",
"2 array where n is the number of site indices mapped. The first",
"required for this generator. \"\"\" data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if len(self.config['data_map_name']) > 0:",
"array is ' + str(max_data), {}) def calculate_dispatch_offer(self, period, param=None): \"\"\"Calculate the dispatch",
"is ' + str(max_data), {}) def calculate_dispatch_offer(self, period, param=None): \"\"\"Calculate the dispatch offer",
">= max_data): raise mureilexception.ConfigException('data_index ' + str(data_index) + ' was requested by the",
"is the site index and the second the index into the data table.",
"### TODO - it may be expensive to have self.data this way -",
"else: # No list of sites is provided. Just map to ordinal numbers.",
"\"\"\" offer_price = self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity = self.calculate_outputs(state_handle, ts_length) return site_indices, offer_price, quantity",
"self.config['tech_type'] flags['dispatch'] = 'semischeduled' return flags def get_config_spec(self): \"\"\"Return a list of tuples",
"memory lines up better? output[i,:] = self.data[:,data_index] * total_cap return site_indices, output def",
"site, so assume # all data are used and map 1:1 to this.",
"def calculate_outputs_and_costs(self, state_handle, supply_request, max_supply=[], price=[]): \"\"\"Implement calculate_outputs_and_costs as defined in TxMultiGeneratorBase, for",
"variable generators. \"\"\" site_indices, supply = self.calculate_outputs(state_handle, len(supply_request)) vble_cost, carbon, other = self.calculate_variable_costs(state_handle,",
"elif len(self.params_to_site) > 0: # No data map is provided, but params_to_site is.",
"offer_price, quantity def calculate_outputs(self, state_handle, ts_length): \"\"\"Calculate the maximum outputs, before scheduling. Inputs:",
"the data dict with the data series required for the generator. Inputs: data:",
"site index and the second the index into the data table. If this",
"was requested by the model in section ' + self.config['section'] + ' but",
"data array e.g. ts_wind_map which holds an n x 2 array where n",
"if not (len(self.params_to_site) == self.data.shape[1]): raise mureilexception.ConfigException('In model ' + self.config['section'] + ',",
"carbon based on schedule. Inputs: state_handle site_indices schedule: The scheduled output, a set",
"NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"assume # all data are used and map 1:1 to this. self.params_to_site =",
"MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"but the maximum index in the data array is ' + str(max_data), {})",
"merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO",
"used and map 1:1 to this. self.params_to_site = map_data[:,0] elif len(self.params_to_site) > 0:",
"automatic mapping is possible.', {}) for i in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] = i else:",
"holding the timeseries capacity factor data, e.g. ts_wind. data_map_name: string - the name",
"Configuration: as for txmultigenerator.TxMultiGeneratorBase, plus: tech_type: string - the generic technology type, to",
"above copyright notice and this permission notice shall be included in all #copies",
"modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to",
"THE #SOFTWARE. # # \"\"\"Module for a variable generator using the txmultigeneratormultisite base",
"+ str(max_data), {}) def calculate_dispatch_offer(self, period, param=None): \"\"\"Calculate the dispatch offer as the",
"the values in site_to_data are within the # self.data matrix. max_data = self.data.shape[1]",
"data, e.g. ts_wind. data_map_name: string - the name of the data array e.g.",
"if (data_index < 0) or (data_index >= max_data): raise mureilexception.ConfigException('data_index ' + str(data_index)",
"data required for this generator. \"\"\" data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if len(self.config['data_map_name']) >",
"No data map is provided, but params_to_site is. If the # lengths agree,",
"with active capacity output: a set of timeseries, corresponding to site_indices \"\"\" cap_list",
"vble_cost = numpy.zeros(num_sites) carbon = numpy.zeros(num_sites) for i in range(num_sites): vble_cost[i] = numpy.sum(schedule[i,:])",
"calculate_outputs(self, state_handle, ts_length): \"\"\"Calculate the maximum outputs, before scheduling. Inputs: state_handle ts_length: an",
"' + str(len(self.params_to_site)) + ' so no automatic mapping is possible.', {}) for",
"self.params_to_site = map_data[:,0] elif len(self.params_to_site) > 0: # No data map is provided,",
"### the memory lines up better? output[i,:] = self.data[:,data_index] * total_cap return site_indices,",
"output = numpy.zeros((num_sites, ts_length)) for i in range(num_sites): site = site_indices[i] total_cap =",
"in all #copies or substantial portions of the Software. # #THE SOFTWARE IS",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED",
"- each a key name describing the data required for this generator. \"\"\"",
"to any person obtaining a copy #of this software and associated documentation files",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"the properties of the generator. \"\"\" flags = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_details(self) flags['technology'] = self.config['tech_type'] flags['dispatch']",
"+ ' with site capacities (MW): ' + ( string.join(map('({:d}: {:.2f}) '.format, results['site_indices'],",
"for i in range(len(self.params_to_site)): self.site_to_data[self.params_to_site[i]] = i else: # No list of sites",
"\"\"\" vom = self.period_configs[state_handle['curr_period']]['vom'] * 1e-6 num_sites = len(site_indices) vble_cost = numpy.zeros(num_sites) carbon",
"variable costs and carbon based on schedule. Inputs: state_handle site_indices schedule: The scheduled",
"timeseries per site, in MW. \"\"\" offer_price = self.calculate_dispatch_offer(state_handle['curr_period']) site_indices, quantity = self.calculate_outputs(state_handle,",
"timeseries, typically provided globally. \"\"\" return txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_config_spec(self) + [ ('tech_type', None, 'generic_variable'), ('detail_type',",
"self.calculate_variable_costs(state_handle, site_indices, supply) return supply, vble_cost, carbon, other def get_simple_desc_string(self, results, state_handle): \"\"\"Implement",
"numpy.zeros(num_sites) carbon = numpy.zeros(num_sites) for i in range(num_sites): vble_cost[i] = numpy.sum(schedule[i,:]) * vom",
"supply, vble_cost, carbon, other def get_simple_desc_string(self, results, state_handle): \"\"\"Implement get_simple_desc_string as defined in",
"def get_full_desc_string(self, results, state_handle): \"\"\"Implement get_full_desc_string as defined in TxMultiGeneratorBase, for the variable",
"> 0: data_types.append(self.config['data_map_name']) return data_types def set_data(self, data): \"\"\"Set the data dict with",
"#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. # # \"\"\"Module",
"shall be included in all #copies or substantial portions of the Software. #",
"output, a set of timeseries Outputs: variable_cost, carbon, other \"\"\" vom = self.period_configs[state_handle['curr_period']]['vom']",
"self.site_to_data[map_data[i, 0]] = map_data[i, 1] if len(self.params_to_site) == 0: # We have a",
"= self.config['tech_type'] flags['dispatch'] = 'semischeduled' return flags def get_config_spec(self): \"\"\"Return a list of",
"SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"for printing in an output string data_name: string - the name of the",
"a 1:1 is assumed. data_ts_length: the length of the data timeseries, typically provided",
"0: map_data = data[self.config['data_map_name']] for i in range(0, map_data.shape[0]): self.site_to_data[map_data[i, 0]] = map_data[i,",
"of the values in site_to_data are within the # self.data matrix. max_data =",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN",
"data_types = txmultigeneratormultisite.TxMultiGeneratorMultiSite.get_data_types(self) data_types.append(self.config['data_name']) if len(self.config['data_map_name']) > 0: data_types.append(self.config['data_map_name']) return data_types def set_data(self,",
"# We have a data map, but no params to site, so assume",
"other = self.calculate_variable_costs(state_handle, site_indices, supply) return supply, vble_cost, carbon, other def get_simple_desc_string(self, results,",
"the generator. Inputs: data: dict - with keys matching those requested by get_data_types.",
"calculate_dispatch_offer(self, period, param=None): \"\"\"Calculate the dispatch offer as the SRMC. This is the",
"into the data table. If this is not provided, a 1:1 is assumed.",
"no default value, e.g. ('name', None, None) Configuration: as for txmultigenerator.TxMultiGeneratorBase, plus: tech_type:",
"IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"mureilexception from generator import txmultigeneratormultisite from master import interfacesflowmaster import copy import numpy",
"('detail_type', None, 'generic_variable'), ('data_name', None, None), ('data_map_name', None, ''), ('data_ts_length', int, None) ]",
"offer price, one per site (interpreted as same for all timesteps) quantity: the",
"def get_data_types(self): \"\"\"Return a list of keys for each type of data required,",
"would it help to transpose it when it's read in, so ### the",
"results['site_indices'], results['capacity']))) def get_full_desc_string(self, results, state_handle): \"\"\"Implement get_full_desc_string as defined in TxMultiGeneratorBase, for",
"self.config['section'] + ' but the maximum index in the data array is '",
"function, default), e.g. ('capex', float, 2.0). Put None if no conversion required, or",
"len(supply_request)) vble_cost, carbon, other = self.calculate_variable_costs(state_handle, site_indices, supply) return supply, vble_cost, carbon, other"
] |
[
". import api from ..database import Interval @api.route('/intervals') def get_intervals(): intervals = Interval.query.all()",
"..database import Interval @api.route('/intervals') def get_intervals(): intervals = Interval.query.all() return jsonify([{ 'id': interval.id,",
"import api from ..database import Interval @api.route('/intervals') def get_intervals(): intervals = Interval.query.all() return",
"@api.route('/intervals') def get_intervals(): intervals = Interval.query.all() return jsonify([{ 'id': interval.id, 'name': interval.name, 'start':",
"from flask import jsonify from . import api from ..database import Interval @api.route('/intervals')",
"import Interval @api.route('/intervals') def get_intervals(): intervals = Interval.query.all() return jsonify([{ 'id': interval.id, 'name':",
"= Interval.query.all() return jsonify([{ 'id': interval.id, 'name': interval.name, 'start': str(interval.start), 'end': str(interval.end) }",
"jsonify from . import api from ..database import Interval @api.route('/intervals') def get_intervals(): intervals",
"'id': interval.id, 'name': interval.name, 'start': str(interval.start), 'end': str(interval.end) } for interval in intervals])",
"Interval @api.route('/intervals') def get_intervals(): intervals = Interval.query.all() return jsonify([{ 'id': interval.id, 'name': interval.name,",
"Interval.query.all() return jsonify([{ 'id': interval.id, 'name': interval.name, 'start': str(interval.start), 'end': str(interval.end) } for",
"intervals = Interval.query.all() return jsonify([{ 'id': interval.id, 'name': interval.name, 'start': str(interval.start), 'end': str(interval.end)",
"return jsonify([{ 'id': interval.id, 'name': interval.name, 'start': str(interval.start), 'end': str(interval.end) } for interval",
"jsonify([{ 'id': interval.id, 'name': interval.name, 'start': str(interval.start), 'end': str(interval.end) } for interval in",
"import jsonify from . import api from ..database import Interval @api.route('/intervals') def get_intervals():",
"api from ..database import Interval @api.route('/intervals') def get_intervals(): intervals = Interval.query.all() return jsonify([{",
"flask import jsonify from . import api from ..database import Interval @api.route('/intervals') def",
"get_intervals(): intervals = Interval.query.all() return jsonify([{ 'id': interval.id, 'name': interval.name, 'start': str(interval.start), 'end':",
"from ..database import Interval @api.route('/intervals') def get_intervals(): intervals = Interval.query.all() return jsonify([{ 'id':",
"from . import api from ..database import Interval @api.route('/intervals') def get_intervals(): intervals =",
"def get_intervals(): intervals = Interval.query.all() return jsonify([{ 'id': interval.id, 'name': interval.name, 'start': str(interval.start),"
] |
[] |
[
"import expand_dict_as_keys from tests.common import BaseCase class Test(BaseCase): def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [ tuple()",
"2), ('c', 5)]), tuple([('a', 1), ('b', 3), ('c', 4)]), tuple([('a', 1), ('b', 3),",
"self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])), [ tuple([('a', 1), ('b', 2)]), tuple([('a', 1), ('b', 3)]), ])",
"]) def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])), [ tuple([('a', 1), ('b', 2)]), tuple([('a', 1),",
"def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [ tuple([('a', 1), ('b', 2)]) ]) def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1,",
"test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5])), [ tuple([('a', 1), ('b', 2), ('c', 4)]),",
"5)]), ]) def test_usage(self): keys = set(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5]))) self.assertIn(expand_dict_as_keys(dict(a=1, b=2,",
"tuple([('a', 1), ('b', 2)]), tuple([('a', 1), ('b', 3)]), ]) def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2,",
"b=2)), [ tuple([('b', 2), ('c', 1)]) ]) def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])), [",
"('b', 3), ('c', 5)]), ]) def test_usage(self): keys = set(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4,",
"1), ('b', 3), ('c', 5)]), ]) def test_usage(self): keys = set(expand_dict_as_keys(dict(a=1, b=[2, 3],",
"test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])), [ tuple([('a', 1), ('b', 2)]), tuple([('a', 1), ('b', 3)]),",
"1), ('b', 2)]), tuple([('a', 1), ('b', 3)]), ]) def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3],",
"def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [ tuple([('b', 2), ('c', 1)]) ]) def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1,",
"1), ('b', 3), ('c', 4)]), tuple([('a', 1), ('b', 3), ('c', 5)]), ]) def",
"3), ('c', 4)]), tuple([('a', 1), ('b', 3), ('c', 5)]), ]) def test_usage(self): keys",
"[ tuple() ]) def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [ tuple([('a', 1), ('b', 2)]) ])",
"expand_dict_as_keys from tests.common import BaseCase class Test(BaseCase): def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [ tuple() ])",
"('b', 2)]), tuple([('a', 1), ('b', 3)]), ]) def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4,",
"[ tuple([('a', 1), ('b', 2), ('c', 4)]), tuple([('a', 1), ('b', 2), ('c', 5)]),",
"5)]), tuple([('a', 1), ('b', 3), ('c', 4)]), tuple([('a', 1), ('b', 3), ('c', 5)]),",
"('b', 3), ('c', 4)]), tuple([('a', 1), ('b', 3), ('c', 5)]), ]) def test_usage(self):",
"2)]) ]) def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [ tuple([('b', 2), ('c', 1)]) ]) def",
"test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [ tuple() ]) def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [ tuple([('a', 1), ('b',",
"mbed_cloud.subscribe.subscribe import expand_dict_as_keys from tests.common import BaseCase class Test(BaseCase): def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [",
"3])), [ tuple([('a', 1), ('b', 2)]), tuple([('a', 1), ('b', 3)]), ]) def test_product(self):",
"3), ('c', 5)]), ]) def test_usage(self): keys = set(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5])))",
"tuple([('a', 1), ('b', 2), ('c', 4)]), tuple([('a', 1), ('b', 2), ('c', 5)]), tuple([('a',",
"def test_usage(self): keys = set(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5]))) self.assertIn(expand_dict_as_keys(dict(a=1, b=2, c=5))[0], keys)",
"]) def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5])), [ tuple([('a', 1), ('b', 2),",
"]) def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [ tuple([('a', 1), ('b', 2)]) ]) def test_static_sorted(self):",
"tuple([('a', 1), ('b', 3)]), ]) def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5])), [",
"3)]), ]) def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5])), [ tuple([('a', 1), ('b',",
"class Test(BaseCase): def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [ tuple() ]) def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [",
"4)]), tuple([('a', 1), ('b', 3), ('c', 5)]), ]) def test_usage(self): keys = set(expand_dict_as_keys(dict(a=1,",
"3], c=[4, 5])), [ tuple([('a', 1), ('b', 2), ('c', 4)]), tuple([('a', 1), ('b',",
"tuple() ]) def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [ tuple([('a', 1), ('b', 2)]) ]) def",
"('c', 4)]), tuple([('a', 1), ('b', 3), ('c', 5)]), ]) def test_usage(self): keys =",
"[ tuple([('b', 2), ('c', 1)]) ]) def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])), [ tuple([('a',",
"1), ('b', 2), ('c', 4)]), tuple([('a', 1), ('b', 2), ('c', 5)]), tuple([('a', 1),",
"tests.common import BaseCase class Test(BaseCase): def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [ tuple() ]) def test_static(self):",
"4)]), tuple([('a', 1), ('b', 2), ('c', 5)]), tuple([('a', 1), ('b', 3), ('c', 4)]),",
"('c', 5)]), tuple([('a', 1), ('b', 3), ('c', 4)]), tuple([('a', 1), ('b', 3), ('c',",
"1), ('b', 2)]) ]) def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [ tuple([('b', 2), ('c', 1)])",
"]) def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [ tuple([('b', 2), ('c', 1)]) ]) def test_expand(self):",
"import BaseCase class Test(BaseCase): def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [ tuple() ]) def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1,",
"[ tuple([('a', 1), ('b', 2)]) ]) def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [ tuple([('b', 2),",
"tuple([('a', 1), ('b', 3), ('c', 4)]), tuple([('a', 1), ('b', 3), ('c', 5)]), ])",
"self.assertEqual(expand_dict_as_keys(dict()), [ tuple() ]) def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [ tuple([('a', 1), ('b', 2)])",
"1), ('b', 3)]), ]) def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5])), [ tuple([('a',",
"tuple([('a', 1), ('b', 2)]) ]) def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [ tuple([('b', 2), ('c',",
"Test(BaseCase): def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [ tuple() ]) def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [ tuple([('a',",
"test_usage(self): keys = set(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5]))) self.assertIn(expand_dict_as_keys(dict(a=1, b=2, c=5))[0], keys) self.assertNotIn(expand_dict_as_keys(dict(a=1,",
"self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [ tuple([('b', 2), ('c', 1)]) ]) def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])),",
"tuple([('b', 2), ('c', 1)]) ]) def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])), [ tuple([('a', 1),",
"b=[2, 3], c=[4, 5])), [ tuple([('a', 1), ('b', 2), ('c', 4)]), tuple([('a', 1),",
"2)]), tuple([('a', 1), ('b', 3)]), ]) def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5])),",
"test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [ tuple([('b', 2), ('c', 1)]) ]) def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2,",
"set(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5]))) self.assertIn(expand_dict_as_keys(dict(a=1, b=2, c=5))[0], keys) self.assertNotIn(expand_dict_as_keys(dict(a=1, b=2, c=6))[0], keys)",
"]) def test_usage(self): keys = set(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5]))) self.assertIn(expand_dict_as_keys(dict(a=1, b=2, c=5))[0],",
"from tests.common import BaseCase class Test(BaseCase): def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [ tuple() ]) def",
"2), ('c', 4)]), tuple([('a', 1), ('b', 2), ('c', 5)]), tuple([('a', 1), ('b', 3),",
"('c', 1)]) ]) def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])), [ tuple([('a', 1), ('b', 2)]),",
"('c', 5)]), ]) def test_usage(self): keys = set(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5]))) self.assertIn(expand_dict_as_keys(dict(a=1,",
"test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [ tuple([('a', 1), ('b', 2)]) ]) def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)),",
"('b', 2), ('c', 5)]), tuple([('a', 1), ('b', 3), ('c', 4)]), tuple([('a', 1), ('b',",
"('c', 4)]), tuple([('a', 1), ('b', 2), ('c', 5)]), tuple([('a', 1), ('b', 3), ('c',",
"def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])), [ tuple([('a', 1), ('b', 2)]), tuple([('a', 1), ('b',",
"BaseCase class Test(BaseCase): def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [ tuple() ]) def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)),",
"[ tuple([('a', 1), ('b', 2)]), tuple([('a', 1), ('b', 3)]), ]) def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1,",
"self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5])), [ tuple([('a', 1), ('b', 2), ('c', 4)]), tuple([('a',",
"tuple([('a', 1), ('b', 3), ('c', 5)]), ]) def test_usage(self): keys = set(expand_dict_as_keys(dict(a=1, b=[2,",
"2), ('c', 1)]) ]) def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])), [ tuple([('a', 1), ('b',",
"1), ('b', 2), ('c', 5)]), tuple([('a', 1), ('b', 3), ('c', 4)]), tuple([('a', 1),",
"from mbed_cloud.subscribe.subscribe import expand_dict_as_keys from tests.common import BaseCase class Test(BaseCase): def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()),",
"5])), [ tuple([('a', 1), ('b', 2), ('c', 4)]), tuple([('a', 1), ('b', 2), ('c',",
"b=[2, 3])), [ tuple([('a', 1), ('b', 2)]), tuple([('a', 1), ('b', 3)]), ]) def",
"1)]) ]) def test_expand(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3])), [ tuple([('a', 1), ('b', 2)]), tuple([('a',",
"self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [ tuple([('a', 1), ('b', 2)]) ]) def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [",
"def test_empty(self): self.assertEqual(expand_dict_as_keys(dict()), [ tuple() ]) def test_static(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=2)), [ tuple([('a', 1),",
"c=[4, 5])), [ tuple([('a', 1), ('b', 2), ('c', 4)]), tuple([('a', 1), ('b', 2),",
"('b', 2)]) ]) def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [ tuple([('b', 2), ('c', 1)]) ])",
"('b', 2), ('c', 4)]), tuple([('a', 1), ('b', 2), ('c', 5)]), tuple([('a', 1), ('b',",
"b=2)), [ tuple([('a', 1), ('b', 2)]) ]) def test_static_sorted(self): self.assertEqual(expand_dict_as_keys(dict(c=1, b=2)), [ tuple([('b',",
"tuple([('a', 1), ('b', 2), ('c', 5)]), tuple([('a', 1), ('b', 3), ('c', 4)]), tuple([('a',",
"= set(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5]))) self.assertIn(expand_dict_as_keys(dict(a=1, b=2, c=5))[0], keys) self.assertNotIn(expand_dict_as_keys(dict(a=1, b=2, c=6))[0],",
"keys = set(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5]))) self.assertIn(expand_dict_as_keys(dict(a=1, b=2, c=5))[0], keys) self.assertNotIn(expand_dict_as_keys(dict(a=1, b=2,",
"def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5])), [ tuple([('a', 1), ('b', 2), ('c',",
"('b', 3)]), ]) def test_product(self): self.assertEqual(expand_dict_as_keys(dict(a=1, b=[2, 3], c=[4, 5])), [ tuple([('a', 1),"
] |
[
"None and b is not None: # Can put good if space +",
"None: # Can put good if space + g <= m: # Can't",
"gi = 0 bi = 0 while space < m: g = good[gi]",
"+= 1 # Can't put good but can put bad elif space +",
"None b = bad[bi] if bi < len(bad) else None # Both good",
"None: # Still room left if space + g <= m: prot +=",
"\"1\": bad.append(int(s)) else: good.append(int(s)) good.sort() bad.sort() prot = 0 space = 0 gi",
"b is not None: # Can put good if space + g <=",
"None: if space + b <= m: prot += 1 space += b",
"not None: # Can put good if space + g <= m: #",
"s, p = input().split() if p == \"1\": bad.append(int(s)) else: good.append(int(s)) good.sort() bad.sort()",
"# Both good and bad left if g is not None and b",
"space = 0 gi = 0 bi = 0 while space < m:",
"< len(good) else None b = bad[bi] if bi < len(bad) else None",
"0 space = 0 gi = 0 bi = 0 while space <",
"space + g <= m: prot += 2 space += g gi +=",
"else: break # Only good left elif g is not None: # Still",
"0 while space < m: g = good[gi] if gi < len(good) else",
"bad and bad is more efficient else: prot += 1 space += b",
"bad left elif b is not None: if space + b <= m:",
"m = int(m) good = [] bad = [] for _ in range(n):",
"+ g <= m: # Can't put bad or good is more efficient",
"g gi += 1 else: break # Only bad left elif b is",
"input().split() if p == \"1\": bad.append(int(s)) else: good.append(int(s)) good.sort() bad.sort() prot = 0",
"efficient if space + b > m or g / 2 < m:",
"bad.append(int(s)) else: good.append(int(s)) good.sort() bad.sort() prot = 0 space = 0 gi =",
"+= b bi += 1 # Can't put good but can put bad",
"m: prot += 1 space += b bi += 1 # Can't put",
"prot += 2 space += g gi += 1 # Can put bad",
"bad is more efficient else: prot += 1 space += b bi +=",
"in range(n): s, p = input().split() if p == \"1\": bad.append(int(s)) else: good.append(int(s))",
"bi += 1 # Can't put either one else: break # Only good",
"if space + g <= m: # Can't put bad or good is",
"is more efficient if space + b > m or g / 2",
"is not None: # Can put good if space + g <= m:",
"# Can't put bad or good is more efficient if space + b",
"= input().split() if p == \"1\": bad.append(int(s)) else: good.append(int(s)) good.sort() bad.sort() prot =",
"else: good.append(int(s)) good.sort() bad.sort() prot = 0 space = 0 gi = 0",
"if bi < len(bad) else None # Both good and bad left if",
"prot += 1 space += b bi += 1 else: break # Nothing",
"1 space += b bi += 1 # Can't put good but can",
"good left elif g is not None: # Still room left if space",
"space += b bi += 1 # Can't put either one else: break",
"< len(bad) else None # Both good and bad left if g is",
"= int(m) good = [] bad = [] for _ in range(n): s,",
"g <= m: prot += 2 space += g gi += 1 else:",
"not None: if space + b <= m: prot += 1 space +=",
"good.append(int(s)) good.sort() bad.sort() prot = 0 space = 0 gi = 0 bi",
"== \"1\": bad.append(int(s)) else: good.append(int(s)) good.sort() bad.sort() prot = 0 space = 0",
"or good is more efficient if space + b > m or g",
"space < m: g = good[gi] if gi < len(good) else None b",
"<= m: prot += 1 space += b bi += 1 # Can't",
"space += b bi += 1 # Can't put good but can put",
"+= 1 space += b bi += 1 # Can't put either one",
"Only good left elif g is not None: # Still room left if",
"room left if space + g <= m: prot += 2 space +=",
"m: prot += 2 space += g gi += 1 # Can put",
"Can put good if space + g <= m: # Can't put bad",
"if space + b > m or g / 2 < m: prot",
"put bad elif space + b <= m: prot += 1 space +=",
"> m or g / 2 < m: prot += 2 space +=",
"_ in range(n): s, p = input().split() if p == \"1\": bad.append(int(s)) else:",
"good is more efficient if space + b > m or g /",
"= 0 gi = 0 bi = 0 while space < m: g",
"+= 2 space += g gi += 1 # Can put bad and",
"elif g is not None: # Still room left if space + g",
"gi += 1 else: break # Only bad left elif b is not",
"n = int(n) m = int(m) good = [] bad = [] for",
"len(bad) else None # Both good and bad left if g is not",
"g = good[gi] if gi < len(good) else None b = bad[bi] if",
"or g / 2 < m: prot += 2 space += g gi",
"m = input().split() n = int(n) m = int(m) good = [] bad",
"2 space += g gi += 1 else: break # Only bad left",
"more efficient if space + b > m or g / 2 <",
"+= 1 space += b bi += 1 else: break # Nothing left",
"m: prot += 2 space += g gi += 1 else: break #",
"+= b bi += 1 # Can't put either one else: break #",
"m: # Can't put bad or good is more efficient if space +",
"# Can't put good but can put bad elif space + b <=",
"Can't put bad or good is more efficient if space + b >",
"efficient else: prot += 1 space += b bi += 1 # Can't",
"bad.sort() prot = 0 space = 0 gi = 0 bi = 0",
"= 0 space = 0 gi = 0 bi = 0 while space",
"1 else: break # Only bad left elif b is not None: if",
"else None b = bad[bi] if bi < len(bad) else None # Both",
"# Can put good if space + g <= m: # Can't put",
"good if space + g <= m: # Can't put bad or good",
"bi = 0 while space < m: g = good[gi] if gi <",
"bad[bi] if bi < len(bad) else None # Both good and bad left",
"= bad[bi] if bi < len(bad) else None # Both good and bad",
"prot += 1 space += b bi += 1 # Can't put good",
"space += b bi += 1 else: break # Nothing left else: break",
"bi += 1 # Can't put good but can put bad elif space",
"g is not None: # Still room left if space + g <=",
"one else: break # Only good left elif g is not None: #",
"0 gi = 0 bi = 0 while space < m: g =",
"left elif g is not None: # Still room left if space +",
"p == \"1\": bad.append(int(s)) else: good.append(int(s)) good.sort() bad.sort() prot = 0 space =",
"# Still room left if space + g <= m: prot += 2",
"= [] for _ in range(n): s, p = input().split() if p ==",
"+= g gi += 1 # Can put bad and bad is more",
"put bad and bad is more efficient else: prot += 1 space +=",
"+= g gi += 1 else: break # Only bad left elif b",
"elif b is not None: if space + b <= m: prot +=",
"= [] bad = [] for _ in range(n): s, p = input().split()",
"good[gi] if gi < len(good) else None b = bad[bi] if bi <",
"either one else: break # Only good left elif g is not None:",
"if g is not None and b is not None: # Can put",
"else: prot += 1 space += b bi += 1 # Can't put",
"+= 1 # Can't put either one else: break # Only good left",
"break # Only good left elif g is not None: # Still room",
"[] bad = [] for _ in range(n): s, p = input().split() if",
"< m: g = good[gi] if gi < len(good) else None b =",
"m: g = good[gi] if gi < len(good) else None b = bad[bi]",
"+ b > m or g / 2 < m: prot += 2",
"put good if space + g <= m: # Can't put bad or",
"space + g <= m: # Can't put bad or good is more",
"1 # Can't put either one else: break # Only good left elif",
"+= 2 space += g gi += 1 else: break # Only bad",
"< m: prot += 2 space += g gi += 1 # Can",
"elif space + b <= m: prot += 1 space += b bi",
"else: break # Only bad left elif b is not None: if space",
"+ g <= m: prot += 2 space += g gi += 1",
"+= 1 # Can put bad and bad is more efficient else: prot",
"and bad left if g is not None and b is not None:",
"b bi += 1 # Can't put good but can put bad elif",
"+= 1 space += b bi += 1 # Can't put good but",
"1 space += b bi += 1 else: break # Nothing left else:",
"good = [] bad = [] for _ in range(n): s, p =",
"= 0 bi = 0 while space < m: g = good[gi] if",
"b > m or g / 2 < m: prot += 2 space",
"but can put bad elif space + b <= m: prot += 1",
"space + b <= m: prot += 1 space += b bi +=",
"<= m: # Can't put bad or good is more efficient if space",
"int(m) good = [] bad = [] for _ in range(n): s, p",
"Can put bad and bad is more efficient else: prot += 1 space",
"# Only good left elif g is not None: # Still room left",
"left if space + g <= m: prot += 2 space += g",
"gi < len(good) else None b = bad[bi] if bi < len(bad) else",
"2 < m: prot += 2 space += g gi += 1 #",
"+ b <= m: prot += 1 space += b bi += 1",
"int(n) m = int(m) good = [] bad = [] for _ in",
"0 bi = 0 while space < m: g = good[gi] if gi",
"else None # Both good and bad left if g is not None",
"put good but can put bad elif space + b <= m: prot",
"Only bad left elif b is not None: if space + b <=",
"bad = [] for _ in range(n): s, p = input().split() if p",
"bad or good is more efficient if space + b > m or",
"break # Only bad left elif b is not None: if space +",
"b <= m: prot += 1 space += b bi += 1 #",
"not None and b is not None: # Can put good if space",
"= 0 while space < m: g = good[gi] if gi < len(good)",
"space += g gi += 1 # Can put bad and bad is",
"g gi += 1 # Can put bad and bad is more efficient",
"= int(n) m = int(m) good = [] bad = [] for _",
"is more efficient else: prot += 1 space += b bi += 1",
"len(good) else None b = bad[bi] if bi < len(bad) else None #",
"and bad is more efficient else: prot += 1 space += b bi",
"<= m: prot += 1 space += b bi += 1 else: break",
"gi += 1 # Can put bad and bad is more efficient else:",
"while space < m: g = good[gi] if gi < len(good) else None",
"put bad or good is more efficient if space + b > m",
"1 # Can't put good but can put bad elif space + b",
"g / 2 < m: prot += 2 space += g gi +=",
"m or g / 2 < m: prot += 2 space += g",
"prot += 2 space += g gi += 1 else: break # Only",
"space += g gi += 1 else: break # Only bad left elif",
"+= 1 else: break # Only bad left elif b is not None:",
"prot = 0 space = 0 gi = 0 bi = 0 while",
"Can't put either one else: break # Only good left elif g is",
"2 space += g gi += 1 # Can put bad and bad",
"Still room left if space + g <= m: prot += 2 space",
"bad elif space + b <= m: prot += 1 space += b",
"+= b bi += 1 else: break # Nothing left else: break print(prot)",
"m: prot += 1 space += b bi += 1 else: break #",
"more efficient else: prot += 1 space += b bi += 1 #",
"b is not None: if space + b <= m: prot += 1",
"n, m = input().split() n = int(n) m = int(m) good = []",
"if gi < len(good) else None b = bad[bi] if bi < len(bad)",
"prot += 1 space += b bi += 1 # Can't put either",
"/ 2 < m: prot += 2 space += g gi += 1",
"bi < len(bad) else None # Both good and bad left if g",
"1 # Can put bad and bad is more efficient else: prot +=",
"is not None: # Still room left if space + g <= m:",
"= good[gi] if gi < len(good) else None b = bad[bi] if bi",
"can put bad elif space + b <= m: prot += 1 space",
"is not None and b is not None: # Can put good if",
"= input().split() n = int(n) m = int(m) good = [] bad =",
"b = bad[bi] if bi < len(bad) else None # Both good and",
"# Can't put either one else: break # Only good left elif g",
"put either one else: break # Only good left elif g is not",
"left elif b is not None: if space + b <= m: prot",
"is not None: if space + b <= m: prot += 1 space",
"good.sort() bad.sort() prot = 0 space = 0 gi = 0 bi =",
"good and bad left if g is not None and b is not",
"# Only bad left elif b is not None: if space + b",
"[] for _ in range(n): s, p = input().split() if p == \"1\":",
"None # Both good and bad left if g is not None and",
"and b is not None: # Can put good if space + g",
"# Can put bad and bad is more efficient else: prot += 1",
"if space + g <= m: prot += 2 space += g gi",
"if p == \"1\": bad.append(int(s)) else: good.append(int(s)) good.sort() bad.sort() prot = 0 space",
"input().split() n = int(n) m = int(m) good = [] bad = []",
"g is not None and b is not None: # Can put good",
"b bi += 1 # Can't put either one else: break # Only",
"left if g is not None and b is not None: # Can",
"b <= m: prot += 1 space += b bi += 1 else:",
"not None: # Still room left if space + g <= m: prot",
"1 space += b bi += 1 # Can't put either one else:",
"bad left if g is not None and b is not None: #",
"if space + b <= m: prot += 1 space += b bi",
"Can't put good but can put bad elif space + b <= m:",
"space + b > m or g / 2 < m: prot +=",
"<= m: prot += 2 space += g gi += 1 else: break",
"good but can put bad elif space + b <= m: prot +=",
"Both good and bad left if g is not None and b is",
"for _ in range(n): s, p = input().split() if p == \"1\": bad.append(int(s))",
"range(n): s, p = input().split() if p == \"1\": bad.append(int(s)) else: good.append(int(s)) good.sort()",
"g <= m: # Can't put bad or good is more efficient if",
"p = input().split() if p == \"1\": bad.append(int(s)) else: good.append(int(s)) good.sort() bad.sort() prot"
] |
[
"not the config :return: \"\"\" init(config) return { grp: {name: content.asdict() for name,",
"= config.DB_TIMEOUT_SEC from . import exploration from . import comparison from . import",
"random def get_kankeiforms(config): init(config) return KankeiForm.registry def get_kankeiforms_dict(config): \"\"\" note:: currently simply forward",
"import exploration from . import comparison from . import random def get_kankeiforms(config): init(config)",
":return: \"\"\" init(config) return { grp: {name: content.asdict() for name, content in content.items()}",
"{name: content.asdict() for name, content in content.items()} for grp, content in KankeiForm.registry.items() }",
"simply forward query config, however it is not ideal since we want to",
"init(config) return { grp: {name: content.asdict() for name, content in content.items()} for grp,",
"from components.kankeiforms.kankeiform import KankeiForm def init(config): KankeiForm.timeout = config.DB_TIMEOUT_SEC from . import exploration",
"config.DB_TIMEOUT_SEC from . import exploration from . import comparison from . import random",
"from . import random def get_kankeiforms(config): init(config) return KankeiForm.registry def get_kankeiforms_dict(config): \"\"\" note::",
"about `querying` and not the config :return: \"\"\" init(config) return { grp: {name:",
". import comparison from . import random def get_kankeiforms(config): init(config) return KankeiForm.registry def",
"we want to present information about `querying` and not the config :return: \"\"\"",
"from . import exploration from . import comparison from . import random def",
"get_kankeiforms(config): init(config) return KankeiForm.registry def get_kankeiforms_dict(config): \"\"\" note:: currently simply forward query config,",
"KankeiForm.timeout = config.DB_TIMEOUT_SEC from . import exploration from . import comparison from .",
"want to present information about `querying` and not the config :return: \"\"\" init(config)",
"components.kankeiforms.kankeiform import KankeiForm def init(config): KankeiForm.timeout = config.DB_TIMEOUT_SEC from . import exploration from",
"information about `querying` and not the config :return: \"\"\" init(config) return { grp:",
"import random def get_kankeiforms(config): init(config) return KankeiForm.registry def get_kankeiforms_dict(config): \"\"\" note:: currently simply",
"def init(config): KankeiForm.timeout = config.DB_TIMEOUT_SEC from . import exploration from . import comparison",
"currently simply forward query config, however it is not ideal since we want",
"def get_kankeiforms_dict(config): \"\"\" note:: currently simply forward query config, however it is not",
"return { grp: {name: content.asdict() for name, content in content.items()} for grp, content",
". import exploration from . import comparison from . import random def get_kankeiforms(config):",
"comparison from . import random def get_kankeiforms(config): init(config) return KankeiForm.registry def get_kankeiforms_dict(config): \"\"\"",
"{ grp: {name: content.asdict() for name, content in content.items()} for grp, content in",
". import random def get_kankeiforms(config): init(config) return KankeiForm.registry def get_kankeiforms_dict(config): \"\"\" note:: currently",
"forward query config, however it is not ideal since we want to present",
"`querying` and not the config :return: \"\"\" init(config) return { grp: {name: content.asdict()",
"is not ideal since we want to present information about `querying` and not",
"since we want to present information about `querying` and not the config :return:",
"init(config) return KankeiForm.registry def get_kankeiforms_dict(config): \"\"\" note:: currently simply forward query config, however",
"get_kankeiforms_dict(config): \"\"\" note:: currently simply forward query config, however it is not ideal",
"config :return: \"\"\" init(config) return { grp: {name: content.asdict() for name, content in",
"from . import comparison from . import random def get_kankeiforms(config): init(config) return KankeiForm.registry",
"config, however it is not ideal since we want to present information about",
"KankeiForm.registry def get_kankeiforms_dict(config): \"\"\" note:: currently simply forward query config, however it is",
"import comparison from . import random def get_kankeiforms(config): init(config) return KankeiForm.registry def get_kankeiforms_dict(config):",
"\"\"\" note:: currently simply forward query config, however it is not ideal since",
"\"\"\" init(config) return { grp: {name: content.asdict() for name, content in content.items()} for",
"not ideal since we want to present information about `querying` and not the",
"import KankeiForm def init(config): KankeiForm.timeout = config.DB_TIMEOUT_SEC from . import exploration from .",
"exploration from . import comparison from . import random def get_kankeiforms(config): init(config) return",
"ideal since we want to present information about `querying` and not the config",
"note:: currently simply forward query config, however it is not ideal since we",
"the config :return: \"\"\" init(config) return { grp: {name: content.asdict() for name, content",
"it is not ideal since we want to present information about `querying` and",
"return KankeiForm.registry def get_kankeiforms_dict(config): \"\"\" note:: currently simply forward query config, however it",
"<reponame>BigJerBD/Kankei-Backend<gh_stars>0 from components.kankeiforms.kankeiform import KankeiForm def init(config): KankeiForm.timeout = config.DB_TIMEOUT_SEC from . import",
"to present information about `querying` and not the config :return: \"\"\" init(config) return",
"present information about `querying` and not the config :return: \"\"\" init(config) return {",
"KankeiForm def init(config): KankeiForm.timeout = config.DB_TIMEOUT_SEC from . import exploration from . import",
"def get_kankeiforms(config): init(config) return KankeiForm.registry def get_kankeiforms_dict(config): \"\"\" note:: currently simply forward query",
"and not the config :return: \"\"\" init(config) return { grp: {name: content.asdict() for",
"grp: {name: content.asdict() for name, content in content.items()} for grp, content in KankeiForm.registry.items()",
"query config, however it is not ideal since we want to present information",
"however it is not ideal since we want to present information about `querying`",
"init(config): KankeiForm.timeout = config.DB_TIMEOUT_SEC from . import exploration from . import comparison from"
] |
[
"roll): self._rolls.append(roll) def clear_rolls(self): self._rolls = [] @property def rolls(self): return self._rolls @property",
"Roll import Roll class Roller: def __init__(self, user): self._rolls = [] self._user =",
"self._rolls = [] @property def rolls(self): return self._rolls @property def user(self): return self._user",
"clear_rolls(self): self._rolls = [] @property def rolls(self): return self._rolls @property def user(self): return",
"user): self._rolls = [] self._user = user def add_roll(self, roll): self._rolls.append(roll) def clear_rolls(self):",
"add_roll(self, roll): self._rolls.append(roll) def clear_rolls(self): self._rolls = [] @property def rolls(self): return self._rolls",
"def __init__(self, user): self._rolls = [] self._user = user def add_roll(self, roll): self._rolls.append(roll)",
"<gh_stars>0 from Roll import Roll class Roller: def __init__(self, user): self._rolls = []",
"= [] self._user = user def add_roll(self, roll): self._rolls.append(roll) def clear_rolls(self): self._rolls =",
"def clear_rolls(self): self._rolls = [] @property def rolls(self): return self._rolls @property def user(self):",
"self._user = user def add_roll(self, roll): self._rolls.append(roll) def clear_rolls(self): self._rolls = [] @property",
"self._rolls = [] self._user = user def add_roll(self, roll): self._rolls.append(roll) def clear_rolls(self): self._rolls",
"= user def add_roll(self, roll): self._rolls.append(roll) def clear_rolls(self): self._rolls = [] @property def",
"self._rolls.append(roll) def clear_rolls(self): self._rolls = [] @property def rolls(self): return self._rolls @property def",
"__init__(self, user): self._rolls = [] self._user = user def add_roll(self, roll): self._rolls.append(roll) def",
"Roll class Roller: def __init__(self, user): self._rolls = [] self._user = user def",
"class Roller: def __init__(self, user): self._rolls = [] self._user = user def add_roll(self,",
"from Roll import Roll class Roller: def __init__(self, user): self._rolls = [] self._user",
"[] self._user = user def add_roll(self, roll): self._rolls.append(roll) def clear_rolls(self): self._rolls = []",
"Roller: def __init__(self, user): self._rolls = [] self._user = user def add_roll(self, roll):",
"import Roll class Roller: def __init__(self, user): self._rolls = [] self._user = user",
"def add_roll(self, roll): self._rolls.append(roll) def clear_rolls(self): self._rolls = [] @property def rolls(self): return",
"user def add_roll(self, roll): self._rolls.append(roll) def clear_rolls(self): self._rolls = [] @property def rolls(self):"
] |
[
"np.concatenate((r1,r2,r3))/100000.0 m,s = blockavg(r[:,1]) print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp =",
"osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude') plt.errorbar(osmp_c36[:,0],osmp_c36[:,1],yerr=osmp_c36[:,2],marker='o',markersize=5,capsize=3,label='c36') plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure",
"osmp = [] f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('# %8s %10s %10s\\n'%('Conc (M)','OsmP (bar)','Error'))",
"%10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp = np.array(osmp) f.close() # plot plt.figure() plt.title(method.upper()+': '+mol1.upper()+' - '+mol2.upper())",
"plt.figure() plt.title(mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude') plt.errorbar(osmp_c36[:,0],osmp_c36[:,1],yerr=osmp_c36[:,2],marker='o',markersize=5,capsize=3,label='c36') plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.legend() plt.tight_layout()",
"print('# %8s %10s %10s'%('Conc (M)','OsmP (bar)','Error')) for d in dirs: c = d.split(\"_\")[2]",
"plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2))",
"mol2 = str(argv[1]), str(argv[2]) sysname = mol1+'_'+mol2 def blockavg(x,nblocks=30): lblock = int(len(x)/nblocks) m",
"matplotlib.pyplot as plt import glob from sys import argv from os.path import exists",
"glob from sys import argv from os.path import exists as file_exists methods =",
"= np.array(osmp) f.close() # plot plt.figure() plt.title(method.upper()+': '+mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)')",
"['drude', 'c36'] mol1, mol2 = str(argv[1]), str(argv[2]) sysname = mol1+'_'+mol2 def blockavg(x,nblocks=30): lblock",
"(i+1)*lblock m.append(np.mean(x[start:end])) m = np.array(m) return np.mean(m), np.std(m) for method in methods: dirs",
"= np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r = np.concatenate((r1,r2,r3))/100000.0 m,s =",
"= np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r = np.concatenate((r1,r2,r3))/100000.0 m,s = blockavg(r[:,1]) print(\"%10.1f %10.3f",
"plt.title(method.upper()+': '+mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close()",
"(bar)','Error')) print('# %8s %10s %10s'%('Conc (M)','OsmP (bar)','Error')) for d in dirs: c =",
"as plt import glob from sys import argv from os.path import exists as",
"print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp = np.array(osmp) f.close() # plot",
"i*lblock end = (i+1)*lblock m.append(np.mean(x[start:end])) m = np.array(m) return np.mean(m), np.std(m) for method",
"(M)','OsmP (bar)','Error')) print('# %8s %10s %10s'%('Conc (M)','OsmP (bar)','Error')) for d in dirs: c",
"c = d.split(\"_\")[2] r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r",
"import argv from os.path import exists as file_exists methods = ['drude', 'c36'] mol1,",
"and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude')",
"np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r = np.concatenate((r1,r2,r3))/100000.0 m,s = blockavg(r[:,1])",
"numpy as np import matplotlib.pyplot as plt import glob from sys import argv",
"= ['drude', 'c36'] mol1, mol2 = str(argv[1]), str(argv[2]) sysname = mol1+'_'+mol2 def blockavg(x,nblocks=30):",
"- '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude') plt.errorbar(osmp_c36[:,0],osmp_c36[:,1],yerr=osmp_c36[:,2],marker='o',markersize=5,capsize=3,label='c36') plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.legend() plt.tight_layout() plt.savefig('OSMP_%s_%s_both.png'%(mol1,mol2)) plt.close()",
"import numpy as np import matplotlib.pyplot as plt import glob from sys import",
"np.mean(m), np.std(m) for method in methods: dirs = sorted(glob.glob('%s_at_*'%(method))) if len(dirs) == 0:",
"r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r = np.concatenate((r1,r2,r3))/100000.0 m,s = blockavg(r[:,1]) print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f",
"np.array(m) return np.mean(m), np.std(m) for method in methods: dirs = sorted(glob.glob('%s_at_*'%(method))) if len(dirs)",
"dirs: c = d.split(\"_\")[2] r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c))",
"np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude') plt.errorbar(osmp_c36[:,0],osmp_c36[:,1],yerr=osmp_c36[:,2],marker='o',markersize=5,capsize=3,label='c36') plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.legend()",
"if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+' -",
"np.std(m) for method in methods: dirs = sorted(glob.glob('%s_at_*'%(method))) if len(dirs) == 0: continue",
"= i*lblock end = (i+1)*lblock m.append(np.mean(x[start:end])) m = np.array(m) return np.mean(m), np.std(m) for",
"= [] f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('# %8s %10s %10s\\n'%('Conc (M)','OsmP (bar)','Error')) print('#",
"plt.title(mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude') plt.errorbar(osmp_c36[:,0],osmp_c36[:,1],yerr=osmp_c36[:,2],marker='o',markersize=5,capsize=3,label='c36') plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.legend() plt.tight_layout() plt.savefig('OSMP_%s_%s_both.png'%(mol1,mol2))",
"for i in range(nblocks): start = i*lblock end = (i+1)*lblock m.append(np.mean(x[start:end])) m =",
"= int(len(x)/nblocks) m = [] for i in range(nblocks): start = i*lblock end",
"m = np.array(m) return np.mean(m), np.std(m) for method in methods: dirs = sorted(glob.glob('%s_at_*'%(method)))",
"m,s = blockavg(r[:,1]) print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp = np.array(osmp)",
"r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r = np.concatenate((r1,r2,r3))/100000.0 m,s",
"%8s %10s %10s\\n'%('Conc (M)','OsmP (bar)','Error')) print('# %8s %10s %10s'%('Conc (M)','OsmP (bar)','Error')) for d",
"np.array(osmp) f.close() # plot plt.figure() plt.title(method.upper()+': '+mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)') plt.ylabel('Osmotic",
"methods: dirs = sorted(glob.glob('%s_at_*'%(method))) if len(dirs) == 0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp = []",
"in range(nblocks): start = i*lblock end = (i+1)*lblock m.append(np.mean(x[start:end])) m = np.array(m) return",
"# plot plt.figure() plt.title(method.upper()+': '+mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)')",
"- '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2))",
"f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('# %8s %10s %10s\\n'%('Conc (M)','OsmP (bar)','Error')) print('# %8s %10s",
"file_exists methods = ['drude', 'c36'] mol1, mol2 = str(argv[1]), str(argv[2]) sysname = mol1+'_'+mol2",
"= sorted(glob.glob('%s_at_*'%(method))) if len(dirs) == 0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp = [] f =",
"open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('# %8s %10s %10s\\n'%('Conc (M)','OsmP (bar)','Error')) print('# %8s %10s %10s'%('Conc (M)','OsmP",
"'c36'] mol1, mol2 = str(argv[1]), str(argv[2]) sysname = mol1+'_'+mol2 def blockavg(x,nblocks=30): lblock =",
"%10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp = np.array(osmp) f.close() # plot plt.figure() plt.title(method.upper()+':",
"file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude') plt.errorbar(osmp_c36[:,0],osmp_c36[:,1],yerr=osmp_c36[:,2],marker='o',markersize=5,capsize=3,label='c36')",
"len(dirs) == 0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp = [] f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('#",
"import matplotlib.pyplot as plt import glob from sys import argv from os.path import",
"[] f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('# %8s %10s %10s\\n'%('Conc (M)','OsmP (bar)','Error')) print('# %8s",
"= np.concatenate((r1,r2,r3))/100000.0 m,s = blockavg(r[:,1]) print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp",
"%10s %10s\\n'%('Conc (M)','OsmP (bar)','Error')) print('# %8s %10s %10s'%('Conc (M)','OsmP (bar)','Error')) for d in",
"lblock = int(len(x)/nblocks) m = [] for i in range(nblocks): start = i*lblock",
"'+mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if",
"np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude') plt.errorbar(osmp_c36[:,0],osmp_c36[:,1],yerr=osmp_c36[:,2],marker='o',markersize=5,capsize=3,label='c36') plt.xlabel('Concentration (M)') plt.ylabel('Osmotic",
"as file_exists methods = ['drude', 'c36'] mol1, mol2 = str(argv[1]), str(argv[2]) sysname =",
"return np.mean(m), np.std(m) for method in methods: dirs = sorted(glob.glob('%s_at_*'%(method))) if len(dirs) ==",
"in dirs: c = d.split(\"_\")[2] r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 =",
"i in range(nblocks): start = i*lblock end = (i+1)*lblock m.append(np.mean(x[start:end])) m = np.array(m)",
"'+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and",
"= np.array(m) return np.mean(m), np.std(m) for method in methods: dirs = sorted(glob.glob('%s_at_*'%(method))) if",
"method in methods: dirs = sorted(glob.glob('%s_at_*'%(method))) if len(dirs) == 0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp",
"[] for i in range(nblocks): start = i*lblock end = (i+1)*lblock m.append(np.mean(x[start:end])) m",
"%10s %10s'%('Conc (M)','OsmP (bar)','Error')) for d in dirs: c = d.split(\"_\")[2] r1 =",
"== 0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp = [] f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('# %8s",
"plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure()",
"plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)):",
"end = (i+1)*lblock m.append(np.mean(x[start:end])) m = np.array(m) return np.mean(m), np.std(m) for method in",
"sorted(glob.glob('%s_at_*'%(method))) if len(dirs) == 0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp = [] f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method),",
"argv from os.path import exists as file_exists methods = ['drude', 'c36'] mol1, mol2",
"sys import argv from os.path import exists as file_exists methods = ['drude', 'c36']",
"= np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude') plt.errorbar(osmp_c36[:,0],osmp_c36[:,1],yerr=osmp_c36[:,2],marker='o',markersize=5,capsize=3,label='c36') plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)')",
"in methods: dirs = sorted(glob.glob('%s_at_*'%(method))) if len(dirs) == 0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp =",
"d.split(\"_\")[2] r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r = np.concatenate((r1,r2,r3))/100000.0",
"= blockavg(r[:,1]) print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp = np.array(osmp) f.close()",
"import exists as file_exists methods = ['drude', 'c36'] mol1, mol2 = str(argv[1]), str(argv[2])",
"= str(argv[1]), str(argv[2]) sysname = mol1+'_'+mol2 def blockavg(x,nblocks=30): lblock = int(len(x)/nblocks) m =",
"= [] for i in range(nblocks): start = i*lblock end = (i+1)*lblock m.append(np.mean(x[start:end]))",
"(M)','OsmP (bar)','Error')) for d in dirs: c = d.split(\"_\")[2] r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2",
"= np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r = np.concatenate((r1,r2,r3))/100000.0 m,s = blockavg(r[:,1]) print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f",
"continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp = [] f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('# %8s %10s %10s\\n'%('Conc",
"np import matplotlib.pyplot as plt import glob from sys import argv from os.path",
"osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude') plt.errorbar(osmp_c36[:,0],osmp_c36[:,1],yerr=osmp_c36[:,2],marker='o',markersize=5,capsize=3,label='c36') plt.xlabel('Concentration",
"str(argv[2]) sysname = mol1+'_'+mol2 def blockavg(x,nblocks=30): lblock = int(len(x)/nblocks) m = [] for",
"%10s'%('Conc (M)','OsmP (bar)','Error')) for d in dirs: c = d.split(\"_\")[2] r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c))",
"if len(dirs) == 0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp = [] f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w')",
"= d.split(\"_\")[2] r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r =",
"= open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('# %8s %10s %10s\\n'%('Conc (M)','OsmP (bar)','Error')) print('# %8s %10s %10s'%('Conc",
"%10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp = np.array(osmp) f.close() # plot plt.figure()",
"(bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 =",
"= mol1+'_'+mol2 def blockavg(x,nblocks=30): lblock = int(len(x)/nblocks) m = [] for i in",
"m.append(np.mean(x[start:end])) m = np.array(m) return np.mean(m), np.std(m) for method in methods: dirs =",
"file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+' - '+mol2.upper())",
"Pressure (bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36",
"plt.ylabel('Osmotic Pressure (bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2))",
"plot plt.figure() plt.title(method.upper()+': '+mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.tight_layout()",
"blockavg(x,nblocks=30): lblock = int(len(x)/nblocks) m = [] for i in range(nblocks): start =",
"r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r = np.concatenate((r1,r2,r3))/100000.0 m,s = blockavg(r[:,1]) print(\"%10.1f",
"(bar)','Error')) for d in dirs: c = d.split(\"_\")[2] r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 =",
"%8s %10s %10s'%('Conc (M)','OsmP (bar)','Error')) for d in dirs: c = d.split(\"_\")[2] r1",
"'w') f.write('# %8s %10s %10s\\n'%('Conc (M)','OsmP (bar)','Error')) print('# %8s %10s %10s'%('Conc (M)','OsmP (bar)','Error'))",
"sysname = mol1+'_'+mol2 def blockavg(x,nblocks=30): lblock = int(len(x)/nblocks) m = [] for i",
"str(argv[1]), str(argv[2]) sysname = mol1+'_'+mol2 def blockavg(x,nblocks=30): lblock = int(len(x)/nblocks) m = []",
"osmp.append((float(c),m,s)) osmp = np.array(osmp) f.close() # plot plt.figure() plt.title(method.upper()+': '+mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3)",
"from sys import argv from os.path import exists as file_exists methods = ['drude',",
"for d in dirs: c = d.split(\"_\")[2] r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c))",
"exists as file_exists methods = ['drude', 'c36'] mol1, mol2 = str(argv[1]), str(argv[2]) sysname",
"plt.figure() plt.title(method.upper()+': '+mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method))",
"d in dirs: c = d.split(\"_\")[2] r1 = np.loadtxt('%s/osmp.%s_%s_%s.1.dat'%(d,mol1,mol2,c)) r2 = np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3",
"%10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp = np.array(osmp) f.close() # plot plt.figure() plt.title(method.upper()+': '+mol1.upper()+' -",
"f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp = np.array(osmp) f.close() # plot plt.figure() plt.title(method.upper()+': '+mol1.upper()+'",
"= np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp_drude[:,0],osmp_drude[:,1],yerr=osmp_drude[:,2],marker='o',markersize=5,capsize=3,label='drude') plt.errorbar(osmp_c36[:,0],osmp_c36[:,1],yerr=osmp_c36[:,2],marker='o',markersize=5,capsize=3,label='c36') plt.xlabel('Concentration (M)')",
"f.close() # plot plt.figure() plt.title(method.upper()+': '+mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure",
"(M)') plt.ylabel('Osmotic Pressure (bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude =",
"as np import matplotlib.pyplot as plt import glob from sys import argv from",
"range(nblocks): start = i*lblock end = (i+1)*lblock m.append(np.mean(x[start:end])) m = np.array(m) return np.mean(m),",
"int(len(x)/nblocks) m = [] for i in range(nblocks): start = i*lblock end =",
"dirs = sorted(glob.glob('%s_at_*'%(method))) if len(dirs) == 0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp = [] f",
"f.write('# %8s %10s %10s\\n'%('Conc (M)','OsmP (bar)','Error')) print('# %8s %10s %10s'%('Conc (M)','OsmP (bar)','Error')) for",
"osmp = np.array(osmp) f.close() # plot plt.figure() plt.title(method.upper()+': '+mol1.upper()+' - '+mol2.upper()) plt.errorbar(osmp[:,0],osmp[:,1],yerr=osmp[:,2],marker='o',markersize=5,capsize=3) plt.xlabel('Concentration",
"mol1+'_'+mol2 def blockavg(x,nblocks=30): lblock = int(len(x)/nblocks) m = [] for i in range(nblocks):",
"plt import glob from sys import argv from os.path import exists as file_exists",
"0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp = [] f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('# %8s %10s",
"for method in methods: dirs = sorted(glob.glob('%s_at_*'%(method))) if len(dirs) == 0: continue print(method.upper(),':',mol1.upper(),'-',mol2.upper())",
"m = [] for i in range(nblocks): start = i*lblock end = (i+1)*lblock",
"methods = ['drude', 'c36'] mol1, mol2 = str(argv[1]), str(argv[2]) sysname = mol1+'_'+mol2 def",
"%10s\\n'%('Conc (M)','OsmP (bar)','Error')) print('# %8s %10s %10s'%('Conc (M)','OsmP (bar)','Error')) for d in dirs:",
"plt.xlabel('Concentration (M)') plt.ylabel('Osmotic Pressure (bar)') plt.tight_layout() plt.savefig('OSMP_%s_%s_%s.png'%(mol1,mol2,method)) plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude",
"start = i*lblock end = (i+1)*lblock m.append(np.mean(x[start:end])) m = np.array(m) return np.mean(m), np.std(m)",
"np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r = np.concatenate((r1,r2,r3))/100000.0 m,s = blockavg(r[:,1]) print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s))",
"r = np.concatenate((r1,r2,r3))/100000.0 m,s = blockavg(r[:,1]) print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s))",
"plt.close() if file_exists('OSMP_%s_%s_drude.dat'%(mol1,mol2)) and file_exists('OSMP_%s_%s_c36.dat'%(mol1,mol2)): osmp_drude = np.loadtxt('OSMP_%s_%s_drude.dat'%(mol1,mol2)) osmp_c36 = np.loadtxt('OSMP_%s_%s_c36.dat'%(mol1,mol2)) plt.figure() plt.title(mol1.upper()+'",
"np.loadtxt('%s/osmp.%s_%s_%s.2.dat'%(d,mol1,mol2,c)) r3 = np.loadtxt('%s/osmp.%s_%s_%s.3.dat'%(d,mol1,mol2,c)) r = np.concatenate((r1,r2,r3))/100000.0 m,s = blockavg(r[:,1]) print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s))",
"os.path import exists as file_exists methods = ['drude', 'c36'] mol1, mol2 = str(argv[1]),",
"def blockavg(x,nblocks=30): lblock = int(len(x)/nblocks) m = [] for i in range(nblocks): start",
"import glob from sys import argv from os.path import exists as file_exists methods",
"= (i+1)*lblock m.append(np.mean(x[start:end])) m = np.array(m) return np.mean(m), np.std(m) for method in methods:",
"mol1, mol2 = str(argv[1]), str(argv[2]) sysname = mol1+'_'+mol2 def blockavg(x,nblocks=30): lblock = int(len(x)/nblocks)",
"blockavg(r[:,1]) print(\"%10.1f %10.3f %10.3f\"%(float(c),m,s)) f.write(\"%10.1f %10.3f %10.3f\\n\"%(float(c),m,s)) osmp.append((float(c),m,s)) osmp = np.array(osmp) f.close() #",
"from os.path import exists as file_exists methods = ['drude', 'c36'] mol1, mol2 =",
"print(method.upper(),':',mol1.upper(),'-',mol2.upper()) osmp = [] f = open('OSMP_%s_%s_%s.dat'%(mol1,mol2,method), 'w') f.write('# %8s %10s %10s\\n'%('Conc (M)','OsmP"
] |
[
"tf.int64, default_value=0), 'frame_2/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'path': tf.io.FixedLenFeature((), tf.string, default_value=''), } return feature_map",
"max_examples > 0: return dataset.take(max_examples) return dataset @gin.configurable('training_dataset') def create_training_dataset( batch_size: int, file:",
"KIND, either express or implied. # See the License for the specific language",
"augment. Returns: Example with augmentation applied to selected images. \"\"\" if augmentation_keys is",
"Unless required by applicable law or agreed to in writing, software # distributed",
"with files[], use crop_sizes[] instead.' ) tables = [] for file, crop_size in",
"tfrecord.\"\"\" dataset = tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) # pylint: disable=g-long-lambda dataset = dataset.interleave( lambda x:",
"using tensorflow's random cropping. max_examples: If > 0, truncate the dataset to 'max_examples'",
"= tf.concat(image_to_crop, axis=-1) cropped_images = _random_crop_images(crop_size, stacked_images, sum(channels)) cropped_images = tf.split( cropped_images, num_or_size_splits=channels,",
"batch_size: The number of images to batch per example. file: (deprecated) A path",
"axis, and perform a random crop once. image_to_crop = [example[key] for key in",
"create_training_dataset this function makes sure that the examples for each dataset are always",
"in a format produced by frame_interpolation/datasets/create_*_tfrecord.py The (batch_size, crop_size, max_examples) are specified for",
"augmentation_keys is None: augmentation_keys = ['<KEY>'] # Apply each augmentation in sequence augmented_images",
"is not None: dataset = dataset.map( lambda x: apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size",
"tf.split( cropped_images, num_or_size_splits=channels, axis=-1) for key, cropped_image in zip(crop_keys, cropped_images): example[key] = cropped_image",
"Deprecated: use 'files' and 'crop_sizes' instead. crop_sizes: List of crop sizes. If >",
"eval datasets. Args: batch_size: The number of images to batch per example. files:",
"to crop images to. This value is used for both height and width.",
"'frame_2/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_2/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/width':",
"opposed to create_training_dataset this function makes sure that the examples for each dataset",
"cropped_images = _random_crop_images(crop_size, stacked_images, sum(channels)) cropped_images = tf.split( cropped_images, num_or_size_splits=channels, axis=-1) for key,",
"default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'path': tf.io.FixedLenFeature((), tf.string, default_value=''),",
"output_dict def _random_crop_images(crop_size: int, images: tf.Tensor, total_channel_size: int) -> tf.Tensor: \"\"\"Crops the tensor",
"used with files[], use crop_sizes[] instead.' ) tables = [] for file, crop_size",
"filename: The sharded filepath. Returns: A list of filepaths for each file in",
"# https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing,",
"fractional time value of frame_1 is not included in our tfrecords, # but",
"makes sure that the examples for each dataset are always read in a",
"crop_keys is None: crop_keys = ['x0', 'x1', 'y'] channels = [3, 3, 3]",
"dataset = dataset.prefetch(buffer_size=2) if max_examples > 0: return dataset.take(max_examples) return dataset @gin.configurable('training_dataset') def",
"return _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size) else: if not crop_sizes or len(crop_sizes) !=",
"The size to crop images to. This value is used for both height",
"'x1', 'y'] channels = [3, 3, 3] # Stack images along channel axis,",
"to a sharded tfrecord in <tfrecord>@N format. Deprecated. Use 'files' instead. files: A",
"function makes sure that the examples for each dataset are always read in",
"\"\"\" if augmentation_keys is None: augmentation_keys = ['<KEY>'] # Apply each augmentation in",
"the ground truth 'time'=[0,1] in a dictionary of tensors. \"\"\" if file: logging.warning('gin-configurable",
"dataset @gin.configurable('training_dataset') def create_training_dataset( batch_size: int, file: Optional[str] = None, files: Optional[List[str]] =",
"# limitations under the License. # ============================================================================== \"\"\"Dataset creation for frame interpolation.\"\"\" from",
"Args: filename: The sharded filepath. Returns: A list of filepaths for each file",
"this file except in compliance with the License. # You may obtain a",
"path to a sharded tfrecord in <tfrecord>@N format. Deprecated. Use 'files' instead. files:",
"examples for each dataset are always read in a deterministic (same) order. Each",
"serialized sample. Args: sample: A serialized tf.Example to be parsed. Returns: dictionary containing",
"tf.string, default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((), tf.string,",
"each file in the shard. \"\"\" base, count = filename.split('@') count = int(count)",
"= [3, 3, 3] # Stack images along channel axis, and perform a",
"for augmentation_function in augmentation_fns.values(): augmented_images = augmentation_function(augmented_images) for key in augmentation_keys: example[key] =",
"contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of",
"to selected images. \"\"\" if crop_keys is None: crop_keys = ['x0', 'x1', 'y']",
"= dataset.interleave( lambda x: _create_from_tfrecord( batch_size, file=x, augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode) #",
"This can be useful for speeding up evaluation loop in case the tfrecord",
"of name to tensorflow dataset for accessing examples that contain the input images",
"= dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform data_augmentation before cropping and batching if augmentation_fns",
"tfrecords in <tfrecord>@N format. crop_size: (deprecated) If > 0, images are cropped to",
"for extracting the frame triplet.\"\"\" feature_map = { 'frame_0/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_0/format':",
"images along channel axis, and perform a random crop once. image_to_crop = [example[key]",
"-> tf.data.Dataset: \"\"\"Creates a dataset from a sharded tfrecord.\"\"\" dataset = tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file))",
"disable=g-long-lambda dataset = dataset.interleave( lambda x: _create_from_tfrecord( batch_size, file=x, augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not",
"x crop_size using tensorflow's random cropping. max_examples: If > 0, truncate the dataset",
"map for extracting the frame triplet.\"\"\" feature_map = { 'frame_0/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''),",
"= None): \"\"\"Random crops selected images in the example to given size and",
"> 0: return dataset.take(max_examples) return dataset @gin.configurable('training_dataset') def create_training_dataset( batch_size: int, file: Optional[str]",
"of tensors. \"\"\" if file: logging.warning('gin-configurable training_dataset.file is deprecated. ' 'Use training_dataset.files instead.')",
"augmentation_keys} for augmentation_function in augmentation_fns.values(): augmented_images = augmentation_function(augmented_images) for key in augmentation_keys: example[key]",
"random offset to the given size.\"\"\" if crop_size > 0: crop_shape = tf.constant([crop_size,",
"original mid frame filepath for identifying examples. 'path': features['path'], } return output_dict def",
"= tf.constant([crop_size, crop_size, total_channel_size]) images = tf.image.random_crop(images, crop_shape) return images def crop_example(example: tf.Tensor,",
"ANY KIND, either express or implied. # See the License for the specific",
"'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), # The fractional time value of frame_1",
"Optional[List[str]] = None): \"\"\"Random crops selected images in the example to given size",
"images. \"\"\" if augmentation_keys is None: augmentation_keys = ['<KEY>'] # Apply each augmentation",
"import Callable, Dict, List, Optional from absl import logging import gin.tf import tensorflow",
"offset to the given size.\"\"\" if crop_size > 0: crop_shape = tf.constant([crop_size, crop_size,",
"augmentation_keys: example[key] = augmented_images[key] return example def _create_from_tfrecord(batch_size, file, augmentation_fns, crop_size) -> tf.data.Dataset:",
"serialized tf.Example to be parsed. Returns: dictionary containing the following: encoded_image image_height image_width",
"very large. Returns: A dict of name to tensorflow dataset for accessing examples",
"value of frame_1 is not included in our tfrecords, # but is always",
"= dataset.prefetch(buffer_size=2) if max_examples > 0: return dataset.take(max_examples) return dataset @gin.configurable('training_dataset') def create_training_dataset(",
"example[key] = augmented_images[key] return example def _create_from_tfrecord(batch_size, file, augmentation_fns, crop_size) -> tf.data.Dataset: \"\"\"Creates",
"else: if not crop_sizes or len(crop_sizes) != len(files): raise ValueError('Please pass crop_sizes[] with",
"num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size, drop_remainder=True) return dataset def _generate_sharded_filenames(filename: str) -> List[str]: \"\"\"Generates",
"in sequence augmented_images = {key: example[key] for key in augmentation_keys} for augmentation_function in",
"crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size, drop_remainder=True) return dataset def _generate_sharded_filenames(filename: str) ->",
"lambda x: _create_from_tfrecord( batch_size, file=x, augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode) # pylint: enable=g-long-lambda",
"augmentation_keys: The images in the input example to augment. Returns: Example with augmentation",
"to be specificed, so # we insert it here. 'time': 0.5, # Store",
"containing the following: encoded_image image_height image_width \"\"\" feature_map = _create_feature_map() features = tf.io.parse_single_example(sample,",
"example. files: List of paths to a sharded tfrecord in <tfrecord>@N format. names:",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"str) -> List[str]: \"\"\"Generates filenames of the each file in the sharded filepath.",
"filenames of the each file in the sharded filepath. Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args:",
"if augmentation_keys is None: augmentation_keys = ['<KEY>'] # Apply each augmentation in sequence",
"in zip(files, crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size)) return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def",
"The number of images to batch per example. file: (deprecated) A path to",
"this to be specificed, so # we insert it here. 'time': 0.5, #",
"if crop_size > 0: raise ValueError( 'crop_size should not be used with files[],",
"dataset = dataset.interleave( lambda x: _create_from_tfrecord( batch_size, file=x, augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode)",
"LLC # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"logging.warning('gin-configurable training_dataset.file is deprecated. ' 'Use training_dataset.files instead.') return _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns,",
"int, files: List[str], names: List[str], crop_size: int = -1, max_examples: int = -1)",
"tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The",
"to be parsed. Returns: dictionary containing the following: encoded_image image_height image_width \"\"\" feature_map",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"crop_shape) return images def crop_example(example: tf.Tensor, crop_size: int, crop_keys: Optional[List[str]] = None): \"\"\"Random",
"for the evaluation set is very large. Returns: A dict of name to",
"dataset.batch(batch_size, drop_remainder=True) return dataset def _generate_sharded_filenames(filename: str) -> List[str]: \"\"\"Generates filenames of the",
"tf.data.Dataset: \"\"\"Creates a dataset from a sharded tfrecord.\"\"\" dataset = tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) #",
"lambda x: apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size > 0: dataset = dataset.map( lambda",
"Returns: Example with cropping applied to selected images. \"\"\" if crop_keys is None:",
"images = tf.image.random_crop(images, crop_shape) return images def crop_example(example: tf.Tensor, crop_size: int, crop_keys: Optional[List[str]]",
"_create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size)) return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def create_eval_datasets(batch_size: int, files: List[str],",
"OF ANY KIND, either express or implied. # See the License for the",
"Store the original mid frame filepath for identifying examples. 'path': features['path'], } return",
"and 'crop_sizes' instead. crop_sizes: List of crop sizes. If > 0, images are",
"a dictionary of tensors. \"\"\" return { name: _create_from_sharded_tfrecord(batch_size, False, file, None, crop_size,",
"selected image keys. Args: augmentation_fns: A Dict of Callables to data augmentation functions.",
"> 0, truncate the dataset to 'max_examples' in length. This can be useful",
"example: tf.Tensor, augmentation_keys: Optional[List[str]] = None) -> tf.Tensor: \"\"\"Applies random augmentation in succession",
"tensors. \"\"\" if file: logging.warning('gin-configurable training_dataset.file is deprecated. ' 'Use training_dataset.files instead.') return",
"= -1, max_examples: int = -1) -> Dict[str, tf.data.Dataset]: \"\"\"Creates the evaluation datasets.",
"the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed",
"The model will expect this to be specificed, so # we insert it",
"for both height and width. crop_keys: The images in the input example to",
"You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless",
"cropping applied to selected images. \"\"\" if crop_keys is None: crop_keys = ['x0',",
"x: crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size, drop_remainder=True) return dataset def _generate_sharded_filenames(filename: str)",
"sharded tfrecord.\"\"\" dataset = tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) # pylint: disable=g-long-lambda dataset = dataset.interleave( lambda",
"x: _create_from_tfrecord( batch_size, file=x, augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode) # pylint: enable=g-long-lambda dataset",
"tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_0/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_0/width': tf.io.FixedLenFeature((),",
"create_training_dataset( batch_size: int, file: Optional[str] = None, files: Optional[List[str]] = None, crop_size: int",
"> 0: raise ValueError( 'crop_size should not be used with files[], use crop_sizes[]",
"example[key] for key in augmentation_keys} for augmentation_function in augmentation_fns.values(): augmented_images = augmentation_function(augmented_images) for",
"0: return dataset.take(max_examples) return dataset @gin.configurable('training_dataset') def create_training_dataset( batch_size: int, file: Optional[str] =",
"} return feature_map def _parse_example(sample): \"\"\"Parses a serialized sample. Args: sample: A serialized",
"the shard. \"\"\" base, count = filename.split('@') count = int(count) return ['{}-{:05d}-of-{:05d}'.format(base, i,",
"that the examples for each dataset are always read in a deterministic (same)",
"paths to sharded tfrecords in <tfrecord>@N format. crop_size: (deprecated) If > 0, images",
"of eval datasets. crop_size: If > 0, images are cropped to crop_size x",
"to 'max_examples' in length. This can be useful for speeding up evaluation loop",
"default_value=0), 'path': tf.io.FixedLenFeature((), tf.string, default_value=''), } return feature_map def _parse_example(sample): \"\"\"Parses a serialized",
"in <tfrecord>@N format. crop_size: (deprecated) If > 0, images are cropped to crop_size",
"the input images 'x0', 'x1', ground truth 'y' and time of the ground",
"'time': 0.5, # Store the original mid frame filepath for identifying examples. 'path':",
"for all eval datasets. Args: batch_size: The number of images to batch per",
"for speeding up evaluation loop in case the tfrecord for the evaluation set",
"evaluation datasets. As opposed to create_training_dataset this function makes sure that the examples",
"parsed. Returns: dictionary containing the following: encoded_image image_height image_width \"\"\" feature_map = _create_feature_map()",
"Args: augmentation_fns: A Dict of Callables to data augmentation functions. example: Input tensor",
"obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by",
"= augmented_images[key] return example def _create_from_tfrecord(batch_size, file, augmentation_fns, crop_size) -> tf.data.Dataset: \"\"\"Creates a",
"\"\"\"Creates a dataset from TFRecord.\"\"\" dataset = tf.data.TFRecordDataset(file) dataset = dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE)",
"to crop_size x crop_size using tensorflow's random cropping. Deprecated: use 'files' and 'crop_sizes'",
"crop_shape = tf.constant([crop_size, crop_size, total_channel_size]) images = tf.image.random_crop(images, crop_shape) return images def crop_example(example:",
"in augmentation_keys} for augmentation_function in augmentation_fns.values(): augmented_images = augmentation_function(augmented_images) for key in augmentation_keys:",
"the dataset to 'max_examples' in length. This can be useful for speeding up",
"by frame_interpolation/datasets/create_*_tfrecord.py The (batch_size, crop_size, max_examples) are specified for all eval datasets. Args:",
"images to. This value is used for both height and width. crop_keys: The",
"tf.Tensor]], example: tf.Tensor, augmentation_keys: Optional[List[str]] = None) -> tf.Tensor: \"\"\"Applies random augmentation in",
"to selected images. \"\"\" if augmentation_keys is None: augmentation_keys = ['<KEY>'] # Apply",
"random cropping. Deprecated: use 'files' and 'crop_sizes' instead. crop_sizes: List of crop sizes.",
"dataset are always read in a deterministic (same) order. Each given tfrecord should",
"names: List of names of eval datasets. crop_size: If > 0, images are",
"augmentation_keys = ['<KEY>'] # Apply each augmentation in sequence augmented_images = {key: example[key]",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"if crop_keys is None: crop_keys = ['x0', 'x1', 'y'] channels = [3, 3,",
"Deprecated. Use 'files' instead. files: A list of paths to sharded tfrecords in",
"crop_keys] stacked_images = tf.concat(image_to_crop, axis=-1) cropped_images = _random_crop_images(crop_size, stacked_images, sum(channels)) cropped_images = tf.split(",
"under the License. # ============================================================================== \"\"\"Dataset creation for frame interpolation.\"\"\" from typing import",
"-> tf.data.Dataset: \"\"\"Creates a dataset from TFRecord.\"\"\" dataset = tf.data.TFRecordDataset(file) dataset = dataset.map(",
"zip(files, crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size)) return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def create_eval_datasets(batch_size:",
"with cropping applied to selected images. \"\"\" if crop_keys is None: crop_keys =",
"return dataset @gin.configurable('training_dataset') def create_training_dataset( batch_size: int, file: Optional[str] = None, files: Optional[List[str]]",
"= None, files: Optional[List[str]] = None, crop_size: int = -1, crop_sizes: Optional[List[int]] =",
"['{}-{:05d}-of-{:05d}'.format(base, i, count) for i in range(count)] def _create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns, crop_size,",
"'frame_2/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'path':",
"axis=-1) for key, cropped_image in zip(crop_keys, cropped_images): example[key] = cropped_image return example def",
"A Dict of Callables to data augmentation functions. Returns: A tensorflow dataset for",
"crop_size using tensorflow's random cropping. max_examples: If > 0, truncate the dataset to",
"\"\"\"Crops the tensor with random offset to the given size.\"\"\" if crop_size >",
"tf.Tensor, crop_size: int, crop_keys: Optional[List[str]] = None): \"\"\"Random crops selected images in the",
"crop_size: int, crop_keys: Optional[List[str]] = None): \"\"\"Random crops selected images in the example",
"Stack images along channel axis, and perform a random crop once. image_to_crop =",
"crop sizes. If > 0, images are cropped to crop_size x crop_size using",
"import gin.tf import tensorflow as tf def _create_feature_map() -> Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates the",
"default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_1/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((), tf.int64, default_value=0),",
"count = filename.split('@') count = int(count) return ['{}-{:05d}-of-{:05d}'.format(base, i, count) for i in",
"the frame triplet.\"\"\" feature_map = { 'frame_0/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_0/format': tf.io.FixedLenFeature((), tf.string,",
"Input tensor representing images to be augmented. augmentation_keys: The images in the input",
"a sharded tfrecord.\"\"\" dataset = tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) # pylint: disable=g-long-lambda dataset = dataset.interleave(",
"' 'Use training_dataset.files instead.') return _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size) else: if not",
"-1, max_examples: int = -1) -> Dict[str, tf.data.Dataset]: \"\"\"Creates the evaluation datasets. As",
"of images to batch per example. files: List of paths to a sharded",
"_create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns, crop_size, max_examples=-1) -> tf.data.Dataset: \"\"\"Creates a dataset from a",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"gin.tf import tensorflow as tf def _create_feature_map() -> Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates the feature",
"crop_sizes[] instead.' ) tables = [] for file, crop_size in zip(files, crop_sizes): tables.append(",
"instead.') return _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size) else: if not crop_sizes or len(crop_sizes)",
"True, file, augmentation_fns, crop_size) else: if not crop_sizes or len(crop_sizes) != len(files): raise",
"of paths to sharded tfrecords in <tfrecord>@N format. crop_size: (deprecated) If > 0,",
"0: crop_shape = tf.constant([crop_size, crop_size, total_channel_size]) images = tf.image.random_crop(images, crop_shape) return images def",
"of Callables to data augmentation functions. example: Input tensor representing images to be",
"Dict[str, Callable[..., tf.Tensor]], example: tf.Tensor, augmentation_keys: Optional[List[str]] = None) -> tf.Tensor: \"\"\"Applies random",
"not None: dataset = dataset.map( lambda x: apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size >",
"def _parse_example(sample): \"\"\"Parses a serialized sample. Args: sample: A serialized tf.Example to be",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"representing images to be augmented. augmentation_keys: The images in the input example to",
"to augment. Returns: Example with augmentation applied to selected images. \"\"\" if augmentation_keys",
"num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform data_augmentation before cropping and batching if augmentation_fns is not None:",
"[] for file, crop_size in zip(files, crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size))",
"@gin.configurable('eval_datasets') def create_eval_datasets(batch_size: int, files: List[str], names: List[str], crop_size: int = -1, max_examples:",
"keys. Args: augmentation_fns: A Dict of Callables to data augmentation functions. example: Input",
"may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required",
"required by applicable law or agreed to in writing, software # distributed under",
"crops selected images in the example to given size and keys. Args: example:",
"tensorflow dataset for accessing examples that contain the input images 'x0', 'x1', ground",
"at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in",
"in <tfrecord>@N format. Deprecated. Use 'files' instead. files: A list of paths to",
"If > 0, images are cropped to crop_size x crop_size using tensorflow's random",
"applicable law or agreed to in writing, software # distributed under the License",
"filepath. Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename: The sharded filepath. Returns: A list of",
"0, images are cropped to crop_size x crop_size using tensorflow's random cropping. max_examples:",
"cropping. Deprecated: use 'files' and 'crop_sizes' instead. crop_sizes: List of crop sizes. If",
"in the input example to augment. Returns: Example with augmentation applied to selected",
"is always at 0.5. The model will expect this to be specificed, so",
"None: augmentation_keys = ['<KEY>'] # Apply each augmentation in sequence augmented_images = {key:",
"return { name: _create_from_sharded_tfrecord(batch_size, False, file, None, crop_size, max_examples) for name, file in",
"time of the ground truth 'time'=[0,1] in a dictionary of tensors. \"\"\" return",
"in a dictionary of tensors. \"\"\" if file: logging.warning('gin-configurable training_dataset.file is deprecated. '",
"but is always at 0.5. The model will expect this to be specificed,",
"size.\"\"\" if crop_size > 0: crop_shape = tf.constant([crop_size, crop_size, total_channel_size]) images = tf.image.random_crop(images,",
"file, crop_size in zip(files, crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size)) return tf.data.experimental.sample_from_datasets(tables)",
"or agreed to in writing, software # distributed under the License is distributed",
"in the input example to crop. Returns: Example with cropping applied to selected",
"(deprecated) If > 0, images are cropped to crop_size x crop_size using tensorflow's",
"instead. crop_sizes: List of crop sizes. If > 0, images are cropped to",
"sharded filepath. Returns: A list of filepaths for each file in the shard.",
"ValueError('Please pass crop_sizes[] with training_dataset.files.') if crop_size > 0: raise ValueError( 'crop_size should",
"Optional from absl import logging import gin.tf import tensorflow as tf def _create_feature_map()",
"be useful for speeding up evaluation loop in case the tfrecord for the",
"key in augmentation_keys: example[key] = augmented_images[key] return example def _create_from_tfrecord(batch_size, file, augmentation_fns, crop_size)",
"'frame_0/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_0/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/encoded':",
"files: List[str], names: List[str], crop_size: int = -1, max_examples: int = -1) ->",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"here. 'time': 0.5, # Store the original mid frame filepath for identifying examples.",
"default_value=''), 'frame_1/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/width': tf.io.FixedLenFeature((), tf.int64, default_value=0),",
"dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform data_augmentation before cropping and batching if augmentation_fns is",
"ValueError( 'crop_size should not be used with files[], use crop_sizes[] instead.' ) tables",
"<tfrecord>@N format. names: List of names of eval datasets. crop_size: If > 0,",
"x: apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size > 0: dataset = dataset.map( lambda x:",
"given tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py The (batch_size,",
"batching if augmentation_fns is not None: dataset = dataset.map( lambda x: apply_data_augmentation(augmentation_fns, x),",
"will expect this to be specificed, so # we insert it here. 'time':",
"frame filepath for identifying examples. 'path': features['path'], } return output_dict def _random_crop_images(crop_size: int,",
"deterministic (same) order. Each given tfrecord should contain data in a format produced",
"(deprecated) A path to a sharded tfrecord in <tfrecord>@N format. Deprecated. Use 'files'",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"to data augmentation functions. example: Input tensor representing images to be augmented. augmentation_keys:",
"file: (deprecated) A path to a sharded tfrecord in <tfrecord>@N format. Deprecated. Use",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"crop_size, total_channel_size]) images = tf.image.random_crop(images, crop_shape) return images def crop_example(example: tf.Tensor, crop_size: int,",
"_parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform data_augmentation before cropping and batching if augmentation_fns is not",
"the input example to crop. Returns: Example with cropping applied to selected images.",
"image_height image_width \"\"\" feature_map = _create_feature_map() features = tf.io.parse_single_example(sample, feature_map) output_dict = {",
"max_examples=-1) -> tf.data.Dataset: \"\"\"Creates a dataset from a sharded tfrecord.\"\"\" dataset = tf.data.Dataset.from_tensor_slices(",
"augmentation_fns, crop_size)) return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def create_eval_datasets(batch_size: int, files: List[str], names: List[str], crop_size:",
"crop_size: If > 0, images are cropped to crop_size x crop_size using tensorflow's",
"language governing permissions and # limitations under the License. # ============================================================================== \"\"\"Dataset creation",
"crop_size, max_examples=-1) -> tf.data.Dataset: \"\"\"Creates a dataset from a sharded tfrecord.\"\"\" dataset =",
"random crop once. image_to_crop = [example[key] for key in crop_keys] stacked_images = tf.concat(image_to_crop,",
"augmentation_fns is not None: dataset = dataset.map( lambda x: apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if",
"example[key] = cropped_image return example def apply_data_augmentation( augmentation_fns: Dict[str, Callable[..., tf.Tensor]], example: tf.Tensor,",
"features = tf.io.parse_single_example(sample, feature_map) output_dict = { 'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32),",
"crop_sizes[] with training_dataset.files.') if crop_size > 0: raise ValueError( 'crop_size should not be",
"A Dict of Callables to data augmentation functions. example: Input tensor representing images",
"Apply each augmentation in sequence augmented_images = {key: example[key] for key in augmentation_keys}",
"# Perform data_augmentation before cropping and batching if augmentation_fns is not None: dataset",
"i in range(count)] def _create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns, crop_size, max_examples=-1) -> tf.data.Dataset: \"\"\"Creates",
"tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) # pylint: disable=g-long-lambda dataset = dataset.interleave( lambda x: _create_from_tfrecord( batch_size, file=x,",
"augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode) # pylint: enable=g-long-lambda dataset = dataset.prefetch(buffer_size=2) if max_examples",
"datasets. Args: batch_size: The number of images to batch per example. files: List",
"permissions and # limitations under the License. # ============================================================================== \"\"\"Dataset creation for frame",
"tf.string, default_value=''), } return feature_map def _parse_example(sample): \"\"\"Parses a serialized sample. Args: sample:",
"None: crop_keys = ['x0', 'x1', 'y'] channels = [3, 3, 3] # Stack",
"_random_crop_images(crop_size: int, images: tf.Tensor, total_channel_size: int) -> tf.Tensor: \"\"\"Crops the tensor with random",
"size and keys. Args: example: Input tensor representing images to be cropped. crop_size:",
"images to batch per example. file: (deprecated) A path to a sharded tfrecord",
"x crop_size using tensorflow's random cropping. augmentation_fns: A Dict of Callables to data",
"tfrecords, # but is always at 0.5. The model will expect this to",
"compliance with the License. # You may obtain a copy of the License",
"[example[key] for key in crop_keys] stacked_images = tf.concat(image_to_crop, axis=-1) cropped_images = _random_crop_images(crop_size, stacked_images,",
"\"\"\" if file: logging.warning('gin-configurable training_dataset.file is deprecated. ' 'Use training_dataset.files instead.') return _create_from_sharded_tfrecord(batch_size,",
"be parsed. Returns: dictionary containing the following: encoded_image image_height image_width \"\"\" feature_map =",
"def crop_example(example: tf.Tensor, crop_size: int, crop_keys: Optional[List[str]] = None): \"\"\"Random crops selected images",
"stacked_images, sum(channels)) cropped_images = tf.split( cropped_images, num_or_size_splits=channels, axis=-1) for key, cropped_image in zip(crop_keys,",
"Callable[..., tf.Tensor]]] = None ) -> tf.data.Dataset: \"\"\"Creates the training dataset. The given",
"selected images. \"\"\" if augmentation_keys is None: augmentation_keys = ['<KEY>'] # Apply each",
"file: Optional[str] = None, files: Optional[List[str]] = None, crop_size: int = -1, crop_sizes:",
"tensor with random offset to the given size.\"\"\" if crop_size > 0: crop_shape",
"num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode) # pylint: enable=g-long-lambda dataset = dataset.prefetch(buffer_size=2) if max_examples > 0:",
"default_value=''), 'frame_2/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/width': tf.io.FixedLenFeature((), tf.int64, default_value=0),",
"the training dataset. The given tfrecord should contain data in a format produced",
"to data augmentation functions. Returns: A tensorflow dataset for accessing examples that contain",
"crop_size) else: if not crop_sizes or len(crop_sizes) != len(files): raise ValueError('Please pass crop_sizes[]",
") tables = [] for file, crop_size in zip(files, crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size, True,",
"tables.append( _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size)) return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def create_eval_datasets(batch_size: int, files:",
"in zip(crop_keys, cropped_images): example[key] = cropped_image return example def apply_data_augmentation( augmentation_fns: Dict[str, Callable[...,",
"= tf.io.parse_single_example(sample, feature_map) output_dict = { 'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y':",
"to crop. Returns: Example with cropping applied to selected images. \"\"\" if crop_keys",
"read in a deterministic (same) order. Each given tfrecord should contain data in",
"_parse_example(sample): \"\"\"Parses a serialized sample. Args: sample: A serialized tf.Example to be parsed.",
"List[str]: \"\"\"Generates filenames of the each file in the sharded filepath. Based on",
"count) for i in range(count)] def _create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns, crop_size, max_examples=-1) ->",
"License. # ============================================================================== \"\"\"Dataset creation for frame interpolation.\"\"\" from typing import Callable, Dict,",
"interpolation.\"\"\" from typing import Callable, Dict, List, Optional from absl import logging import",
"['x0', 'x1', 'y'] channels = [3, 3, 3] # Stack images along channel",
"cropped to crop_size x crop_size using tensorflow's random cropping. Deprecated: use 'files' and",
"sizes. If > 0, images are cropped to crop_size x crop_size using tensorflow's",
"feature_map = _create_feature_map() features = tf.io.parse_single_example(sample, feature_map) output_dict = { 'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32),",
"frame triplet.\"\"\" feature_map = { 'frame_0/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_0/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'),",
"the example to given size and keys. Args: example: Input tensor representing images",
"List[str], names: List[str], crop_size: int = -1, max_examples: int = -1) -> Dict[str,",
"augmentation_fns, crop_size) -> tf.data.Dataset: \"\"\"Creates a dataset from TFRecord.\"\"\" dataset = tf.data.TFRecordDataset(file) dataset",
"# ============================================================================== \"\"\"Dataset creation for frame interpolation.\"\"\" from typing import Callable, Dict, List,",
"tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'path': tf.io.FixedLenFeature((),",
"and width. crop_keys: The images in the input example to crop. Returns: Example",
"produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of images to batch per example.",
"crop_size x crop_size using tensorflow's random cropping. Deprecated: use 'files' and 'crop_sizes' instead.",
"_create_from_sharded_tfrecord(batch_size, False, file, None, crop_size, max_examples) for name, file in zip(names, files) }",
"the tfrecord for the evaluation set is very large. Returns: A dict of",
"are cropped to crop_size x crop_size using tensorflow's random cropping. Deprecated: use 'files'",
"the given size.\"\"\" if crop_size > 0: crop_shape = tf.constant([crop_size, crop_size, total_channel_size]) images",
"['<KEY>'] # Apply each augmentation in sequence augmented_images = {key: example[key] for key",
"A list of paths to sharded tfrecords in <tfrecord>@N format. crop_size: (deprecated) If",
"the License. # ============================================================================== \"\"\"Dataset creation for frame interpolation.\"\"\" from typing import Callable,",
"# Copyright 2022 Google LLC # Licensed under the Apache License, Version 2.0",
"not use this file except in compliance with the License. # You may",
"return example def apply_data_augmentation( augmentation_fns: Dict[str, Callable[..., tf.Tensor]], example: tf.Tensor, augmentation_keys: Optional[List[str]] =",
"default_value=0), 'frame_0/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_1/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'),",
"batch per example. files: List of paths to a sharded tfrecord in <tfrecord>@N",
"examples. 'path': features['path'], } return output_dict def _random_crop_images(crop_size: int, images: tf.Tensor, total_channel_size: int)",
"augmentation_function in augmentation_fns.values(): augmented_images = augmentation_function(augmented_images) for key in augmentation_keys: example[key] = augmented_images[key]",
"image_width \"\"\" feature_map = _create_feature_map() features = tf.io.parse_single_example(sample, feature_map) output_dict = { 'x0':",
"to be augmented. augmentation_keys: The images in the input example to augment. Returns:",
"for key in augmentation_keys: example[key] = augmented_images[key] return example def _create_from_tfrecord(batch_size, file, augmentation_fns,",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"'frame_1/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_1/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/width':",
"deprecated. ' 'Use training_dataset.files instead.') return _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size) else: if",
"output_dict = { 'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), #",
"or len(crop_sizes) != len(files): raise ValueError('Please pass crop_sizes[] with training_dataset.files.') if crop_size >",
"dataset def _generate_sharded_filenames(filename: str) -> List[str]: \"\"\"Generates filenames of the each file in",
"dataset.map( lambda x: crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size, drop_remainder=True) return dataset def",
"using tensorflow's random cropping. augmentation_fns: A Dict of Callables to data augmentation functions.",
"-1) -> Dict[str, tf.data.Dataset]: \"\"\"Creates the evaluation datasets. As opposed to create_training_dataset this",
"included in our tfrecords, # but is always at 0.5. The model will",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"in case the tfrecord for the evaluation set is very large. Returns: A",
"each dataset are always read in a deterministic (same) order. Each given tfrecord",
"should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py The (batch_size, crop_size, max_examples)",
"tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), # The fractional time value of frame_1 is not included in",
"max_examples: int = -1) -> Dict[str, tf.data.Dataset]: \"\"\"Creates the evaluation datasets. As opposed",
"'y' and time of the ground truth 'time'=[0,1] in a dictionary of tensors.",
"truncate the dataset to 'max_examples' in length. This can be useful for speeding",
"dataset = dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform data_augmentation before cropping and batching if",
"3, 3] # Stack images along channel axis, and perform a random crop",
"triplet.\"\"\" feature_map = { 'frame_0/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_0/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_0/height':",
"in the example to given size and keys. Args: example: Input tensor representing",
"in augmentation_fns.values(): augmented_images = augmentation_function(augmented_images) for key in augmentation_keys: example[key] = augmented_images[key] return",
"default_value=0), 'frame_1/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_2/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'),",
"# you may not use this file except in compliance with the License.",
"@gin.configurable('training_dataset') def create_training_dataset( batch_size: int, file: Optional[str] = None, files: Optional[List[str]] = None,",
"dataset = tf.data.TFRecordDataset(file) dataset = dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform data_augmentation before cropping",
"dictionary containing the following: encoded_image image_height image_width \"\"\" feature_map = _create_feature_map() features =",
"int = -1, crop_sizes: Optional[List[int]] = None, augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] = None",
"truth 'time'=[0,1] in a dictionary of tensors. \"\"\" return { name: _create_from_sharded_tfrecord(batch_size, False,",
"a sharded tfrecord in <tfrecord>@N format. Deprecated. Use 'files' instead. files: A list",
"should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number",
"augmentation_fns.values(): augmented_images = augmentation_function(augmented_images) for key in augmentation_keys: example[key] = augmented_images[key] return example",
"None): \"\"\"Random crops selected images in the example to given size and keys.",
"agreed to in writing, software # distributed under the License is distributed on",
"typing import Callable, Dict, List, Optional from absl import logging import gin.tf import",
"feature_map def _parse_example(sample): \"\"\"Parses a serialized sample. Args: sample: A serialized tf.Example to",
"is None: augmentation_keys = ['<KEY>'] # Apply each augmentation in sequence augmented_images =",
"input images 'x0', 'x1', ground truth 'y' and time of the ground truth",
"the evaluation datasets. As opposed to create_training_dataset this function makes sure that the",
"crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode) # pylint: enable=g-long-lambda dataset = dataset.prefetch(buffer_size=2) if max_examples >",
"absl import logging import gin.tf import tensorflow as tf def _create_feature_map() -> Dict[str,",
"training_dataset.files.') if crop_size > 0: raise ValueError( 'crop_size should not be used with",
"As opposed to create_training_dataset this function makes sure that the examples for each",
"both height and width. crop_keys: The images in the input example to crop.",
"example. file: (deprecated) A path to a sharded tfrecord in <tfrecord>@N format. Deprecated.",
"use 'files' and 'crop_sizes' instead. crop_sizes: List of crop sizes. If > 0,",
"(the \"License\"); # you may not use this file except in compliance with",
"crop_size x crop_size using tensorflow's random cropping. augmentation_fns: A Dict of Callables to",
"total_channel_size: int) -> tf.Tensor: \"\"\"Crops the tensor with random offset to the given",
"format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of images to batch per",
"'time'=[0,1] in a dictionary of tensors. \"\"\" return { name: _create_from_sharded_tfrecord(batch_size, False, file,",
"images to be augmented. augmentation_keys: The images in the input example to augment.",
"random cropping. max_examples: If > 0, truncate the dataset to 'max_examples' in length.",
"num_or_size_splits=channels, axis=-1) for key, cropped_image in zip(crop_keys, cropped_images): example[key] = cropped_image return example",
"the following: encoded_image image_height image_width \"\"\" feature_map = _create_feature_map() features = tf.io.parse_single_example(sample, feature_map)",
"# Unless required by applicable law or agreed to in writing, software #",
"tf.string, default_value=''), 'frame_1/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/width': tf.io.FixedLenFeature((), tf.int64,",
"'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), # The fractional time",
"the examples for each dataset are always read in a deterministic (same) order.",
"'crop_size should not be used with files[], use crop_sizes[] instead.' ) tables =",
"Callables to data augmentation functions. Returns: A tensorflow dataset for accessing examples that",
"by applicable law or agreed to in writing, software # distributed under the",
"The images in the input example to crop. Returns: Example with cropping applied",
"in a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of images to",
"we insert it here. 'time': 0.5, # Store the original mid frame filepath",
"file, augmentation_fns, crop_size) -> tf.data.Dataset: \"\"\"Creates a dataset from TFRecord.\"\"\" dataset = tf.data.TFRecordDataset(file)",
"not crop_sizes or len(crop_sizes) != len(files): raise ValueError('Please pass crop_sizes[] with training_dataset.files.') if",
"files: A list of paths to sharded tfrecords in <tfrecord>@N format. crop_size: (deprecated)",
"Optional[str] = None, files: Optional[List[str]] = None, crop_size: int = -1, crop_sizes: Optional[List[int]]",
"cropped_image in zip(crop_keys, cropped_images): example[key] = cropped_image return example def apply_data_augmentation( augmentation_fns: Dict[str,",
"value is used for both height and width. crop_keys: The images in the",
"frame_interpolation/datasets/create_*_tfrecord.py The (batch_size, crop_size, max_examples) are specified for all eval datasets. Args: batch_size:",
"loop in case the tfrecord for the evaluation set is very large. Returns:",
"Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename: The sharded filepath. Returns: A list of filepaths",
"crop_sizes: List of crop sizes. If > 0, images are cropped to crop_size",
"return feature_map def _parse_example(sample): \"\"\"Parses a serialized sample. Args: sample: A serialized tf.Example",
"'files' instead. files: A list of paths to sharded tfrecords in <tfrecord>@N format.",
"once. image_to_crop = [example[key] for key in crop_keys] stacked_images = tf.concat(image_to_crop, axis=-1) cropped_images",
"sharded tfrecords in <tfrecord>@N format. crop_size: (deprecated) If > 0, images are cropped",
"to create_training_dataset this function makes sure that the examples for each dataset are",
"# Stack images along channel axis, and perform a random crop once. image_to_crop",
"list of filepaths for each file in the shard. \"\"\" base, count =",
"in the shard. \"\"\" base, count = filename.split('@') count = int(count) return ['{}-{:05d}-of-{:05d}'.format(base,",
"in a deterministic (same) order. Each given tfrecord should contain data in a",
"List of crop sizes. If > 0, images are cropped to crop_size x",
"to selected image keys. Args: augmentation_fns: A Dict of Callables to data augmentation",
"crop_size > 0: crop_shape = tf.constant([crop_size, crop_size, total_channel_size]) images = tf.image.random_crop(images, crop_shape) return",
"creation for frame interpolation.\"\"\" from typing import Callable, Dict, List, Optional from absl",
"feature map for extracting the frame triplet.\"\"\" feature_map = { 'frame_0/encoded': tf.io.FixedLenFeature((), tf.string,",
"Args: batch_size: The number of images to batch per example. files: List of",
"is not included in our tfrecords, # but is always at 0.5. The",
"file except in compliance with the License. # You may obtain a copy",
"'max_examples' in length. This can be useful for speeding up evaluation loop in",
"= _create_feature_map() features = tf.io.parse_single_example(sample, feature_map) output_dict = { 'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1':",
"# pylint: enable=g-long-lambda dataset = dataset.prefetch(buffer_size=2) if max_examples > 0: return dataset.take(max_examples) return",
"key, cropped_image in zip(crop_keys, cropped_images): example[key] = cropped_image return example def apply_data_augmentation( augmentation_fns:",
"= -1, crop_sizes: Optional[List[int]] = None, augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] = None )",
"ground truth 'time'=[0,1] in a dictionary of tensors. \"\"\" return { name: _create_from_sharded_tfrecord(batch_size,",
"for each file in the shard. \"\"\" base, count = filename.split('@') count =",
"https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software",
"of Callables to data augmentation functions. Returns: A tensorflow dataset for accessing examples",
"tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_2/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((),",
"mid frame filepath for identifying examples. 'path': features['path'], } return output_dict def _random_crop_images(crop_size:",
"always at 0.5. The model will expect this to be specificed, so #",
"extracting the frame triplet.\"\"\" feature_map = { 'frame_0/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_0/format': tf.io.FixedLenFeature((),",
"License for the specific language governing permissions and # limitations under the License.",
"None, crop_size: int = -1, crop_sizes: Optional[List[int]] = None, augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]]",
"cropping and batching if augmentation_fns is not None: dataset = dataset.map( lambda x:",
"to in writing, software # distributed under the License is distributed on an",
"Copyright 2022 Google LLC # Licensed under the Apache License, Version 2.0 (the",
"contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py The (batch_size, crop_size, max_examples) are",
"tf.data.TFRecordDataset(file) dataset = dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform data_augmentation before cropping and batching",
"augmented. augmentation_keys: The images in the input example to augment. Returns: Example with",
"_create_feature_map() -> Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates the feature map for extracting the frame triplet.\"\"\"",
"with random offset to the given size.\"\"\" if crop_size > 0: crop_shape =",
"and keys. Args: example: Input tensor representing images to be cropped. crop_size: The",
"implied. # See the License for the specific language governing permissions and #",
"= [] for file, crop_size in zip(files, crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns,",
"applied to selected images. \"\"\" if crop_keys is None: crop_keys = ['x0', 'x1',",
"\"License\"); # you may not use this file except in compliance with the",
"logging import gin.tf import tensorflow as tf def _create_feature_map() -> Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates",
"<tfrecord>@N format. crop_size: (deprecated) If > 0, images are cropped to crop_size x",
"tensor representing images to be cropped. crop_size: The size to crop images to.",
"tf.io.FixedLenFeature]: \"\"\"Creates the feature map for extracting the frame triplet.\"\"\" feature_map = {",
"A serialized tf.Example to be parsed. Returns: dictionary containing the following: encoded_image image_height",
"be cropped. crop_size: The size to crop images to. This value is used",
"tfrecord for the evaluation set is very large. Returns: A dict of name",
"# Store the original mid frame filepath for identifying examples. 'path': features['path'], }",
"if crop_size > 0: crop_shape = tf.constant([crop_size, crop_size, total_channel_size]) images = tf.image.random_crop(images, crop_shape)",
"tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((),",
"each file in the sharded filepath. Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename: The sharded",
"file: logging.warning('gin-configurable training_dataset.file is deprecated. ' 'Use training_dataset.files instead.') return _create_from_sharded_tfrecord(batch_size, True, file,",
"from typing import Callable, Dict, List, Optional from absl import logging import gin.tf",
"= ['<KEY>'] # Apply each augmentation in sequence augmented_images = {key: example[key] for",
"drop_remainder=True) return dataset def _generate_sharded_filenames(filename: str) -> List[str]: \"\"\"Generates filenames of the each",
"crop. Returns: Example with cropping applied to selected images. \"\"\" if crop_keys is",
"files: Optional[List[str]] = None, crop_size: int = -1, crop_sizes: Optional[List[int]] = None, augmentation_fns:",
"'frame_1/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/encoded':",
"encoded_image image_height image_width \"\"\" feature_map = _create_feature_map() features = tf.io.parse_single_example(sample, feature_map) output_dict =",
"def _create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns, crop_size, max_examples=-1) -> tf.data.Dataset: \"\"\"Creates a dataset from",
"before cropping and batching if augmentation_fns is not None: dataset = dataset.map( lambda",
"tf.io.FixedLenFeature((), tf.string, default_value=''), } return feature_map def _parse_example(sample): \"\"\"Parses a serialized sample. Args:",
"============================================================================== \"\"\"Dataset creation for frame interpolation.\"\"\" from typing import Callable, Dict, List, Optional",
"names: List[str], crop_size: int = -1, max_examples: int = -1) -> Dict[str, tf.data.Dataset]:",
"tensorflow's random cropping. Deprecated: use 'files' and 'crop_sizes' instead. crop_sizes: List of crop",
"size to crop images to. This value is used for both height and",
"batch_size, file=x, augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode) # pylint: enable=g-long-lambda dataset = dataset.prefetch(buffer_size=2)",
"images to be cropped. crop_size: The size to crop images to. This value",
"or implied. # See the License for the specific language governing permissions and",
"crop images to. This value is used for both height and width. crop_keys:",
"crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size, drop_remainder=True) return dataset def _generate_sharded_filenames(filename: str) -> List[str]:",
"from absl import logging import gin.tf import tensorflow as tf def _create_feature_map() ->",
"= [example[key] for key in crop_keys] stacked_images = tf.concat(image_to_crop, axis=-1) cropped_images = _random_crop_images(crop_size,",
"of crop sizes. If > 0, images are cropped to crop_size x crop_size",
"tf.io.parse_single_example(sample, feature_map) output_dict = { 'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'],",
"\"\"\"Parses a serialized sample. Args: sample: A serialized tf.Example to be parsed. Returns:",
"sample: A serialized tf.Example to be parsed. Returns: dictionary containing the following: encoded_image",
"images: tf.Tensor, total_channel_size: int) -> tf.Tensor: \"\"\"Crops the tensor with random offset to",
"image keys. Args: augmentation_fns: A Dict of Callables to data augmentation functions. example:",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"sample. Args: sample: A serialized tf.Example to be parsed. Returns: dictionary containing the",
"height and width. crop_keys: The images in the input example to crop. Returns:",
"deterministic=not train_mode) # pylint: enable=g-long-lambda dataset = dataset.prefetch(buffer_size=2) if max_examples > 0: return",
"def apply_data_augmentation( augmentation_fns: Dict[str, Callable[..., tf.Tensor]], example: tf.Tensor, augmentation_keys: Optional[List[str]] = None) ->",
"to batch per example. file: (deprecated) A path to a sharded tfrecord in",
"used for both height and width. crop_keys: The images in the input example",
"file in the sharded filepath. Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename: The sharded filepath.",
"in writing, software # distributed under the License is distributed on an \"AS",
"augmentation_fns: A Dict of Callables to data augmentation functions. example: Input tensor representing",
"# You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 #",
"-1, crop_sizes: Optional[List[int]] = None, augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] = None ) ->",
"data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py The (batch_size, crop_size, max_examples) are specified",
"to the given size.\"\"\" if crop_size > 0: crop_shape = tf.constant([crop_size, crop_size, total_channel_size])",
"= dataset.map( lambda x: apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size > 0: dataset =",
"A list of filepaths for each file in the shard. \"\"\" base, count",
"evaluation set is very large. Returns: A dict of name to tensorflow dataset",
"return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def create_eval_datasets(batch_size: int, files: List[str], names: List[str], crop_size: int =",
"= { 'frame_0/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_0/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((), tf.int64,",
"dataset from TFRecord.\"\"\" dataset = tf.data.TFRecordDataset(file) dataset = dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform",
"file in the shard. \"\"\" base, count = filename.split('@') count = int(count) return",
"_create_from_tfrecord(batch_size, file, augmentation_fns, crop_size) -> tf.data.Dataset: \"\"\"Creates a dataset from TFRecord.\"\"\" dataset =",
"None, augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] = None ) -> tf.data.Dataset: \"\"\"Creates the training",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"Callable[..., tf.Tensor]], example: tf.Tensor, augmentation_keys: Optional[List[str]] = None) -> tf.Tensor: \"\"\"Applies random augmentation",
"augmentation in sequence augmented_images = {key: example[key] for key in augmentation_keys} for augmentation_function",
"augmented_images = augmentation_function(augmented_images) for key in augmentation_keys: example[key] = augmented_images[key] return example def",
"= _random_crop_images(crop_size, stacked_images, sum(channels)) cropped_images = tf.split( cropped_images, num_or_size_splits=channels, axis=-1) for key, cropped_image",
"Optional[List[int]] = None, augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] = None ) -> tf.data.Dataset: \"\"\"Creates",
"tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def create_eval_datasets(batch_size: int, files: List[str], names: List[str], crop_size: int = -1,",
"length. This can be useful for speeding up evaluation loop in case the",
"each augmentation in sequence augmented_images = {key: example[key] for key in augmentation_keys} for",
"'frame_0/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_1/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_1/height':",
"{key: example[key] for key in augmentation_keys} for augmentation_function in augmentation_fns.values(): augmented_images = augmentation_function(augmented_images)",
"\"\"\" return { name: _create_from_sharded_tfrecord(batch_size, False, file, None, crop_size, max_examples) for name, file",
"The images in the input example to augment. Returns: Example with augmentation applied",
"0.5, # Store the original mid frame filepath for identifying examples. 'path': features['path'],",
"file, augmentation_fns, crop_size)) return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def create_eval_datasets(batch_size: int, files: List[str], names: List[str],",
"tensorflow's random cropping. max_examples: If > 0, truncate the dataset to 'max_examples' in",
"dataset to 'max_examples' in length. This can be useful for speeding up evaluation",
"3] # Stack images along channel axis, and perform a random crop once.",
"0, images are cropped to crop_size x crop_size using tensorflow's random cropping. augmentation_fns:",
"a deterministic (same) order. Each given tfrecord should contain data in a format",
"None ) -> tf.data.Dataset: \"\"\"Creates the training dataset. The given tfrecord should contain",
"= ['x0', 'x1', 'y'] channels = [3, 3, 3] # Stack images along",
"to crop_size x crop_size using tensorflow's random cropping. max_examples: If > 0, truncate",
"apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size > 0: dataset = dataset.map( lambda x: crop_example(x,",
"0: raise ValueError( 'crop_size should not be used with files[], use crop_sizes[] instead.'",
"feature_map) output_dict = { 'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32),",
"eval datasets. crop_size: If > 0, images are cropped to crop_size x crop_size",
"tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_0/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_1/format': tf.io.FixedLenFeature((),",
"is used for both height and width. crop_keys: The images in the input",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"crop_size x crop_size using tensorflow's random cropping. max_examples: If > 0, truncate the",
"you may not use this file except in compliance with the License. #",
"time value of frame_1 is not included in our tfrecords, # but is",
"key in crop_keys] stacked_images = tf.concat(image_to_crop, axis=-1) cropped_images = _random_crop_images(crop_size, stacked_images, sum(channels)) cropped_images",
"instead.' ) tables = [] for file, crop_size in zip(files, crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size,",
"tf.string, default_value=''), 'frame_0/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_0/width': tf.io.FixedLenFeature((), tf.int64,",
"in <tfrecord>@N format. names: List of names of eval datasets. crop_size: If >",
"given size and keys. Args: example: Input tensor representing images to be cropped.",
"if max_examples > 0: return dataset.take(max_examples) return dataset @gin.configurable('training_dataset') def create_training_dataset( batch_size: int,",
"images in the example to given size and keys. Args: example: Input tensor",
"def create_training_dataset( batch_size: int, file: Optional[str] = None, files: Optional[List[str]] = None, crop_size:",
"of tensors. \"\"\" return { name: _create_from_sharded_tfrecord(batch_size, False, file, None, crop_size, max_examples) for",
"augmentation_function(augmented_images) for key in augmentation_keys: example[key] = augmented_images[key] return example def _create_from_tfrecord(batch_size, file,",
"tf.string, default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'path': tf.io.FixedLenFeature((), tf.string,",
"random augmentation in succession to selected image keys. Args: augmentation_fns: A Dict of",
"applied to selected images. \"\"\" if augmentation_keys is None: augmentation_keys = ['<KEY>'] #",
"The given tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args:",
"contain the input images 'x0', 'x1', ground truth 'y' and time of the",
"crop_size: int = -1, max_examples: int = -1) -> Dict[str, tf.data.Dataset]: \"\"\"Creates the",
"file=x, augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode) # pylint: enable=g-long-lambda dataset = dataset.prefetch(buffer_size=2) if",
"sharded tfrecord in <tfrecord>@N format. Deprecated. Use 'files' instead. files: A list of",
"default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_2/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((), tf.int64, default_value=0),",
"for file, crop_size in zip(files, crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size)) return",
"def _create_from_tfrecord(batch_size, file, augmentation_fns, crop_size) -> tf.data.Dataset: \"\"\"Creates a dataset from TFRecord.\"\"\" dataset",
"'frame_1/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_2/format':",
"image_to_crop = [example[key] for key in crop_keys] stacked_images = tf.concat(image_to_crop, axis=-1) cropped_images =",
"is very large. Returns: A dict of name to tensorflow dataset for accessing",
"use this file except in compliance with the License. # You may obtain",
"name: _create_from_sharded_tfrecord(batch_size, False, file, None, crop_size, max_examples) for name, file in zip(names, files)",
"to tensorflow dataset for accessing examples that contain the input images 'x0', 'x1',",
"specific language governing permissions and # limitations under the License. # ============================================================================== \"\"\"Dataset",
"a serialized sample. Args: sample: A serialized tf.Example to be parsed. Returns: dictionary",
"feature_map = { 'frame_0/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_0/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((),",
"'crop_sizes' instead. crop_sizes: List of crop sizes. If > 0, images are cropped",
"for each dataset are always read in a deterministic (same) order. Each given",
"data augmentation functions. Returns: A tensorflow dataset for accessing examples that contain the",
"dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), # The fractional time value of",
"from TFRecord.\"\"\" dataset = tf.data.TFRecordDataset(file) dataset = dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform data_augmentation",
"License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to",
"tf.int64, default_value=0), 'frame_1/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_2/format': tf.io.FixedLenFeature((), tf.string,",
"_create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size) else: if not crop_sizes or len(crop_sizes) != len(files):",
"\"\"\"Dataset creation for frame interpolation.\"\"\" from typing import Callable, Dict, List, Optional from",
"-> tf.Tensor: \"\"\"Crops the tensor with random offset to the given size.\"\"\" if",
"default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''),",
"Args: batch_size: The number of images to batch per example. file: (deprecated) A",
"'frame_2/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'path': tf.io.FixedLenFeature((), tf.string, default_value=''), }",
"insert it here. 'time': 0.5, # Store the original mid frame filepath for",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"data augmentation functions. example: Input tensor representing images to be augmented. augmentation_keys: The",
"of paths to a sharded tfrecord in <tfrecord>@N format. names: List of names",
"to given size and keys. Args: example: Input tensor representing images to be",
"lambda x: crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size, drop_remainder=True) return dataset def _generate_sharded_filenames(filename:",
"input example to crop. Returns: Example with cropping applied to selected images. \"\"\"",
"return dataset def _generate_sharded_filenames(filename: str) -> List[str]: \"\"\"Generates filenames of the each file",
"crop_size: int = -1, crop_sizes: Optional[List[int]] = None, augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] =",
"all eval datasets. Args: batch_size: The number of images to batch per example.",
"= filename.split('@') count = int(count) return ['{}-{:05d}-of-{:05d}'.format(base, i, count) for i in range(count)]",
"train_mode) # pylint: enable=g-long-lambda dataset = dataset.prefetch(buffer_size=2) if max_examples > 0: return dataset.take(max_examples)",
"tf.int64, default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_2/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((), tf.int64,",
"0: dataset = dataset.map( lambda x: crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size, drop_remainder=True)",
"useful for speeding up evaluation loop in case the tfrecord for the evaluation",
"in a dictionary of tensors. \"\"\" return { name: _create_from_sharded_tfrecord(batch_size, False, file, None,",
"dataset = dataset.batch(batch_size, drop_remainder=True) return dataset def _generate_sharded_filenames(filename: str) -> List[str]: \"\"\"Generates filenames",
"dtype=tf.float32), # The fractional time value of frame_1 is not included in our",
"the each file in the sharded filepath. Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename: The",
"augmentation_fns, crop_size, max_examples=-1) -> tf.data.Dataset: \"\"\"Creates a dataset from a sharded tfrecord.\"\"\" dataset",
"pylint: disable=g-long-lambda dataset = dataset.interleave( lambda x: _create_from_tfrecord( batch_size, file=x, augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE,",
"a dictionary of tensors. \"\"\" if file: logging.warning('gin-configurable training_dataset.file is deprecated. ' 'Use",
"tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py The (batch_size, crop_size,",
"\"\"\"Creates the feature map for extracting the frame triplet.\"\"\" feature_map = { 'frame_0/encoded':",
"is deprecated. ' 'Use training_dataset.files instead.') return _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size) else:",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"features['path'], } return output_dict def _random_crop_images(crop_size: int, images: tf.Tensor, total_channel_size: int) -> tf.Tensor:",
"governing permissions and # limitations under the License. # ============================================================================== \"\"\"Dataset creation for",
"Returns: dictionary containing the following: encoded_image image_height image_width \"\"\" feature_map = _create_feature_map() features",
"x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size > 0: dataset = dataset.map( lambda x: crop_example(x, crop_size=crop_size),",
"= dataset.map( lambda x: crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size, drop_remainder=True) return dataset",
"range(count)] def _create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns, crop_size, max_examples=-1) -> tf.data.Dataset: \"\"\"Creates a dataset",
"the feature map for extracting the frame triplet.\"\"\" feature_map = { 'frame_0/encoded': tf.io.FixedLenFeature((),",
"speeding up evaluation loop in case the tfrecord for the evaluation set is",
"= tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) # pylint: disable=g-long-lambda dataset = dataset.interleave( lambda x: _create_from_tfrecord( batch_size,",
"for the specific language governing permissions and # limitations under the License. #",
"tf.Tensor: \"\"\"Applies random augmentation in succession to selected image keys. Args: augmentation_fns: A",
"ground truth 'y' and time of the ground truth 'time'=[0,1] in a dictionary",
"len(files): raise ValueError('Please pass crop_sizes[] with training_dataset.files.') if crop_size > 0: raise ValueError(",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"images def crop_example(example: tf.Tensor, crop_size: int, crop_keys: Optional[List[str]] = None): \"\"\"Random crops selected",
"= tf.split( cropped_images, num_or_size_splits=channels, axis=-1) for key, cropped_image in zip(crop_keys, cropped_images): example[key] =",
"dataset = dataset.map( lambda x: crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size, drop_remainder=True) return",
"truth 'time'=[0,1] in a dictionary of tensors. \"\"\" if file: logging.warning('gin-configurable training_dataset.file is",
"are specified for all eval datasets. Args: batch_size: The number of images to",
"tf.Tensor]]] = None ) -> tf.data.Dataset: \"\"\"Creates the training dataset. The given tfrecord",
"_random_crop_images(crop_size, stacked_images, sum(channels)) cropped_images = tf.split( cropped_images, num_or_size_splits=channels, axis=-1) for key, cropped_image in",
"images in the input example to crop. Returns: Example with cropping applied to",
"'Use training_dataset.files instead.') return _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size) else: if not crop_sizes",
"express or implied. # See the License for the specific language governing permissions",
"example to crop. Returns: Example with cropping applied to selected images. \"\"\" if",
"be specificed, so # we insert it here. 'time': 0.5, # Store the",
"ground truth 'time'=[0,1] in a dictionary of tensors. \"\"\" if file: logging.warning('gin-configurable training_dataset.file",
"None, files: Optional[List[str]] = None, crop_size: int = -1, crop_sizes: Optional[List[int]] = None,",
"default_value=''), } return feature_map def _parse_example(sample): \"\"\"Parses a serialized sample. Args: sample: A",
"if not crop_sizes or len(crop_sizes) != len(files): raise ValueError('Please pass crop_sizes[] with training_dataset.files.')",
"training_dataset.files instead.') return _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size) else: if not crop_sizes or",
"tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), # The fractional time value of frame_1 is",
"sure that the examples for each dataset are always read in a deterministic",
"'frame_0/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_0/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_1/format':",
"not included in our tfrecords, # but is always at 0.5. The model",
"per example. file: (deprecated) A path to a sharded tfrecord in <tfrecord>@N format.",
"if file: logging.warning('gin-configurable training_dataset.file is deprecated. ' 'Use training_dataset.files instead.') return _create_from_sharded_tfrecord(batch_size, True,",
"= -1) -> Dict[str, tf.data.Dataset]: \"\"\"Creates the evaluation datasets. As opposed to create_training_dataset",
"The number of images to batch per example. files: List of paths to",
"= tf.image.random_crop(images, crop_shape) return images def crop_example(example: tf.Tensor, crop_size: int, crop_keys: Optional[List[str]] =",
"cropped_images = tf.split( cropped_images, num_or_size_splits=channels, axis=-1) for key, cropped_image in zip(crop_keys, cropped_images): example[key]",
"selected images. \"\"\" if crop_keys is None: crop_keys = ['x0', 'x1', 'y'] channels",
"enable=g-long-lambda dataset = dataset.prefetch(buffer_size=2) if max_examples > 0: return dataset.take(max_examples) return dataset @gin.configurable('training_dataset')",
"either express or implied. # See the License for the specific language governing",
"Returns: A tensorflow dataset for accessing examples that contain the input images 'x0',",
"'time'=[0,1] in a dictionary of tensors. \"\"\" if file: logging.warning('gin-configurable training_dataset.file is deprecated.",
"crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size)) return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def create_eval_datasets(batch_size: int,",
"filepath for identifying examples. 'path': features['path'], } return output_dict def _random_crop_images(crop_size: int, images:",
"number of images to batch per example. file: (deprecated) A path to a",
"= dataset.batch(batch_size, drop_remainder=True) return dataset def _generate_sharded_filenames(filename: str) -> List[str]: \"\"\"Generates filenames of",
"List of names of eval datasets. crop_size: If > 0, images are cropped",
"images are cropped to crop_size x crop_size using tensorflow's random cropping. max_examples: If",
"of frame_1 is not included in our tfrecords, # but is always at",
"given tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size:",
"case the tfrecord for the evaluation set is very large. Returns: A dict",
"channels = [3, 3, 3] # Stack images along channel axis, and perform",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"crop_size in zip(files, crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size)) return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets')",
"produced by frame_interpolation/datasets/create_*_tfrecord.py The (batch_size, crop_size, max_examples) are specified for all eval datasets.",
"dataset from a sharded tfrecord.\"\"\" dataset = tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) # pylint: disable=g-long-lambda dataset",
"a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable",
"and perform a random crop once. image_to_crop = [example[key] for key in crop_keys]",
"examples that contain the input images 'x0', 'x1', ground truth 'y' and time",
"of filepaths for each file in the shard. \"\"\" base, count = filename.split('@')",
"'x1', ground truth 'y' and time of the ground truth 'time'=[0,1] in a",
"augmentation_fns, crop_size) else: if not crop_sizes or len(crop_sizes) != len(files): raise ValueError('Please pass",
"training_dataset.file is deprecated. ' 'Use training_dataset.files instead.') return _create_from_sharded_tfrecord(batch_size, True, file, augmentation_fns, crop_size)",
"set is very large. Returns: A dict of name to tensorflow dataset for",
"_generate_sharded_filenames(filename: str) -> List[str]: \"\"\"Generates filenames of the each file in the sharded",
"_create_from_tfrecord( batch_size, file=x, augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode) # pylint: enable=g-long-lambda dataset =",
"The fractional time value of frame_1 is not included in our tfrecords, #",
"def _random_crop_images(crop_size: int, images: tf.Tensor, total_channel_size: int) -> tf.Tensor: \"\"\"Crops the tensor with",
"cropping. max_examples: If > 0, truncate the dataset to 'max_examples' in length. This",
"to crop_size x crop_size using tensorflow's random cropping. augmentation_fns: A Dict of Callables",
"the sharded filepath. Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename: The sharded filepath. Returns: A",
"tf.concat(image_to_crop, axis=-1) cropped_images = _random_crop_images(crop_size, stacked_images, sum(channels)) cropped_images = tf.split( cropped_images, num_or_size_splits=channels, axis=-1)",
"cropped_image return example def apply_data_augmentation( augmentation_fns: Dict[str, Callable[..., tf.Tensor]], example: tf.Tensor, augmentation_keys: Optional[List[str]]",
"tf.Tensor: \"\"\"Crops the tensor with random offset to the given size.\"\"\" if crop_size",
"for key in augmentation_keys} for augmentation_function in augmentation_fns.values(): augmented_images = augmentation_function(augmented_images) for key",
"for i in range(count)] def _create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns, crop_size, max_examples=-1) -> tf.data.Dataset:",
"crop_size: (deprecated) If > 0, images are cropped to crop_size x crop_size using",
"frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of images to batch per example. file: (deprecated)",
"'y'] channels = [3, 3, 3] # Stack images along channel axis, and",
"Dict, List, Optional from absl import logging import gin.tf import tensorflow as tf",
"tf.Example to be parsed. Returns: dictionary containing the following: encoded_image image_height image_width \"\"\"",
"always read in a deterministic (same) order. Each given tfrecord should contain data",
"the License. # You may obtain a copy of the License at #",
"tf.Tensor, total_channel_size: int) -> tf.Tensor: \"\"\"Crops the tensor with random offset to the",
"augmentation functions. Returns: A tensorflow dataset for accessing examples that contain the input",
"this function makes sure that the examples for each dataset are always read",
"github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename: The sharded filepath. Returns: A list of filepaths for each",
"tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_2/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/width': tf.io.FixedLenFeature((),",
"in range(count)] def _create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns, crop_size, max_examples=-1) -> tf.data.Dataset: \"\"\"Creates a",
"augmentation applied to selected images. \"\"\" if augmentation_keys is None: augmentation_keys = ['<KEY>']",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"\"\"\"Creates the training dataset. The given tfrecord should contain data in a format",
"sum(channels)) cropped_images = tf.split( cropped_images, num_or_size_splits=channels, axis=-1) for key, cropped_image in zip(crop_keys, cropped_images):",
"using tensorflow's random cropping. Deprecated: use 'files' and 'crop_sizes' instead. crop_sizes: List of",
"augmentation in succession to selected image keys. Args: augmentation_fns: A Dict of Callables",
"should not be used with files[], use crop_sizes[] instead.' ) tables = []",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), # The fractional time value",
"int = -1) -> Dict[str, tf.data.Dataset]: \"\"\"Creates the evaluation datasets. As opposed to",
"crop_keys = ['x0', 'x1', 'y'] channels = [3, 3, 3] # Stack images",
"functions. example: Input tensor representing images to be augmented. augmentation_keys: The images in",
"crop_sizes or len(crop_sizes) != len(files): raise ValueError('Please pass crop_sizes[] with training_dataset.files.') if crop_size",
"succession to selected image keys. Args: augmentation_fns: A Dict of Callables to data",
"of the ground truth 'time'=[0,1] in a dictionary of tensors. \"\"\" return {",
"The (batch_size, crop_size, max_examples) are specified for all eval datasets. Args: batch_size: The",
"'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), # The fractional time value of frame_1 is not included",
"input example to augment. Returns: Example with augmentation applied to selected images. \"\"\"",
"number of images to batch per example. files: List of paths to a",
"Each given tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py The",
"to sharded tfrecords in <tfrecord>@N format. crop_size: (deprecated) If > 0, images are",
"tf.int64, default_value=0), 'frame_0/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_1/format': tf.io.FixedLenFeature((), tf.string,",
"in our tfrecords, # but is always at 0.5. The model will expect",
"example def apply_data_augmentation( augmentation_fns: Dict[str, Callable[..., tf.Tensor]], example: tf.Tensor, augmentation_keys: Optional[List[str]] = None)",
"dictionary of tensors. \"\"\" if file: logging.warning('gin-configurable training_dataset.file is deprecated. ' 'Use training_dataset.files",
"be augmented. augmentation_keys: The images in the input example to augment. Returns: Example",
"in length. This can be useful for speeding up evaluation loop in case",
"{ 'frame_0/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_0/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((), tf.int64, default_value=0),",
"files[], use crop_sizes[] instead.' ) tables = [] for file, crop_size in zip(files,",
"random cropping. augmentation_fns: A Dict of Callables to data augmentation functions. Returns: A",
"format. names: List of names of eval datasets. crop_size: If > 0, images",
"in the sharded filepath. Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename: The sharded filepath. Returns:",
"axis=-1) cropped_images = _random_crop_images(crop_size, stacked_images, sum(channels)) cropped_images = tf.split( cropped_images, num_or_size_splits=channels, axis=-1) for",
"Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates the feature map for extracting the frame triplet.\"\"\" feature_map =",
"with augmentation applied to selected images. \"\"\" if augmentation_keys is None: augmentation_keys =",
"} return output_dict def _random_crop_images(crop_size: int, images: tf.Tensor, total_channel_size: int) -> tf.Tensor: \"\"\"Crops",
"return output_dict def _random_crop_images(crop_size: int, images: tf.Tensor, total_channel_size: int) -> tf.Tensor: \"\"\"Crops the",
"raise ValueError('Please pass crop_sizes[] with training_dataset.files.') if crop_size > 0: raise ValueError( 'crop_size",
"to batch per example. files: List of paths to a sharded tfrecord in",
"model will expect this to be specificed, so # we insert it here.",
"return images def crop_example(example: tf.Tensor, crop_size: int, crop_keys: Optional[List[str]] = None): \"\"\"Random crops",
"batch_size: int, file: Optional[str] = None, files: Optional[List[str]] = None, crop_size: int =",
"0, truncate the dataset to 'max_examples' in length. This can be useful for",
"for key, cropped_image in zip(crop_keys, cropped_images): example[key] = cropped_image return example def apply_data_augmentation(",
"> 0, images are cropped to crop_size x crop_size using tensorflow's random cropping.",
"images are cropped to crop_size x crop_size using tensorflow's random cropping. Deprecated: use",
"zip(crop_keys, cropped_images): example[key] = cropped_image return example def apply_data_augmentation( augmentation_fns: Dict[str, Callable[..., tf.Tensor]],",
"dataset.map( lambda x: apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size > 0: dataset = dataset.map(",
"example to augment. Returns: Example with augmentation applied to selected images. \"\"\" if",
"dataset = dataset.map( lambda x: apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size > 0: dataset",
"frame interpolation.\"\"\" from typing import Callable, Dict, List, Optional from absl import logging",
"stacked_images = tf.concat(image_to_crop, axis=-1) cropped_images = _random_crop_images(crop_size, stacked_images, sum(channels)) cropped_images = tf.split( cropped_images,",
"to. This value is used for both height and width. crop_keys: The images",
"a random crop once. image_to_crop = [example[key] for key in crop_keys] stacked_images =",
"> 0: dataset = dataset.map( lambda x: crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size,",
"with training_dataset.files.') if crop_size > 0: raise ValueError( 'crop_size should not be used",
"default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_0/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''),",
"crop_keys: The images in the input example to crop. Returns: Example with cropping",
"for accessing examples that contain the input images 'x0', 'x1', ground truth 'y'",
"images 'x0', 'x1', ground truth 'y' and time of the ground truth 'time'=[0,1]",
"dictionary of tensors. \"\"\" return { name: _create_from_sharded_tfrecord(batch_size, False, file, None, crop_size, max_examples)",
"def _generate_sharded_filenames(filename: str) -> List[str]: \"\"\"Generates filenames of the each file in the",
"Perform data_augmentation before cropping and batching if augmentation_fns is not None: dataset =",
"dataset = tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) # pylint: disable=g-long-lambda dataset = dataset.interleave( lambda x: _create_from_tfrecord(",
"'x0', 'x1', ground truth 'y' and time of the ground truth 'time'=[0,1] in",
"base, count = filename.split('@') count = int(count) return ['{}-{:05d}-of-{:05d}'.format(base, i, count) for i",
"The sharded filepath. Returns: A list of filepaths for each file in the",
"sharded filepath. Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename: The sharded filepath. Returns: A list",
"with the License. # You may obtain a copy of the License at",
"tensorflow as tf def _create_feature_map() -> Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates the feature map for",
"Args: example: Input tensor representing images to be cropped. crop_size: The size to",
"augmented_images = {key: example[key] for key in augmentation_keys} for augmentation_function in augmentation_fns.values(): augmented_images",
"if crop_size > 0: dataset = dataset.map( lambda x: crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset",
"= tf.data.TFRecordDataset(file) dataset = dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform data_augmentation before cropping and",
"crop_size) -> tf.data.Dataset: \"\"\"Creates a dataset from TFRecord.\"\"\" dataset = tf.data.TFRecordDataset(file) dataset =",
"evaluation loop in case the tfrecord for the evaluation set is very large.",
"int(count) return ['{}-{:05d}-of-{:05d}'.format(base, i, count) for i in range(count)] def _create_from_sharded_tfrecord(batch_size, train_mode, file,",
"pass crop_sizes[] with training_dataset.files.') if crop_size > 0: raise ValueError( 'crop_size should not",
"are cropped to crop_size x crop_size using tensorflow's random cropping. max_examples: If >",
"a format produced by frame_interpolation/datasets/create_*_tfrecord.py The (batch_size, crop_size, max_examples) are specified for all",
"a dataset from TFRecord.\"\"\" dataset = tf.data.TFRecordDataset(file) dataset = dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) #",
"of the ground truth 'time'=[0,1] in a dictionary of tensors. \"\"\" if file:",
"Returns: A list of filepaths for each file in the shard. \"\"\" base,",
"= cropped_image return example def apply_data_augmentation( augmentation_fns: Dict[str, Callable[..., tf.Tensor]], example: tf.Tensor, augmentation_keys:",
"int, file: Optional[str] = None, files: Optional[List[str]] = None, crop_size: int = -1,",
"functions. Returns: A tensorflow dataset for accessing examples that contain the input images",
"specificed, so # we insert it here. 'time': 0.5, # Store the original",
"crop_keys: Optional[List[str]] = None): \"\"\"Random crops selected images in the example to given",
"Returns: Example with augmentation applied to selected images. \"\"\" if augmentation_keys is None:",
"the evaluation set is very large. Returns: A dict of name to tensorflow",
"crop_size > 0: raise ValueError( 'crop_size should not be used with files[], use",
"max_examples: If > 0, truncate the dataset to 'max_examples' in length. This can",
"def _create_feature_map() -> Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates the feature map for extracting the frame",
"'frame_2/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'path': tf.io.FixedLenFeature((), tf.string, default_value=''), } return feature_map def _parse_example(sample):",
"that contain the input images 'x0', 'x1', ground truth 'y' and time of",
"in succession to selected image keys. Args: augmentation_fns: A Dict of Callables to",
"crop_size > 0: dataset = dataset.map( lambda x: crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset =",
"use crop_sizes[] instead.' ) tables = [] for file, crop_size in zip(files, crop_sizes):",
"along channel axis, and perform a random crop once. image_to_crop = [example[key] for",
"at 0.5. The model will expect this to be specificed, so # we",
"perform a random crop once. image_to_crop = [example[key] for key in crop_keys] stacked_images",
"expect this to be specificed, so # we insert it here. 'time': 0.5,",
"by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of images to batch per example. file:",
"time of the ground truth 'time'=[0,1] in a dictionary of tensors. \"\"\" if",
"law or agreed to in writing, software # distributed under the License is",
"crop_size)) return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def create_eval_datasets(batch_size: int, files: List[str], names: List[str], crop_size: int",
"the License for the specific language governing permissions and # limitations under the",
"crop_size using tensorflow's random cropping. augmentation_fns: A Dict of Callables to data augmentation",
"= {key: example[key] for key in augmentation_keys} for augmentation_function in augmentation_fns.values(): augmented_images =",
"# Apply each augmentation in sequence augmented_images = {key: example[key] for key in",
"crop_size using tensorflow's random cropping. Deprecated: use 'files' and 'crop_sizes' instead. crop_sizes: List",
"be used with files[], use crop_sizes[] instead.' ) tables = [] for file,",
"= augmentation_function(augmented_images) for key in augmentation_keys: example[key] = augmented_images[key] return example def _create_from_tfrecord(batch_size,",
"'frame_1/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_2/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_2/height':",
"on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename: The sharded filepath. Returns: A list of filepaths for",
"tfrecord in <tfrecord>@N format. Deprecated. Use 'files' instead. files: A list of paths",
"Example with augmentation applied to selected images. \"\"\" if augmentation_keys is None: augmentation_keys",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"frame_1 is not included in our tfrecords, # but is always at 0.5.",
"filepaths for each file in the shard. \"\"\" base, count = filename.split('@') count",
"A path to a sharded tfrecord in <tfrecord>@N format. Deprecated. Use 'files' instead.",
"tf.image.random_crop(images, crop_shape) return images def crop_example(example: tf.Tensor, crop_size: int, crop_keys: Optional[List[str]] = None):",
"a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of images to batch",
"file, augmentation_fns, crop_size) else: if not crop_sizes or len(crop_sizes) != len(files): raise ValueError('Please",
"List[str], crop_size: int = -1, max_examples: int = -1) -> Dict[str, tf.data.Dataset]: \"\"\"Creates",
"tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_1/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((),",
"dataset for accessing examples that contain the input images 'x0', 'x1', ground truth",
"\"\"\"Applies random augmentation in succession to selected image keys. Args: augmentation_fns: A Dict",
"is None: crop_keys = ['x0', 'x1', 'y'] channels = [3, 3, 3] #",
"the tensor with random offset to the given size.\"\"\" if crop_size > 0:",
"cropped_images): example[key] = cropped_image return example def apply_data_augmentation( augmentation_fns: Dict[str, Callable[..., tf.Tensor]], example:",
"to a sharded tfrecord in <tfrecord>@N format. names: List of names of eval",
"example: Input tensor representing images to be augmented. augmentation_keys: The images in the",
"images to batch per example. files: List of paths to a sharded tfrecord",
"augmentation_keys: Optional[List[str]] = None) -> tf.Tensor: \"\"\"Applies random augmentation in succession to selected",
"Optional[List[str]] = None, crop_size: int = -1, crop_sizes: Optional[List[int]] = None, augmentation_fns: Optional[Dict[str,",
"create_eval_datasets(batch_size: int, files: List[str], names: List[str], crop_size: int = -1, max_examples: int =",
"= { 'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), # The",
"# we insert it here. 'time': 0.5, # Store the original mid frame",
"\"\"\"Random crops selected images in the example to given size and keys. Args:",
"tf.data.Dataset: \"\"\"Creates the training dataset. The given tfrecord should contain data in a",
"of images to batch per example. file: (deprecated) A path to a sharded",
"total_channel_size]) images = tf.image.random_crop(images, crop_shape) return images def crop_example(example: tf.Tensor, crop_size: int, crop_keys:",
"tensor representing images to be augmented. augmentation_keys: The images in the input example",
"names of eval datasets. crop_size: If > 0, images are cropped to crop_size",
"int) -> tf.Tensor: \"\"\"Crops the tensor with random offset to the given size.\"\"\"",
"Callable, Dict, List, Optional from absl import logging import gin.tf import tensorflow as",
"in compliance with the License. # You may obtain a copy of the",
"per example. files: List of paths to a sharded tfrecord in <tfrecord>@N format.",
"name to tensorflow dataset for accessing examples that contain the input images 'x0',",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"images are cropped to crop_size x crop_size using tensorflow's random cropping. augmentation_fns: A",
"raise ValueError( 'crop_size should not be used with files[], use crop_sizes[] instead.' )",
"files: List of paths to a sharded tfrecord in <tfrecord>@N format. names: List",
"copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law",
"order. Each given tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py",
"of the each file in the sharded filepath. Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py. Args: filename:",
"tf.Tensor, augmentation_keys: Optional[List[str]] = None) -> tf.Tensor: \"\"\"Applies random augmentation in succession to",
"keys. Args: example: Input tensor representing images to be cropped. crop_size: The size",
"Args: sample: A serialized tf.Example to be parsed. Returns: dictionary containing the following:",
"None) -> tf.Tensor: \"\"\"Applies random augmentation in succession to selected image keys. Args:",
"\"\"\"Creates a dataset from a sharded tfrecord.\"\"\" dataset = tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) # pylint:",
"dataset. The given tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py",
"x crop_size using tensorflow's random cropping. Deprecated: use 'files' and 'crop_sizes' instead. crop_sizes:",
"format. crop_size: (deprecated) If > 0, images are cropped to crop_size x crop_size",
"and batching if augmentation_fns is not None: dataset = dataset.map( lambda x: apply_data_augmentation(augmentation_fns,",
"format. Deprecated. Use 'files' instead. files: A list of paths to sharded tfrecords",
"tables = [] for file, crop_size in zip(files, crop_sizes): tables.append( _create_from_sharded_tfrecord(batch_size, True, file,",
"'path': features['path'], } return output_dict def _random_crop_images(crop_size: int, images: tf.Tensor, total_channel_size: int) ->",
"Use 'files' instead. files: A list of paths to sharded tfrecords in <tfrecord>@N",
"See the License for the specific language governing permissions and # limitations under",
"tensorflow's random cropping. augmentation_fns: A Dict of Callables to data augmentation functions. Returns:",
"'path': tf.io.FixedLenFeature((), tf.string, default_value=''), } return feature_map def _parse_example(sample): \"\"\"Parses a serialized sample.",
"augmentation_fns: A Dict of Callables to data augmentation functions. Returns: A tensorflow dataset",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"so # we insert it here. 'time': 0.5, # Store the original mid",
"cropped to crop_size x crop_size using tensorflow's random cropping. augmentation_fns: A Dict of",
"Optional[Dict[str, Callable[..., tf.Tensor]]] = None ) -> tf.data.Dataset: \"\"\"Creates the training dataset. The",
"# but is always at 0.5. The model will expect this to be",
"the input example to augment. Returns: Example with augmentation applied to selected images.",
"return ['{}-{:05d}-of-{:05d}'.format(base, i, count) for i in range(count)] def _create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns,",
"True, file, augmentation_fns, crop_size)) return tf.data.experimental.sample_from_datasets(tables) @gin.configurable('eval_datasets') def create_eval_datasets(batch_size: int, files: List[str], names:",
"crop_size: The size to crop images to. This value is used for both",
"it here. 'time': 0.5, # Store the original mid frame filepath for identifying",
"identifying examples. 'path': features['path'], } return output_dict def _random_crop_images(crop_size: int, images: tf.Tensor, total_channel_size:",
"from a sharded tfrecord.\"\"\" dataset = tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) # pylint: disable=g-long-lambda dataset =",
"batch per example. file: (deprecated) A path to a sharded tfrecord in <tfrecord>@N",
"\"\"\"Creates the evaluation datasets. As opposed to create_training_dataset this function makes sure that",
"int, crop_keys: Optional[List[str]] = None): \"\"\"Random crops selected images in the example to",
"example def _create_from_tfrecord(batch_size, file, augmentation_fns, crop_size) -> tf.data.Dataset: \"\"\"Creates a dataset from TFRecord.\"\"\"",
"list of paths to sharded tfrecords in <tfrecord>@N format. crop_size: (deprecated) If >",
"in augmentation_keys: example[key] = augmented_images[key] return example def _create_from_tfrecord(batch_size, file, augmentation_fns, crop_size) ->",
"and time of the ground truth 'time'=[0,1] in a dictionary of tensors. \"\"\"",
"{ name: _create_from_sharded_tfrecord(batch_size, False, file, None, crop_size, max_examples) for name, file in zip(names,",
"-> tf.Tensor: \"\"\"Applies random augmentation in succession to selected image keys. Args: augmentation_fns:",
"num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size > 0: dataset = dataset.map( lambda x: crop_example(x, crop_size=crop_size), num_parallel_calls=tf.data.experimental.AUTOTUNE)",
"int = -1, max_examples: int = -1) -> Dict[str, tf.data.Dataset]: \"\"\"Creates the evaluation",
"our tfrecords, # but is always at 0.5. The model will expect this",
"the original mid frame filepath for identifying examples. 'path': features['path'], } return output_dict",
"batch_size: The number of images to batch per example. files: List of paths",
"large. Returns: A dict of name to tensorflow dataset for accessing examples that",
"cropped. crop_size: The size to crop images to. This value is used for",
"= int(count) return ['{}-{:05d}-of-{:05d}'.format(base, i, count) for i in range(count)] def _create_from_sharded_tfrecord(batch_size, train_mode,",
"= None ) -> tf.data.Dataset: \"\"\"Creates the training dataset. The given tfrecord should",
"filename.split('@') count = int(count) return ['{}-{:05d}-of-{:05d}'.format(base, i, count) for i in range(count)] def",
"Dict of Callables to data augmentation functions. Returns: A tensorflow dataset for accessing",
"data_augmentation before cropping and batching if augmentation_fns is not None: dataset = dataset.map(",
"tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_2/format': tf.io.FixedLenFeature((),",
"count = int(count) return ['{}-{:05d}-of-{:05d}'.format(base, i, count) for i in range(count)] def _create_from_sharded_tfrecord(batch_size,",
"cropped to crop_size x crop_size using tensorflow's random cropping. max_examples: If > 0,",
"for frame interpolation.\"\"\" from typing import Callable, Dict, List, Optional from absl import",
"(same) order. Each given tfrecord should contain data in a format produced by",
"pylint: enable=g-long-lambda dataset = dataset.prefetch(buffer_size=2) if max_examples > 0: return dataset.take(max_examples) return dataset",
"limitations under the License. # ============================================================================== \"\"\"Dataset creation for frame interpolation.\"\"\" from typing",
"as tf def _create_feature_map() -> Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates the feature map for extracting",
"filepath. Returns: A list of filepaths for each file in the shard. \"\"\"",
"len(crop_sizes) != len(files): raise ValueError('Please pass crop_sizes[] with training_dataset.files.') if crop_size > 0:",
"tf.data.Dataset]: \"\"\"Creates the evaluation datasets. As opposed to create_training_dataset this function makes sure",
"tf.int64, default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_1/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((), tf.int64,",
"max_examples) are specified for all eval datasets. Args: batch_size: The number of images",
"default_value=''), 'frame_0/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_0/width': tf.io.FixedLenFeature((), tf.int64, default_value=0),",
"up evaluation loop in case the tfrecord for the evaluation set is very",
"images. \"\"\" if crop_keys is None: crop_keys = ['x0', 'x1', 'y'] channels =",
"training dataset. The given tfrecord should contain data in a format produced by",
"List of paths to a sharded tfrecord in <tfrecord>@N format. names: List of",
"def create_eval_datasets(batch_size: int, files: List[str], names: List[str], crop_size: int = -1, max_examples: int",
"datasets. crop_size: If > 0, images are cropped to crop_size x crop_size using",
"augmented_images[key] return example def _create_from_tfrecord(batch_size, file, augmentation_fns, crop_size) -> tf.data.Dataset: \"\"\"Creates a dataset",
"{ 'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'], dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), # The fractional",
"key in augmentation_keys} for augmentation_function in augmentation_fns.values(): augmented_images = augmentation_function(augmented_images) for key in",
"apply_data_augmentation( augmentation_fns: Dict[str, Callable[..., tf.Tensor]], example: tf.Tensor, augmentation_keys: Optional[List[str]] = None) -> tf.Tensor:",
"file, augmentation_fns, crop_size, max_examples=-1) -> tf.data.Dataset: \"\"\"Creates a dataset from a sharded tfrecord.\"\"\"",
"-> tf.data.Dataset: \"\"\"Creates the training dataset. The given tfrecord should contain data in",
"tf.data.Dataset: \"\"\"Creates a dataset from TFRecord.\"\"\" dataset = tf.data.TFRecordDataset(file) dataset = dataset.map( _parse_example,",
"!= len(files): raise ValueError('Please pass crop_sizes[] with training_dataset.files.') if crop_size > 0: raise",
"\"\"\" feature_map = _create_feature_map() features = tf.io.parse_single_example(sample, feature_map) output_dict = { 'x0': tf.io.decode_image(features['frame_0/encoded'],",
"if augmentation_fns is not None: dataset = dataset.map( lambda x: apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE)",
"sharded tfrecord in <tfrecord>@N format. names: List of names of eval datasets. crop_size:",
"This value is used for both height and width. crop_keys: The images in",
"dict of name to tensorflow dataset for accessing examples that contain the input",
"Example with cropping applied to selected images. \"\"\" if crop_keys is None: crop_keys",
"augmentation functions. example: Input tensor representing images to be augmented. augmentation_keys: The images",
"crop_size, max_examples) are specified for all eval datasets. Args: batch_size: The number of",
"\"\"\" if crop_keys is None: crop_keys = ['x0', 'x1', 'y'] channels = [3,",
"to be cropped. crop_size: The size to crop images to. This value is",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"int, images: tf.Tensor, total_channel_size: int) -> tf.Tensor: \"\"\"Crops the tensor with random offset",
"width. crop_keys: The images in the input example to crop. Returns: Example with",
"except in compliance with the License. # You may obtain a copy of",
"for key in crop_keys] stacked_images = tf.concat(image_to_crop, axis=-1) cropped_images = _random_crop_images(crop_size, stacked_images, sum(channels))",
"the specific language governing permissions and # limitations under the License. # ==============================================================================",
"in crop_keys] stacked_images = tf.concat(image_to_crop, axis=-1) cropped_images = _random_crop_images(crop_size, stacked_images, sum(channels)) cropped_images =",
"2022 Google LLC # Licensed under the Apache License, Version 2.0 (the \"License\");",
"following: encoded_image image_height image_width \"\"\" feature_map = _create_feature_map() features = tf.io.parse_single_example(sample, feature_map) output_dict",
"sequence augmented_images = {key: example[key] for key in augmentation_keys} for augmentation_function in augmentation_fns.values():",
"dataset.prefetch(buffer_size=2) if max_examples > 0: return dataset.take(max_examples) return dataset @gin.configurable('training_dataset') def create_training_dataset( batch_size:",
"augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] = None ) -> tf.data.Dataset: \"\"\"Creates the training dataset.",
"crop_example(example: tf.Tensor, crop_size: int, crop_keys: Optional[List[str]] = None): \"\"\"Random crops selected images in",
"not be used with files[], use crop_sizes[] instead.' ) tables = [] for",
"i, count) for i in range(count)] def _create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns, crop_size, max_examples=-1)",
"<tfrecord>@N format. Deprecated. Use 'files' instead. files: A list of paths to sharded",
"the ground truth 'time'=[0,1] in a dictionary of tensors. \"\"\" return { name:",
"Dict[str, tf.data.Dataset]: \"\"\"Creates the evaluation datasets. As opposed to create_training_dataset this function makes",
"(batch_size, crop_size, max_examples) are specified for all eval datasets. Args: batch_size: The number",
"augmentation_fns: Dict[str, Callable[..., tf.Tensor]], example: tf.Tensor, augmentation_keys: Optional[List[str]] = None) -> tf.Tensor: \"\"\"Applies",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"given size.\"\"\" if crop_size > 0: crop_shape = tf.constant([crop_size, crop_size, total_channel_size]) images =",
"_generate_sharded_filenames(file)) # pylint: disable=g-long-lambda dataset = dataset.interleave( lambda x: _create_from_tfrecord( batch_size, file=x, augmentation_fns=augmentation_fns,",
"tf def _create_feature_map() -> Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates the feature map for extracting the",
"-> List[str]: \"\"\"Generates filenames of the each file in the sharded filepath. Based",
"example to given size and keys. Args: example: Input tensor representing images to",
"import logging import gin.tf import tensorflow as tf def _create_feature_map() -> Dict[str, tf.io.FixedLenFeature]:",
"Callables to data augmentation functions. example: Input tensor representing images to be augmented.",
"truth 'y' and time of the ground truth 'time'=[0,1] in a dictionary of",
"\"\"\" base, count = filename.split('@') count = int(count) return ['{}-{:05d}-of-{:05d}'.format(base, i, count) for",
"dataset.interleave( lambda x: _create_from_tfrecord( batch_size, file=x, augmentation_fns=augmentation_fns, crop_size=crop_size), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not train_mode) # pylint:",
"'files' and 'crop_sizes' instead. crop_sizes: List of crop sizes. If > 0, images",
"of names of eval datasets. crop_size: If > 0, images are cropped to",
"representing images to be cropped. crop_size: The size to crop images to. This",
"= None, crop_size: int = -1, crop_sizes: Optional[List[int]] = None, augmentation_fns: Optional[Dict[str, Callable[...,",
"A dict of name to tensorflow dataset for accessing examples that contain the",
"format produced by frame_interpolation/datasets/create_*_tfrecord.py The (batch_size, crop_size, max_examples) are specified for all eval",
"-> Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates the feature map for extracting the frame triplet.\"\"\" feature_map",
"for identifying examples. 'path': features['path'], } return output_dict def _random_crop_images(crop_size: int, images: tf.Tensor,",
"train_mode, file, augmentation_fns, crop_size, max_examples=-1) -> tf.data.Dataset: \"\"\"Creates a dataset from a sharded",
"can be useful for speeding up evaluation loop in case the tfrecord for",
"selected images in the example to given size and keys. Args: example: Input",
"example: Input tensor representing images to be cropped. crop_size: The size to crop",
"Optional[List[str]] = None) -> tf.Tensor: \"\"\"Applies random augmentation in succession to selected image",
") -> tf.data.Dataset: \"\"\"Creates the training dataset. The given tfrecord should contain data",
"tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_0/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((),",
"\"\"\"Generates filenames of the each file in the sharded filepath. Based on github.com/google/revisiting-self-supervised/blob/master/datasets.py.",
"crop once. image_to_crop = [example[key] for key in crop_keys] stacked_images = tf.concat(image_to_crop, axis=-1)",
"0, images are cropped to crop_size x crop_size using tensorflow's random cropping. Deprecated:",
"images in the input example to augment. Returns: Example with augmentation applied to",
"List, Optional from absl import logging import gin.tf import tensorflow as tf def",
"'frame_0/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_0/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_0/width':",
"are always read in a deterministic (same) order. Each given tfrecord should contain",
"return example def _create_from_tfrecord(batch_size, file, augmentation_fns, crop_size) -> tf.data.Dataset: \"\"\"Creates a dataset from",
"shard. \"\"\" base, count = filename.split('@') count = int(count) return ['{}-{:05d}-of-{:05d}'.format(base, i, count)",
"tf.string, default_value='jpg'), 'frame_0/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_0/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/encoded': tf.io.FixedLenFeature((), tf.string,",
"tfrecord in <tfrecord>@N format. names: List of names of eval datasets. crop_size: If",
"cropping. augmentation_fns: A Dict of Callables to data augmentation functions. Returns: A tensorflow",
"-> Dict[str, tf.data.Dataset]: \"\"\"Creates the evaluation datasets. As opposed to create_training_dataset this function",
"Returns: A dict of name to tensorflow dataset for accessing examples that contain",
"specified for all eval datasets. Args: batch_size: The number of images to batch",
"data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of images",
"# pylint: disable=g-long-lambda dataset = dataset.interleave( lambda x: _create_from_tfrecord( batch_size, file=x, augmentation_fns=augmentation_fns, crop_size=crop_size),",
"a sharded tfrecord in <tfrecord>@N format. names: List of names of eval datasets.",
"crop_sizes: Optional[List[int]] = None, augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] = None ) -> tf.data.Dataset:",
"and # limitations under the License. # ============================================================================== \"\"\"Dataset creation for frame interpolation.\"\"\"",
"tf.constant([crop_size, crop_size, total_channel_size]) images = tf.image.random_crop(images, crop_shape) return images def crop_example(example: tf.Tensor, crop_size:",
"default_value=0), 'frame_2/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'path': tf.io.FixedLenFeature((), tf.string, default_value=''), } return feature_map def",
"Dict of Callables to data augmentation functions. example: Input tensor representing images to",
"a dataset from a sharded tfrecord.\"\"\" dataset = tf.data.Dataset.from_tensor_slices( _generate_sharded_filenames(file)) # pylint: disable=g-long-lambda",
"accessing examples that contain the input images 'x0', 'x1', ground truth 'y' and",
"datasets. As opposed to create_training_dataset this function makes sure that the examples for",
"= None, augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] = None ) -> tf.data.Dataset: \"\"\"Creates the",
"tf.int64, default_value=0), 'path': tf.io.FixedLenFeature((), tf.string, default_value=''), } return feature_map def _parse_example(sample): \"\"\"Parses a",
"None: dataset = dataset.map( lambda x: apply_data_augmentation(augmentation_fns, x), num_parallel_calls=tf.data.experimental.AUTOTUNE) if crop_size > 0:",
"Google LLC # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"paths to a sharded tfrecord in <tfrecord>@N format. names: List of names of",
"import tensorflow as tf def _create_feature_map() -> Dict[str, tf.io.FixedLenFeature]: \"\"\"Creates the feature map",
"are cropped to crop_size x crop_size using tensorflow's random cropping. augmentation_fns: A Dict",
"tf.io.FixedLenFeature((), tf.string, default_value=''), 'frame_1/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_1/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_1/width': tf.io.FixedLenFeature((),",
"License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0",
"cropped_images, num_or_size_splits=channels, axis=-1) for key, cropped_image in zip(crop_keys, cropped_images): example[key] = cropped_image return",
"= None) -> tf.Tensor: \"\"\"Applies random augmentation in succession to selected image keys.",
"# The fractional time value of frame_1 is not included in our tfrecords,",
"A tensorflow dataset for accessing examples that contain the input images 'x0', 'x1',",
"Input tensor representing images to be cropped. crop_size: The size to crop images",
"tensors. \"\"\" return { name: _create_from_sharded_tfrecord(batch_size, False, file, None, crop_size, max_examples) for name,",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"[3, 3, 3] # Stack images along channel axis, and perform a random",
"tf.string, default_value=''), 'frame_2/format': tf.io.FixedLenFeature((), tf.string, default_value='jpg'), 'frame_2/height': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/width': tf.io.FixedLenFeature((), tf.int64,",
"tf.io.FixedLenFeature((), tf.int64, default_value=0), 'path': tf.io.FixedLenFeature((), tf.string, default_value=''), } return feature_map def _parse_example(sample): \"\"\"Parses",
"If > 0, truncate the dataset to 'max_examples' in length. This can be",
"> 0: crop_shape = tf.constant([crop_size, crop_size, total_channel_size]) images = tf.image.random_crop(images, crop_shape) return images",
"channel axis, and perform a random crop once. image_to_crop = [example[key] for key",
"instead. files: A list of paths to sharded tfrecords in <tfrecord>@N format. crop_size:",
"tf.io.FixedLenFeature((), tf.int64, default_value=0), 'frame_2/width': tf.io.FixedLenFeature((), tf.int64, default_value=0), 'path': tf.io.FixedLenFeature((), tf.string, default_value=''), } return",
"_create_feature_map() features = tf.io.parse_single_example(sample, feature_map) output_dict = { 'x0': tf.io.decode_image(features['frame_0/encoded'], dtype=tf.float32), 'x1': tf.io.decode_image(features['frame_2/encoded'],",
"dataset.take(max_examples) return dataset @gin.configurable('training_dataset') def create_training_dataset( batch_size: int, file: Optional[str] = None, files:",
"0.5. The model will expect this to be specificed, so # we insert",
"TFRecord.\"\"\" dataset = tf.data.TFRecordDataset(file) dataset = dataset.map( _parse_example, num_parallel_calls=tf.data.experimental.AUTOTUNE) # Perform data_augmentation before",
"of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or",
"return dataset.take(max_examples) return dataset @gin.configurable('training_dataset') def create_training_dataset( batch_size: int, file: Optional[str] = None,",
"dtype=tf.float32), 'y': tf.io.decode_image(features['frame_1/encoded'], dtype=tf.float32), # The fractional time value of frame_1 is not"
] |
[
"len(s)==1: return True for i in range(1,len(s),1): if ord(s[i])-ord(s[i-1])!=1: return False return True",
"s.sort() s=''.join(s) if len(s)==1: return True for i in range(1,len(s),1): if ord(s[i])-ord(s[i-1])!=1: return",
"s=''.join(s) if len(s)==1: return True for i in range(1,len(s),1): if ord(s[i])-ord(s[i-1])!=1: return False",
"if len(s)==1: return True for i in range(1,len(s),1): if ord(s[i])-ord(s[i-1])!=1: return False return",
"solve(s): s=list(s) s.sort() s=''.join(s) if len(s)==1: return True for i in range(1,len(s),1): if",
"s=list(s) s.sort() s=''.join(s) if len(s)==1: return True for i in range(1,len(s),1): if ord(s[i])-ord(s[i-1])!=1:",
"def solve(s): s=list(s) s.sort() s=''.join(s) if len(s)==1: return True for i in range(1,len(s),1):"
] |
[
"return mat #plt.matshow(makeMatCores(100,100)) #define range of Z's Z_low = 2 Z_top = 150",
"BE_liquidDrop(N+1,Z) BE_f_down = BE_liquidDrop(N,Z) Qdown = BE_f_down-BE_i_down if (Q<0): mat[Z-Zstart, N-Nstart] = 1",
"N else: N = N+1 def makeMatCores(Zrange): Nstart = 0 Nrange = int(2.3*Zrange)",
"BE_liquidDrop(N,Z): #N=num of neutrons, Z=num of protons #num of nucleons A = N+Z",
"for Z in range(Zstart,Zrange): for N in range(Nstart,Nrange): BE_i_up = BE_liquidDrop(N+1,Z) BE_f_up =",
"for the range Z=36-44 #Z = range(Z_low, Z_top+1) #N = [] # #for",
"= range(Z_low, Z_top+1) #N = [] # #for z in Z: # dripline",
"= plt.imshow(mat,interpolation='nearest', origin='lower') plt.show() #interested in finding the neutron drip line for the",
"0 Nrange = int(2.3*Zrange) Zstart = 1 mat = np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z in",
"the neutron drip line for the range Z=36-44 #Z = range(Z_low, Z_top+1) #N",
"1 mat = np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z in range(Zstart,Zrange): for N in range(Nstart,Nrange): BE_i_up",
"#N=num of neutrons, Z=num of protons #num of nucleons A = N+Z #physical",
"a2 = 17.23 a3 = 0.697 a4 = 22.6 #nuclear liquid drop model",
"False): BE_i = BE_liquidDrop(N+1,Z) BE_f = BE_liquidDrop(N,Z) Q = BE_f-BE_i if (Q>0): return",
"= BE_liquidDrop(N,Z) Q = BE_f-BE_i if (Q>0): return N else: N = N+1",
"= int(2.3*Zrange) Zstart = 1 mat = np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z in range(Zstart,Zrange): for",
"mat = np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z in range(Zstart,Zrange): for N in range(Nstart,Nrange): BE_i_up =",
"BE_liquidDrop(N+1,Z) BE_f_up = BE_liquidDrop(N,Z) Qup = BE_f_up-BE_i_up BE_i_down = BE_liquidDrop(N+1,Z) BE_f_down = BE_liquidDrop(N,Z)",
"= BE_liquidDrop(N+1,Z) BE_f_up = BE_liquidDrop(N,Z) Qup = BE_f_up-BE_i_up BE_i_down = BE_liquidDrop(N+1,Z) BE_f_down =",
"#iterative search for dripline while (check == False): BE_i = BE_liquidDrop(N+1,Z) BE_f =",
"if (Q<0): mat[Z-Zstart, N-Nstart] = 1 else: mat[Z-Zstart, N-Nstart] = 0 return mat",
"range(Z_low, Z_top+1) #N = [] # #for z in Z: # dripline =",
"= 1 else: mat[Z-Zstart, N-Nstart] = 0 return mat #plt.matshow(makeMatCores(100,100)) #define range of",
"(check == False): BE_i = BE_liquidDrop(N+1,Z) BE_f = BE_liquidDrop(N,Z) Q = BE_f-BE_i if",
"findDripLine(z) # print \"For\", z,\"protons, the neutron dripline is\",dripline, \"neutrons\" # N.append(dripline) #",
"nucleus N=Z #iterative search for dripline while (check == False): BE_i = BE_liquidDrop(N+1,Z)",
"statement for finding dripline check = False #start with symmetric nucleus N=Z #iterative",
"protons #num of nucleons A = N+Z #physical constants (from Alex's notes, in",
"#test statement for finding dripline check = False #start with symmetric nucleus N=Z",
"= N+1 def makeMatCores(Zrange): Nstart = 0 Nrange = int(2.3*Zrange) Zstart = 1",
"# #for z in Z: # dripline = findDripLine(z) # print \"For\", z,\"protons,",
"neutron drip line for the range Z=36-44 #Z = range(Z_low, Z_top+1) #N =",
"#nuclear liquid drop model return a1*A - a2*A**(2./3) - a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A #finds",
"Z=36-44 #Z = range(Z_low, Z_top+1) #N = [] # #for z in Z:",
"N.append(dripline) # #mat = np.zeros((max(Z)+1,max(N)+1)) # #for i in range(0,len(Z)): # mat[Z[i],N[i]] =",
"BE_f_down = BE_liquidDrop(N,Z) Qdown = BE_f_down-BE_i_down if (Q<0): mat[Z-Zstart, N-Nstart] = 1 else:",
"mat[Z-Zstart, N-Nstart] = 0 return mat #plt.matshow(makeMatCores(100,100)) #define range of Z's Z_low =",
"A = N+Z #physical constants (from Alex's notes, in MeV) a1 = 15.49",
"N=Z #iterative search for dripline while (check == False): BE_i = BE_liquidDrop(N+1,Z) BE_f",
"BE_i_down = BE_liquidDrop(N+1,Z) BE_f_down = BE_liquidDrop(N,Z) Qdown = BE_f_down-BE_i_down if (Q<0): mat[Z-Zstart, N-Nstart]",
"is\",dripline, \"neutrons\" # N.append(dripline) # #mat = np.zeros((max(Z)+1,max(N)+1)) # #for i in range(0,len(Z)):",
"#finds the neutron dripline def findDripLine(Z): #test statement for finding dripline check =",
"return a1*A - a2*A**(2./3) - a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A #finds the neutron dripline def",
"# N.append(dripline) # #mat = np.zeros((max(Z)+1,max(N)+1)) # #for i in range(0,len(Z)): # mat[Z[i],N[i]]",
"of nucleons A = N+Z #physical constants (from Alex's notes, in MeV) a1",
"check = False #start with symmetric nucleus N=Z #iterative search for dripline while",
"of protons #num of nucleons A = N+Z #physical constants (from Alex's notes,",
"15.49 a2 = 17.23 a3 = 0.697 a4 = 22.6 #nuclear liquid drop",
"mat[Z-Zstart, N-Nstart] = 1 else: mat[Z-Zstart, N-Nstart] = 0 return mat #plt.matshow(makeMatCores(100,100)) #define",
"(Q>0): return N else: N = N+1 def makeMatCores(Zrange): Nstart = 0 Nrange",
"makeMatCores(Z_top) img2 = plt.imshow(mat,interpolation='nearest', origin='lower') plt.show() #interested in finding the neutron drip line",
"Z_low = 2 Z_top = 150 mat = makeMatCores(Z_top) img2 = plt.imshow(mat,interpolation='nearest', origin='lower')",
"= 0 Nrange = int(2.3*Zrange) Zstart = 1 mat = np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z",
"neutrons, Z=num of protons #num of nucleons A = N+Z #physical constants (from",
"z in Z: # dripline = findDripLine(z) # print \"For\", z,\"protons, the neutron",
"= 0.697 a4 = 22.6 #nuclear liquid drop model return a1*A - a2*A**(2./3)",
"for dripline while (check == False): BE_i = BE_liquidDrop(N+1,Z) BE_f = BE_liquidDrop(N,Z) Q",
"= BE_liquidDrop(N+1,Z) BE_f = BE_liquidDrop(N,Z) Q = BE_f-BE_i if (Q>0): return N else:",
"BE_i_up = BE_liquidDrop(N+1,Z) BE_f_up = BE_liquidDrop(N,Z) Qup = BE_f_up-BE_i_up BE_i_down = BE_liquidDrop(N+1,Z) BE_f_down",
"BE_f_up = BE_liquidDrop(N,Z) Qup = BE_f_up-BE_i_up BE_i_down = BE_liquidDrop(N+1,Z) BE_f_down = BE_liquidDrop(N,Z) Qdown",
"- a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A #finds the neutron dripline def findDripLine(Z): #test statement for",
"N-Nstart] = 0 return mat #plt.matshow(makeMatCores(100,100)) #define range of Z's Z_low = 2",
"np #returns the binding energy predicted by nuclear liquid drop model def BE_liquidDrop(N,Z):",
"in range(Zstart,Zrange): for N in range(Nstart,Nrange): BE_i_up = BE_liquidDrop(N+1,Z) BE_f_up = BE_liquidDrop(N,Z) Qup",
"0.697 a4 = 22.6 #nuclear liquid drop model return a1*A - a2*A**(2./3) -",
"a1 = 15.49 a2 = 17.23 a3 = 0.697 a4 = 22.6 #nuclear",
"range(Nstart,Nrange): BE_i_up = BE_liquidDrop(N+1,Z) BE_f_up = BE_liquidDrop(N,Z) Qup = BE_f_up-BE_i_up BE_i_down = BE_liquidDrop(N+1,Z)",
"drop model return a1*A - a2*A**(2./3) - a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A #finds the neutron",
"= False #start with symmetric nucleus N=Z #iterative search for dripline while (check",
"the neutron dripline def findDripLine(Z): #test statement for finding dripline check = False",
"(from Alex's notes, in MeV) a1 = 15.49 a2 = 17.23 a3 =",
"drip line for the range Z=36-44 #Z = range(Z_low, Z_top+1) #N = []",
"as np #returns the binding energy predicted by nuclear liquid drop model def",
"plt.show() #interested in finding the neutron drip line for the range Z=36-44 #Z",
"mat = makeMatCores(Z_top) img2 = plt.imshow(mat,interpolation='nearest', origin='lower') plt.show() #interested in finding the neutron",
"of neutrons, Z=num of protons #num of nucleons A = N+Z #physical constants",
"Q = BE_f-BE_i if (Q>0): return N else: N = N+1 def makeMatCores(Zrange):",
"150 mat = makeMatCores(Z_top) img2 = plt.imshow(mat,interpolation='nearest', origin='lower') plt.show() #interested in finding the",
"with symmetric nucleus N=Z #iterative search for dripline while (check == False): BE_i",
"predicted by nuclear liquid drop model def BE_liquidDrop(N,Z): #N=num of neutrons, Z=num of",
"return N else: N = N+1 def makeMatCores(Zrange): Nstart = 0 Nrange =",
"a4 = 22.6 #nuclear liquid drop model return a1*A - a2*A**(2./3) - a3*(Z**2)/(A*(1./3))",
"BE_liquidDrop(N+1,Z) BE_f = BE_liquidDrop(N,Z) Q = BE_f-BE_i if (Q>0): return N else: N",
"N = N+1 def makeMatCores(Zrange): Nstart = 0 Nrange = int(2.3*Zrange) Zstart =",
"= [] # #for z in Z: # dripline = findDripLine(z) # print",
"mat #plt.matshow(makeMatCores(100,100)) #define range of Z's Z_low = 2 Z_top = 150 mat",
"#mat = np.zeros((max(Z)+1,max(N)+1)) # #for i in range(0,len(Z)): # mat[Z[i],N[i]] = 1 #plt.matshow(mat)",
"= 0 return mat #plt.matshow(makeMatCores(100,100)) #define range of Z's Z_low = 2 Z_top",
"Nstart = 0 Nrange = int(2.3*Zrange) Zstart = 1 mat = np.zeros((Zrange-Zstart,Nrange-Nstart)) for",
"= makeMatCores(Z_top) img2 = plt.imshow(mat,interpolation='nearest', origin='lower') plt.show() #interested in finding the neutron drip",
"#start with symmetric nucleus N=Z #iterative search for dripline while (check == False):",
"int(2.3*Zrange) Zstart = 1 mat = np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z in range(Zstart,Zrange): for N",
"= BE_liquidDrop(N+1,Z) BE_f_down = BE_liquidDrop(N,Z) Qdown = BE_f_down-BE_i_down if (Q<0): mat[Z-Zstart, N-Nstart] =",
"= N+Z #physical constants (from Alex's notes, in MeV) a1 = 15.49 a2",
"(Q<0): mat[Z-Zstart, N-Nstart] = 1 else: mat[Z-Zstart, N-Nstart] = 0 return mat #plt.matshow(makeMatCores(100,100))",
"False #start with symmetric nucleus N=Z #iterative search for dripline while (check ==",
"Z: # dripline = findDripLine(z) # print \"For\", z,\"protons, the neutron dripline is\",dripline,",
"= BE_f_down-BE_i_down if (Q<0): mat[Z-Zstart, N-Nstart] = 1 else: mat[Z-Zstart, N-Nstart] = 0",
"0 return mat #plt.matshow(makeMatCores(100,100)) #define range of Z's Z_low = 2 Z_top =",
"findDripLine(Z): #test statement for finding dripline check = False #start with symmetric nucleus",
"while (check == False): BE_i = BE_liquidDrop(N+1,Z) BE_f = BE_liquidDrop(N,Z) Q = BE_f-BE_i",
"- a2*A**(2./3) - a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A #finds the neutron dripline def findDripLine(Z): #test",
"BE_i = BE_liquidDrop(N+1,Z) BE_f = BE_liquidDrop(N,Z) Q = BE_f-BE_i if (Q>0): return N",
"22.6 #nuclear liquid drop model return a1*A - a2*A**(2./3) - a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A",
"\"neutrons\" # N.append(dripline) # #mat = np.zeros((max(Z)+1,max(N)+1)) # #for i in range(0,len(Z)): #",
"= findDripLine(z) # print \"For\", z,\"protons, the neutron dripline is\",dripline, \"neutrons\" # N.append(dripline)",
"= 22.6 #nuclear liquid drop model return a1*A - a2*A**(2./3) - a3*(Z**2)/(A*(1./3)) -",
"else: N = N+1 def makeMatCores(Zrange): Nstart = 0 Nrange = int(2.3*Zrange) Zstart",
"finding the neutron drip line for the range Z=36-44 #Z = range(Z_low, Z_top+1)",
"Z_top = 150 mat = makeMatCores(Z_top) img2 = plt.imshow(mat,interpolation='nearest', origin='lower') plt.show() #interested in",
"a2*A**(2./3) - a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A #finds the neutron dripline def findDripLine(Z): #test statement",
"matplotlib.pyplot as plt import numpy as np #returns the binding energy predicted by",
"Qdown = BE_f_down-BE_i_down if (Q<0): mat[Z-Zstart, N-Nstart] = 1 else: mat[Z-Zstart, N-Nstart] =",
"1 else: mat[Z-Zstart, N-Nstart] = 0 return mat #plt.matshow(makeMatCores(100,100)) #define range of Z's",
"dripline is\",dripline, \"neutrons\" # N.append(dripline) # #mat = np.zeros((max(Z)+1,max(N)+1)) # #for i in",
"#for z in Z: # dripline = findDripLine(z) # print \"For\", z,\"protons, the",
"# print \"For\", z,\"protons, the neutron dripline is\",dripline, \"neutrons\" # N.append(dripline) # #mat",
"in MeV) a1 = 15.49 a2 = 17.23 a3 = 0.697 a4 =",
"energy predicted by nuclear liquid drop model def BE_liquidDrop(N,Z): #N=num of neutrons, Z=num",
"= 17.23 a3 = 0.697 a4 = 22.6 #nuclear liquid drop model return",
"a3 = 0.697 a4 = 22.6 #nuclear liquid drop model return a1*A -",
"for N in range(Nstart,Nrange): BE_i_up = BE_liquidDrop(N+1,Z) BE_f_up = BE_liquidDrop(N,Z) Qup = BE_f_up-BE_i_up",
"import numpy as np #returns the binding energy predicted by nuclear liquid drop",
"search for dripline while (check == False): BE_i = BE_liquidDrop(N+1,Z) BE_f = BE_liquidDrop(N,Z)",
"#define range of Z's Z_low = 2 Z_top = 150 mat = makeMatCores(Z_top)",
"as plt import numpy as np #returns the binding energy predicted by nuclear",
"a4*(N-Z)**2/A #finds the neutron dripline def findDripLine(Z): #test statement for finding dripline check",
"def makeMatCores(Zrange): Nstart = 0 Nrange = int(2.3*Zrange) Zstart = 1 mat =",
"= 150 mat = makeMatCores(Z_top) img2 = plt.imshow(mat,interpolation='nearest', origin='lower') plt.show() #interested in finding",
"= np.zeros((max(Z)+1,max(N)+1)) # #for i in range(0,len(Z)): # mat[Z[i],N[i]] = 1 #plt.matshow(mat) #plt.show()",
"origin='lower') plt.show() #interested in finding the neutron drip line for the range Z=36-44",
"else: mat[Z-Zstart, N-Nstart] = 0 return mat #plt.matshow(makeMatCores(100,100)) #define range of Z's Z_low",
"BE_liquidDrop(N,Z) Q = BE_f-BE_i if (Q>0): return N else: N = N+1 def",
"2 Z_top = 150 mat = makeMatCores(Z_top) img2 = plt.imshow(mat,interpolation='nearest', origin='lower') plt.show() #interested",
"#N = [] # #for z in Z: # dripline = findDripLine(z) #",
"Z=num of protons #num of nucleons A = N+Z #physical constants (from Alex's",
"Z_top+1) #N = [] # #for z in Z: # dripline = findDripLine(z)",
"neutron dripline def findDripLine(Z): #test statement for finding dripline check = False #start",
"N+Z #physical constants (from Alex's notes, in MeV) a1 = 15.49 a2 =",
"N in range(Nstart,Nrange): BE_i_up = BE_liquidDrop(N+1,Z) BE_f_up = BE_liquidDrop(N,Z) Qup = BE_f_up-BE_i_up BE_i_down",
"in range(Nstart,Nrange): BE_i_up = BE_liquidDrop(N+1,Z) BE_f_up = BE_liquidDrop(N,Z) Qup = BE_f_up-BE_i_up BE_i_down =",
"numpy as np #returns the binding energy predicted by nuclear liquid drop model",
"a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A #finds the neutron dripline def findDripLine(Z): #test statement for finding",
"#num of nucleons A = N+Z #physical constants (from Alex's notes, in MeV)",
"a1*A - a2*A**(2./3) - a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A #finds the neutron dripline def findDripLine(Z):",
"the neutron dripline is\",dripline, \"neutrons\" # N.append(dripline) # #mat = np.zeros((max(Z)+1,max(N)+1)) # #for",
"#physical constants (from Alex's notes, in MeV) a1 = 15.49 a2 = 17.23",
"liquid drop model return a1*A - a2*A**(2./3) - a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A #finds the",
"plt import numpy as np #returns the binding energy predicted by nuclear liquid",
"#returns the binding energy predicted by nuclear liquid drop model def BE_liquidDrop(N,Z): #N=num",
"Nrange = int(2.3*Zrange) Zstart = 1 mat = np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z in range(Zstart,Zrange):",
"def findDripLine(Z): #test statement for finding dripline check = False #start with symmetric",
"#Z = range(Z_low, Z_top+1) #N = [] # #for z in Z: #",
"N-Nstart] = 1 else: mat[Z-Zstart, N-Nstart] = 0 return mat #plt.matshow(makeMatCores(100,100)) #define range",
"dripline check = False #start with symmetric nucleus N=Z #iterative search for dripline",
"in finding the neutron drip line for the range Z=36-44 #Z = range(Z_low,",
"constants (from Alex's notes, in MeV) a1 = 15.49 a2 = 17.23 a3",
"range(Zstart,Zrange): for N in range(Nstart,Nrange): BE_i_up = BE_liquidDrop(N+1,Z) BE_f_up = BE_liquidDrop(N,Z) Qup =",
"= 15.49 a2 = 17.23 a3 = 0.697 a4 = 22.6 #nuclear liquid",
"= np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z in range(Zstart,Zrange): for N in range(Nstart,Nrange): BE_i_up = BE_liquidDrop(N+1,Z)",
"17.23 a3 = 0.697 a4 = 22.6 #nuclear liquid drop model return a1*A",
"of Z's Z_low = 2 Z_top = 150 mat = makeMatCores(Z_top) img2 =",
"neutron dripline is\",dripline, \"neutrons\" # N.append(dripline) # #mat = np.zeros((max(Z)+1,max(N)+1)) # #for i",
"nuclear liquid drop model def BE_liquidDrop(N,Z): #N=num of neutrons, Z=num of protons #num",
"Zstart = 1 mat = np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z in range(Zstart,Zrange): for N in",
"range of Z's Z_low = 2 Z_top = 150 mat = makeMatCores(Z_top) img2",
"liquid drop model def BE_liquidDrop(N,Z): #N=num of neutrons, Z=num of protons #num of",
"import matplotlib.pyplot as plt import numpy as np #returns the binding energy predicted",
"def BE_liquidDrop(N,Z): #N=num of neutrons, Z=num of protons #num of nucleons A =",
"Alex's notes, in MeV) a1 = 15.49 a2 = 17.23 a3 = 0.697",
"= BE_f_up-BE_i_up BE_i_down = BE_liquidDrop(N+1,Z) BE_f_down = BE_liquidDrop(N,Z) Qdown = BE_f_down-BE_i_down if (Q<0):",
"if (Q>0): return N else: N = N+1 def makeMatCores(Zrange): Nstart = 0",
"BE_f_up-BE_i_up BE_i_down = BE_liquidDrop(N+1,Z) BE_f_down = BE_liquidDrop(N,Z) Qdown = BE_f_down-BE_i_down if (Q<0): mat[Z-Zstart,",
"dripline = findDripLine(z) # print \"For\", z,\"protons, the neutron dripline is\",dripline, \"neutrons\" #",
"BE_f-BE_i if (Q>0): return N else: N = N+1 def makeMatCores(Zrange): Nstart =",
"== False): BE_i = BE_liquidDrop(N+1,Z) BE_f = BE_liquidDrop(N,Z) Q = BE_f-BE_i if (Q>0):",
"line for the range Z=36-44 #Z = range(Z_low, Z_top+1) #N = [] #",
"BE_f = BE_liquidDrop(N,Z) Q = BE_f-BE_i if (Q>0): return N else: N =",
"dripline while (check == False): BE_i = BE_liquidDrop(N+1,Z) BE_f = BE_liquidDrop(N,Z) Q =",
"= BE_liquidDrop(N,Z) Qdown = BE_f_down-BE_i_down if (Q<0): mat[Z-Zstart, N-Nstart] = 1 else: mat[Z-Zstart,",
"BE_liquidDrop(N,Z) Qdown = BE_f_down-BE_i_down if (Q<0): mat[Z-Zstart, N-Nstart] = 1 else: mat[Z-Zstart, N-Nstart]",
"#plt.matshow(makeMatCores(100,100)) #define range of Z's Z_low = 2 Z_top = 150 mat =",
"img2 = plt.imshow(mat,interpolation='nearest', origin='lower') plt.show() #interested in finding the neutron drip line for",
"plt.imshow(mat,interpolation='nearest', origin='lower') plt.show() #interested in finding the neutron drip line for the range",
"in Z: # dripline = findDripLine(z) # print \"For\", z,\"protons, the neutron dripline",
"by nuclear liquid drop model def BE_liquidDrop(N,Z): #N=num of neutrons, Z=num of protons",
"N+1 def makeMatCores(Zrange): Nstart = 0 Nrange = int(2.3*Zrange) Zstart = 1 mat",
"= 1 mat = np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z in range(Zstart,Zrange): for N in range(Nstart,Nrange):",
"the binding energy predicted by nuclear liquid drop model def BE_liquidDrop(N,Z): #N=num of",
"z,\"protons, the neutron dripline is\",dripline, \"neutrons\" # N.append(dripline) # #mat = np.zeros((max(Z)+1,max(N)+1)) #",
"finding dripline check = False #start with symmetric nucleus N=Z #iterative search for",
"the range Z=36-44 #Z = range(Z_low, Z_top+1) #N = [] # #for z",
"#interested in finding the neutron drip line for the range Z=36-44 #Z =",
"makeMatCores(Zrange): Nstart = 0 Nrange = int(2.3*Zrange) Zstart = 1 mat = np.zeros((Zrange-Zstart,Nrange-Nstart))",
"[] # #for z in Z: # dripline = findDripLine(z) # print \"For\",",
"np.zeros((Zrange-Zstart,Nrange-Nstart)) for Z in range(Zstart,Zrange): for N in range(Nstart,Nrange): BE_i_up = BE_liquidDrop(N+1,Z) BE_f_up",
"nucleons A = N+Z #physical constants (from Alex's notes, in MeV) a1 =",
"Qup = BE_f_up-BE_i_up BE_i_down = BE_liquidDrop(N+1,Z) BE_f_down = BE_liquidDrop(N,Z) Qdown = BE_f_down-BE_i_down if",
"# dripline = findDripLine(z) # print \"For\", z,\"protons, the neutron dripline is\",dripline, \"neutrons\"",
"symmetric nucleus N=Z #iterative search for dripline while (check == False): BE_i =",
"range Z=36-44 #Z = range(Z_low, Z_top+1) #N = [] # #for z in",
"binding energy predicted by nuclear liquid drop model def BE_liquidDrop(N,Z): #N=num of neutrons,",
"Z's Z_low = 2 Z_top = 150 mat = makeMatCores(Z_top) img2 = plt.imshow(mat,interpolation='nearest',",
"print \"For\", z,\"protons, the neutron dripline is\",dripline, \"neutrons\" # N.append(dripline) # #mat =",
"\"For\", z,\"protons, the neutron dripline is\",dripline, \"neutrons\" # N.append(dripline) # #mat = np.zeros((max(Z)+1,max(N)+1))",
"# #mat = np.zeros((max(Z)+1,max(N)+1)) # #for i in range(0,len(Z)): # mat[Z[i],N[i]] = 1",
"model return a1*A - a2*A**(2./3) - a3*(Z**2)/(A*(1./3)) - a4*(N-Z)**2/A #finds the neutron dripline",
"= BE_liquidDrop(N,Z) Qup = BE_f_up-BE_i_up BE_i_down = BE_liquidDrop(N+1,Z) BE_f_down = BE_liquidDrop(N,Z) Qdown =",
"MeV) a1 = 15.49 a2 = 17.23 a3 = 0.697 a4 = 22.6",
"= BE_f-BE_i if (Q>0): return N else: N = N+1 def makeMatCores(Zrange): Nstart",
"Z in range(Zstart,Zrange): for N in range(Nstart,Nrange): BE_i_up = BE_liquidDrop(N+1,Z) BE_f_up = BE_liquidDrop(N,Z)",
"= 2 Z_top = 150 mat = makeMatCores(Z_top) img2 = plt.imshow(mat,interpolation='nearest', origin='lower') plt.show()",
"for finding dripline check = False #start with symmetric nucleus N=Z #iterative search",
"model def BE_liquidDrop(N,Z): #N=num of neutrons, Z=num of protons #num of nucleons A",
"BE_f_down-BE_i_down if (Q<0): mat[Z-Zstart, N-Nstart] = 1 else: mat[Z-Zstart, N-Nstart] = 0 return",
"- a4*(N-Z)**2/A #finds the neutron dripline def findDripLine(Z): #test statement for finding dripline",
"notes, in MeV) a1 = 15.49 a2 = 17.23 a3 = 0.697 a4",
"drop model def BE_liquidDrop(N,Z): #N=num of neutrons, Z=num of protons #num of nucleons",
"BE_liquidDrop(N,Z) Qup = BE_f_up-BE_i_up BE_i_down = BE_liquidDrop(N+1,Z) BE_f_down = BE_liquidDrop(N,Z) Qdown = BE_f_down-BE_i_down",
"dripline def findDripLine(Z): #test statement for finding dripline check = False #start with"
] |
[
"import * from DNAInteractiveProp import DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp): def __init__(self): DNAInteractiveProp.__init__(self) self.anim =",
"DNAInteractiveProp import DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp): def __init__(self): DNAInteractiveProp.__init__(self) self.anim = '' def setAnim(self,",
"def __init__(self): DNAInteractiveProp.__init__(self) self.anim = '' def setAnim(self, anim): self.anim = anim def",
"import DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp): def __init__(self): DNAInteractiveProp.__init__(self) self.anim = '' def setAnim(self, anim):",
"import * from panda3d.core import * from DNAInteractiveProp import DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp): def",
"from panda3d.core import * from DNAInteractiveProp import DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp): def __init__(self): DNAInteractiveProp.__init__(self)",
"* from panda3d.core import * from DNAInteractiveProp import DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp): def __init__(self):",
"__init__(self): DNAInteractiveProp.__init__(self) self.anim = '' def setAnim(self, anim): self.anim = anim def getAnim(self):",
"* from DNAInteractiveProp import DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp): def __init__(self): DNAInteractiveProp.__init__(self) self.anim = ''",
"DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp): def __init__(self): DNAInteractiveProp.__init__(self) self.anim = '' def setAnim(self, anim): self.anim",
"pandac.PandaModules import * from panda3d.core import * from DNAInteractiveProp import DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp):",
"from pandac.PandaModules import * from panda3d.core import * from DNAInteractiveProp import DNAInteractiveProp class",
"class DNAAnimBuilding(DNAInteractiveProp): def __init__(self): DNAInteractiveProp.__init__(self) self.anim = '' def setAnim(self, anim): self.anim =",
"<reponame>Toonerz/libdna<filename>src/DNAAnimBuilding.py from pandac.PandaModules import * from panda3d.core import * from DNAInteractiveProp import DNAInteractiveProp",
"DNAInteractiveProp.__init__(self) self.anim = '' def setAnim(self, anim): self.anim = anim def getAnim(self): return",
"from DNAInteractiveProp import DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp): def __init__(self): DNAInteractiveProp.__init__(self) self.anim = '' def",
"panda3d.core import * from DNAInteractiveProp import DNAInteractiveProp class DNAAnimBuilding(DNAInteractiveProp): def __init__(self): DNAInteractiveProp.__init__(self) self.anim",
"self.anim = '' def setAnim(self, anim): self.anim = anim def getAnim(self): return self.anim",
"DNAAnimBuilding(DNAInteractiveProp): def __init__(self): DNAInteractiveProp.__init__(self) self.anim = '' def setAnim(self, anim): self.anim = anim"
] |
[] |
[
"__init__(self, parent: wx.Window, gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent, -1) self._renderer = gc_app self._renderer.swap_buffers =",
"key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer): def __init__(self, canvas: GCraftCanvas): wx.Timer.__init__(self) self.canvas = canvas",
"mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if event.GetEventType() == wx.wxEVT_RIGHT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE,",
"gcraft.core.input_event import InputEvent import wx from wx import glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self,",
"InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] - event.X, mouse_dy=self._last_mouse_pos[1] - event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0] =",
"wx.Window, gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent, -1) self._renderer = gc_app self._renderer.swap_buffers = self.on_swap_buffers self._renderer_inited",
"on_resize_event(self, event): wx.CallAfter(self.resize) event.Skip() def on_paint_event(self, event): self.SetCurrent(self._context) if not self._renderer_inited: self.init() self.render()",
"10) def stop(self): wx.Timer.Stop(self) def Notify(self): self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas): def __init__(self, parent: wx.Window,",
"self.render() self.Refresh(False) def on_mouse_event(self, event): if event.GetEventType() == wx.wxEVT_LEFT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X,",
"input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_MOTION:",
"InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_LEFT_UP: input_event =",
"to avoid flashing on MSW. def on_resize_event(self, event): wx.CallAfter(self.resize) event.Skip() def on_paint_event(self, event):",
"InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer): def __init__(self, canvas: GCraftCanvas): wx.Timer.__init__(self)",
"input_event = InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] - event.X, mouse_dy=self._last_mouse_pos[1] - event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event)",
"self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def init(self): glutInit() self._renderer_inited = True",
"canvas def start(self): wx.Timer.Start(self, 10) def stop(self): wx.Timer.Stop(self) def Notify(self): self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas):",
"MSW. def on_resize_event(self, event): wx.CallAfter(self.resize) event.Skip() def on_paint_event(self, event): self.SetCurrent(self._context) if not self._renderer_inited:",
"self._renderer_inited: self.init() self.render() self.Refresh(False) def on_mouse_event(self, event): if event.GetEventType() == wx.wxEVT_LEFT_DOWN: input_event =",
"wx.wxEVT_RIGHT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() ==",
"InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if event.GetEventType() == wx.wxEVT_RIGHT_DOWN: input_event =",
"def start(self): wx.Timer.Start(self, 10) def stop(self): wx.Timer.Stop(self) def Notify(self): self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas): def",
"def __init__(self, parent: wx.Window, gc_app: GCraftApp): GCraftCanvas.__init__(self, parent, gc_app) self.renderer_timer = GCraftContinuousRenderer(self) def",
"key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def on_key_up_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event)",
"self.canvas = canvas def start(self): wx.Timer.Start(self, 10) def stop(self): wx.Timer.Stop(self) def Notify(self): self.canvas.Refresh(False)",
"self._context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event)",
"pass # Do nothing, to avoid flashing on MSW. def on_resize_event(self, event): wx.CallAfter(self.resize)",
"self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer): def __init__(self, canvas: GCraftCanvas): wx.Timer.__init__(self) self.canvas = canvas def start(self):",
"self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_LEFT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event)",
"self.SetCurrent(self._context) if not self._renderer_inited: self.init() self.render() self.Refresh(False) def on_mouse_event(self, event): if event.GetEventType() ==",
"event): input_event = InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def on_key_up_event(self, event): input_event",
"wx import glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent,",
"event.X self._last_mouse_pos[1] = event.Y def on_key_down_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode())",
"event.Y] input_event = InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] - event.X, mouse_dy=self._last_mouse_pos[1] - event.Y) self._renderer.input_state.update_state(input_event)",
"def on_resize_event(self, event): wx.CallAfter(self.resize) event.Skip() def on_paint_event(self, event): self.SetCurrent(self._context) if not self._renderer_inited: self.init()",
"mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_MOTION: if self._last_mouse_pos is",
"InputEvent import wx from wx import glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent: wx.Window,",
"self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): GCraftCanvas.__init__(self, parent, gc_app) self.renderer_timer",
"[event.X, event.Y] input_event = InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] - event.X, mouse_dy=self._last_mouse_pos[1] - event.Y)",
"= InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_RIGHT_UP: input_event",
"self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_MOTION: if self._last_mouse_pos is None: self._last_mouse_pos = [event.X,",
"render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self): self.SwapBuffers() def on_erase_background_event(self, event): pass # Do nothing,",
"event.GetEventType() == wx.wxEVT_MOTION: if self._last_mouse_pos is None: self._last_mouse_pos = [event.X, event.Y] input_event =",
"== wx.wxEVT_LEFT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType()",
"def on_paint_event(self, event): self.SetCurrent(self._context) if not self._renderer_inited: self.init() self.render() self.Refresh(False) def on_mouse_event(self, event):",
"self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height) def render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self): self.SwapBuffers() def on_erase_background_event(self,",
"mouse_y=event.Y, mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_LEFT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X,",
"self._last_mouse_pos[1] = event.Y def on_key_down_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event)",
"stop(self): wx.Timer.Stop(self) def Notify(self): self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp):",
"Notify(self): self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): GCraftCanvas.__init__(self, parent, gc_app)",
"InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def on_key_up_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y,",
"def resize(self): if self._renderer_inited: size = self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height) def render(self): self._renderer.on_render()",
"event): self.SetCurrent(self._context) if not self._renderer_inited: self.init() self.render() self.Refresh(False) def on_mouse_event(self, event): if event.GetEventType()",
"mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer): def __init__(self, canvas: GCraftCanvas): wx.Timer.__init__(self) self.canvas",
"self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_LEFT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=False)",
"== wx.wxEVT_RIGHT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType()",
"None: self._last_mouse_pos = [event.X, event.Y] input_event = InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] - event.X,",
"if not self._renderer_inited: self.init() self.render() self.Refresh(False) def on_mouse_event(self, event): if event.GetEventType() == wx.wxEVT_LEFT_DOWN:",
"wx.Timer.__init__(self) self.canvas = canvas def start(self): wx.Timer.Start(self, 10) def stop(self): wx.Timer.Stop(self) def Notify(self):",
"import * from gcraft.core.app import GCraftApp from gcraft.core.input_event import InputEvent import wx from",
"import InputEvent import wx from wx import glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent:",
"self._renderer_inited = True self._renderer.on_init() self.resize() def resize(self): if self._renderer_inited: size = self.GetClientSize() self.SetCurrent(self._context)",
"event): if event.GetEventType() == wx.wxEVT_LEFT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event)",
"size.height) def render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self): self.SwapBuffers() def on_erase_background_event(self, event): pass #",
"avoid flashing on MSW. def on_resize_event(self, event): wx.CallAfter(self.resize) event.Skip() def on_paint_event(self, event): self.SetCurrent(self._context)",
"self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_RIGHT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=False)",
"= False self._last_mouse_pos = None self._context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT,",
"on_swap_buffers(self): self.SwapBuffers() def on_erase_background_event(self, event): pass # Do nothing, to avoid flashing on",
"def __init__(self, canvas: GCraftCanvas): wx.Timer.__init__(self) self.canvas = canvas def start(self): wx.Timer.Start(self, 10) def",
"def on_mouse_event(self, event): if event.GetEventType() == wx.wxEVT_LEFT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0,",
"GCraftCanvas): wx.Timer.__init__(self) self.canvas = canvas def start(self): wx.Timer.Start(self, 10) def stop(self): wx.Timer.Stop(self) def",
"event): pass # Do nothing, to avoid flashing on MSW. def on_resize_event(self, event):",
"not self._renderer_inited: self.init() self.render() self.Refresh(False) def on_mouse_event(self, event): if event.GetEventType() == wx.wxEVT_LEFT_DOWN: input_event",
"self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def on_key_up_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event)",
"GCraftContinuousRenderer(wx.Timer): def __init__(self, canvas: GCraftCanvas): wx.Timer.__init__(self) self.canvas = canvas def start(self): wx.Timer.Start(self, 10)",
"mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if event.GetEventType() == wx.wxEVT_RIGHT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y,",
"parent: wx.Window, gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent, -1) self._renderer = gc_app self._renderer.swap_buffers = self.on_swap_buffers",
"= None self._context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event)",
"self._renderer.on_init() self.resize() def resize(self): if self._renderer_inited: size = self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height) def",
"flashing on MSW. def on_resize_event(self, event): wx.CallAfter(self.resize) event.Skip() def on_paint_event(self, event): self.SetCurrent(self._context) if",
"mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_LEFT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y,",
"elif event.GetEventType() == wx.wxEVT_MOTION: if self._last_mouse_pos is None: self._last_mouse_pos = [event.X, event.Y] input_event",
"self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height) def render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self): self.SwapBuffers() def on_erase_background_event(self, event):",
"event.GetEventType() == wx.wxEVT_LEFT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if",
"parent, -1) self._renderer = gc_app self._renderer.swap_buffers = self.on_swap_buffers self._renderer_inited = False self._last_mouse_pos =",
"self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def",
"from wx import glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self,",
"input_event = InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer): def __init__(self, canvas:",
"wx.wxEVT_RIGHT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() ==",
"from gcraft.core.app import GCraftApp from gcraft.core.input_event import InputEvent import wx from wx import",
"state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_LEFT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0,",
"input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_RIGHT_UP:",
"self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0] = event.X self._last_mouse_pos[1] = event.Y def on_key_down_event(self, event): input_event =",
"event.Skip() def on_paint_event(self, event): self.SetCurrent(self._context) if not self._renderer_inited: self.init() self.render() self.Refresh(False) def on_mouse_event(self,",
"class GCraftContinuousCanvas(GCraftCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): GCraftCanvas.__init__(self, parent, gc_app) self.renderer_timer =",
"class GCraftContinuousRenderer(wx.Timer): def __init__(self, canvas: GCraftCanvas): wx.Timer.__init__(self) self.canvas = canvas def start(self): wx.Timer.Start(self,",
"on MSW. def on_resize_event(self, event): wx.CallAfter(self.resize) event.Skip() def on_paint_event(self, event): self.SetCurrent(self._context) if not",
"GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent, -1) self._renderer = gc_app",
"wx.glcanvas.GLCanvas.__init__(self, parent, -1) self._renderer = gc_app self._renderer.swap_buffers = self.on_swap_buffers self._renderer_inited = False self._last_mouse_pos",
"if self._last_mouse_pos is None: self._last_mouse_pos = [event.X, event.Y] input_event = InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y,",
"self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self): self.SwapBuffers() def on_erase_background_event(self, event): pass # Do nothing, to avoid",
"self.on_swap_buffers self._renderer_inited = False self._last_mouse_pos = None self._context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE,",
"self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def init(self): glutInit() self._renderer_inited = True self._renderer.on_init() self.resize() def",
"= InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_MOTION: if",
"gcraft.core.app import GCraftApp from gcraft.core.input_event import InputEvent import wx from wx import glcanvas",
"event.Y def on_key_down_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def",
"wx from wx import glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp):",
"event.X, mouse_dy=self._last_mouse_pos[1] - event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0] = event.X self._last_mouse_pos[1] = event.Y def",
"from OpenGL.GLUT import * from gcraft.core.app import GCraftApp from gcraft.core.input_event import InputEvent import",
"= InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] - event.X, mouse_dy=self._last_mouse_pos[1] - event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0]",
"on_key_up_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer): def",
"= self.on_swap_buffers self._renderer_inited = False self._last_mouse_pos = None self._context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event)",
"= wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP,",
"= self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height) def render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self): self.SwapBuffers() def",
"self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self): self.SwapBuffers() def on_erase_background_event(self, event): pass # Do nothing, to",
"canvas: GCraftCanvas): wx.Timer.__init__(self) self.canvas = canvas def start(self): wx.Timer.Start(self, 10) def stop(self): wx.Timer.Stop(self)",
"mouse_y=event.Y, mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if event.GetEventType() == wx.wxEVT_RIGHT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X,",
"== wx.wxEVT_RIGHT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType()",
"state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_MOTION: if self._last_mouse_pos is None: self._last_mouse_pos =",
"def on_erase_background_event(self, event): pass # Do nothing, to avoid flashing on MSW. def",
"import glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent, -1)",
"init(self): glutInit() self._renderer_inited = True self._renderer.on_init() self.resize() def resize(self): if self._renderer_inited: size =",
"self._last_mouse_pos = [event.X, event.Y] input_event = InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] - event.X, mouse_dy=self._last_mouse_pos[1]",
"gc_app: GCraftApp): GCraftCanvas.__init__(self, parent, gc_app) self.renderer_timer = GCraftContinuousRenderer(self) def start(self): self.renderer_timer.start() def stop(self):",
"def on_key_down_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def on_key_up_event(self,",
"wx.Timer.Start(self, 10) def stop(self): wx.Timer.Stop(self) def Notify(self): self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas): def __init__(self, parent:",
"self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def init(self): glutInit() self._renderer_inited = True self._renderer.on_init() self.resize() def resize(self):",
"def stop(self): wx.Timer.Stop(self) def Notify(self): self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas): def __init__(self, parent: wx.Window, gc_app:",
"wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event)",
"True self._renderer.on_init() self.resize() def resize(self): if self._renderer_inited: size = self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height)",
"self._last_mouse_pos[0] = event.X self._last_mouse_pos[1] = event.Y def on_key_down_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y,",
"mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_LEFT_UP: input_event = InputEvent(InputEvent.IE_MOUSE,",
"gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent, -1) self._renderer = gc_app self._renderer.swap_buffers = self.on_swap_buffers self._renderer_inited =",
"self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer): def __init__(self, canvas: GCraftCanvas): wx.Timer.__init__(self) self.canvas = canvas def",
"start(self): wx.Timer.Start(self, 10) def stop(self): wx.Timer.Stop(self) def Notify(self): self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas): def __init__(self,",
"event.GetEventType() == wx.wxEVT_RIGHT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif",
"input_event = InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def on_key_up_event(self, event): input_event =",
"mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def on_key_up_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y,",
"state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if event.GetEventType() == wx.wxEVT_RIGHT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1,",
"GCraftApp from gcraft.core.input_event import InputEvent import wx from wx import glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas):",
"mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] - event.X, mouse_dy=self._last_mouse_pos[1] - event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0] = event.X self._last_mouse_pos[1]",
"def __init__(self, parent: wx.Window, gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent, -1) self._renderer = gc_app self._renderer.swap_buffers",
"= InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if event.GetEventType() == wx.wxEVT_RIGHT_DOWN: input_event",
"event.GetEventType() == wx.wxEVT_RIGHT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif",
"= canvas def start(self): wx.Timer.Start(self, 10) def stop(self): wx.Timer.Stop(self) def Notify(self): self.canvas.Refresh(False) class",
"__init__(self, parent: wx.Window, gc_app: GCraftApp): GCraftCanvas.__init__(self, parent, gc_app) self.renderer_timer = GCraftContinuousRenderer(self) def start(self):",
"self._renderer.swap_buffers = self.on_swap_buffers self._renderer_inited = False self._last_mouse_pos = None self._context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND,",
"self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def init(self): glutInit() self._renderer_inited = True self._renderer.on_init() self.resize()",
"- event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0] = event.X self._last_mouse_pos[1] = event.Y def on_key_down_event(self, event):",
"None self._context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN,",
"mouse_dx=self._last_mouse_pos[0] - event.X, mouse_dy=self._last_mouse_pos[1] - event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0] = event.X self._last_mouse_pos[1] =",
"= True self._renderer.on_init() self.resize() def resize(self): if self._renderer_inited: size = self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width,",
"import wx from wx import glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent: wx.Window, gc_app:",
"self._renderer_inited = False self._last_mouse_pos = None self._context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event)",
"gc_app self._renderer.swap_buffers = self.on_swap_buffers self._renderer_inited = False self._last_mouse_pos = None self._context = wx.glcanvas.GLContext(self)",
"on_mouse_event(self, event): if event.GetEventType() == wx.wxEVT_LEFT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=True)",
"self.init() self.render() self.Refresh(False) def on_mouse_event(self, event): if event.GetEventType() == wx.wxEVT_LEFT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE,",
"input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if event.GetEventType() == wx.wxEVT_RIGHT_DOWN:",
"self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if event.GetEventType() == wx.wxEVT_RIGHT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=True)",
"__init__(self, canvas: GCraftCanvas): wx.Timer.__init__(self) self.canvas = canvas def start(self): wx.Timer.Start(self, 10) def stop(self):",
"nothing, to avoid flashing on MSW. def on_resize_event(self, event): wx.CallAfter(self.resize) event.Skip() def on_paint_event(self,",
"<gh_stars>0 from OpenGL.GLUT import * from gcraft.core.app import GCraftApp from gcraft.core.input_event import InputEvent",
"resize(self): if self._renderer_inited: size = self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height) def render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement()",
"= gc_app self._renderer.swap_buffers = self.on_swap_buffers self._renderer_inited = False self._last_mouse_pos = None self._context =",
"input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_LEFT_UP:",
"mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_MOTION: if self._last_mouse_pos is None: self._last_mouse_pos",
"OpenGL.GLUT import * from gcraft.core.app import GCraftApp from gcraft.core.input_event import InputEvent import wx",
"self.resize() def resize(self): if self._renderer_inited: size = self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height) def render(self):",
"self.Refresh(False) def on_mouse_event(self, event): if event.GetEventType() == wx.wxEVT_LEFT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y,",
"InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_MOTION: if self._last_mouse_pos",
"event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0] = event.X self._last_mouse_pos[1] = event.Y def on_key_down_event(self, event): input_event",
"GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent, -1) self._renderer = gc_app self._renderer.swap_buffers = self.on_swap_buffers self._renderer_inited = False",
"self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def init(self): glutInit() self._renderer_inited = True self._renderer.on_init() self.resize() def resize(self): if",
"InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_RIGHT_UP: input_event =",
"= InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer): def __init__(self, canvas: GCraftCanvas):",
"wx.wxEVT_LEFT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if event.GetEventType() ==",
"import GCraftApp from gcraft.core.input_event import InputEvent import wx from wx import glcanvas class",
"glutInit() self._renderer_inited = True self._renderer.on_init() self.resize() def resize(self): if self._renderer_inited: size = self.GetClientSize()",
"state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_RIGHT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1,",
"- event.X, mouse_dy=self._last_mouse_pos[1] - event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0] = event.X self._last_mouse_pos[1] = event.Y",
"on_key_down_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def on_key_up_event(self, event):",
"self._renderer.on_reshape(size.width, size.height) def render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self): self.SwapBuffers() def on_erase_background_event(self, event): pass",
"mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def on_key_up_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode())",
"from gcraft.core.input_event import InputEvent import wx from wx import glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas): def",
"class GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent, -1) self._renderer =",
"mouse_y=event.Y, mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_MOTION: if self._last_mouse_pos is None:",
"self._renderer = gc_app self._renderer.swap_buffers = self.on_swap_buffers self._renderer_inited = False self._last_mouse_pos = None self._context",
"mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_RIGHT_UP: input_event = InputEvent(InputEvent.IE_MOUSE,",
"if event.GetEventType() == wx.wxEVT_LEFT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event)",
"mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] - event.X, mouse_dy=self._last_mouse_pos[1] - event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0] = event.X",
"self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_RIGHT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event)",
"def on_swap_buffers(self): self.SwapBuffers() def on_erase_background_event(self, event): pass # Do nothing, to avoid flashing",
"self.on_key_up_event) def init(self): glutInit() self._renderer_inited = True self._renderer.on_init() self.resize() def resize(self): if self._renderer_inited:",
"self._renderer.on_input(input_event) if event.GetEventType() == wx.wxEVT_RIGHT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event)",
"if self._renderer_inited: size = self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height) def render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def",
"self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def init(self): glutInit() self._renderer_inited = True self._renderer.on_init()",
"self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def init(self):",
"== wx.wxEVT_MOTION: if self._last_mouse_pos is None: self._last_mouse_pos = [event.X, event.Y] input_event = InputEvent(InputEvent.IE_MOUSE_MOVE,",
"if event.GetEventType() == wx.wxEVT_RIGHT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event)",
"= InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_LEFT_UP: input_event",
"parent: wx.Window, gc_app: GCraftApp): GCraftCanvas.__init__(self, parent, gc_app) self.renderer_timer = GCraftContinuousRenderer(self) def start(self): self.renderer_timer.start()",
"on_erase_background_event(self, event): pass # Do nothing, to avoid flashing on MSW. def on_resize_event(self,",
"wx.Timer.Stop(self) def Notify(self): self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): GCraftCanvas.__init__(self,",
"event): input_event = InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer): def __init__(self,",
"* from gcraft.core.app import GCraftApp from gcraft.core.input_event import InputEvent import wx from wx",
"glcanvas class GCraftCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): wx.glcanvas.GLCanvas.__init__(self, parent, -1) self._renderer",
"on_paint_event(self, event): self.SetCurrent(self._context) if not self._renderer_inited: self.init() self.render() self.Refresh(False) def on_mouse_event(self, event): if",
"elif event.GetEventType() == wx.wxEVT_RIGHT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=1, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event)",
"self._last_mouse_pos is None: self._last_mouse_pos = [event.X, event.Y] input_event = InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0]",
"False self._last_mouse_pos = None self._context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event)",
"self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_MOTION: if self._last_mouse_pos is None: self._last_mouse_pos = [event.X, event.Y]",
"mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer): def __init__(self, canvas: GCraftCanvas): wx.Timer.__init__(self) self.canvas =",
"is None: self._last_mouse_pos = [event.X, event.Y] input_event = InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] -",
"GCraftContinuousCanvas(GCraftCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): GCraftCanvas.__init__(self, parent, gc_app) self.renderer_timer = GCraftContinuousRenderer(self)",
"self._renderer_inited: size = self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height) def render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self):",
"wx.wxEVT_LEFT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() ==",
"Do nothing, to avoid flashing on MSW. def on_resize_event(self, event): wx.CallAfter(self.resize) event.Skip() def",
"= event.X self._last_mouse_pos[1] = event.Y def on_key_down_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y,",
"-1) self._renderer = gc_app self._renderer.swap_buffers = self.on_swap_buffers self._renderer_inited = False self._last_mouse_pos = None",
"# Do nothing, to avoid flashing on MSW. def on_resize_event(self, event): wx.CallAfter(self.resize) event.Skip()",
"= event.Y def on_key_down_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event)",
"def on_key_up_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class GCraftContinuousRenderer(wx.Timer):",
"mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_RIGHT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y,",
"self._last_mouse_pos = None self._context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background_event) self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS,",
"mouse_dy=self._last_mouse_pos[1] - event.Y) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) self._last_mouse_pos[0] = event.X self._last_mouse_pos[1] = event.Y def on_key_down_event(self,",
"event.GetEventType() == wx.wxEVT_LEFT_DOWN: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif",
"self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def init(self): glutInit() self._renderer_inited =",
"self.SwapBuffers() def on_erase_background_event(self, event): pass # Do nothing, to avoid flashing on MSW.",
"elif event.GetEventType() == wx.wxEVT_LEFT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event)",
"= InputEvent(InputEvent.IE_KEY_DOWN, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) def on_key_up_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_UP,",
"self.Bind(wx.EVT_SIZE, self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def init(self): glutInit()",
"def init(self): glutInit() self._renderer_inited = True self._renderer.on_init() self.resize() def resize(self): if self._renderer_inited: size",
"self._renderer.on_input(input_event) def on_key_up_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_UP, mouse_x=event.Y, mouse_y=event.Y, key=event.GetKeyCode()) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) class",
"def Notify(self): self.canvas.Refresh(False) class GCraftContinuousCanvas(GCraftCanvas): def __init__(self, parent: wx.Window, gc_app: GCraftApp): GCraftCanvas.__init__(self, parent,",
"self._renderer.on_input(input_event) self._last_mouse_pos[0] = event.X self._last_mouse_pos[1] = event.Y def on_key_down_event(self, event): input_event = InputEvent(InputEvent.IE_KEY_DOWN,",
"GCraftApp): GCraftCanvas.__init__(self, parent, gc_app) self.renderer_timer = GCraftContinuousRenderer(self) def start(self): self.renderer_timer.start() def stop(self): self.renderer_timer.stop()",
"def render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self): self.SwapBuffers() def on_erase_background_event(self, event): pass # Do",
"wx.wxEVT_MOTION: if self._last_mouse_pos is None: self._last_mouse_pos = [event.X, event.Y] input_event = InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X,",
"self.on_resize_event) self.Bind(wx.EVT_PAINT, self.on_paint_event) self.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) self.Bind(wx.EVT_KEY_DOWN, self.on_key_down_event) self.Bind(wx.EVT_KEY_UP, self.on_key_up_event) def init(self): glutInit() self._renderer_inited",
"wx.CallAfter(self.resize) event.Skip() def on_paint_event(self, event): self.SetCurrent(self._context) if not self._renderer_inited: self.init() self.render() self.Refresh(False) def",
"= [event.X, event.Y] input_event = InputEvent(InputEvent.IE_MOUSE_MOVE, mouse_x=event.X, mouse_y=event.Y, mouse_dx=self._last_mouse_pos[0] - event.X, mouse_dy=self._last_mouse_pos[1] -",
"== wx.wxEVT_LEFT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X, mouse_y=event.Y, mouse_btn=0, state=False) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) if event.GetEventType()",
"size = self.GetClientSize() self.SetCurrent(self._context) self._renderer.on_reshape(size.width, size.height) def render(self): self._renderer.on_render() self._renderer.input_state.clear_mouse_movement() def on_swap_buffers(self): self.SwapBuffers()",
"event): wx.CallAfter(self.resize) event.Skip() def on_paint_event(self, event): self.SetCurrent(self._context) if not self._renderer_inited: self.init() self.render() self.Refresh(False)",
"wx.Window, gc_app: GCraftApp): GCraftCanvas.__init__(self, parent, gc_app) self.renderer_timer = GCraftContinuousRenderer(self) def start(self): self.renderer_timer.start() def",
"mouse_y=event.Y, mouse_btn=1, state=True) self._renderer.input_state.update_state(input_event) self._renderer.on_input(input_event) elif event.GetEventType() == wx.wxEVT_RIGHT_UP: input_event = InputEvent(InputEvent.IE_MOUSE, mouse_x=event.X,"
] |
[
"/ (1 + np.exp(-x)) class LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter) def fit(self,x,y): x=np.insert(x,",
"np.exp(-x)) class LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter) def fit(self,x,y): x=np.insert(x, 0, values=1, axis=1)",
"x=np.insert(x, 0, values=1, axis=1) return sigmoid(x.dot(self.w)) if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0)",
"i in range(self.iter): p = sigmoid(x.dot(w)) w -= self.lr * x.T.dot(p - y)",
"self.w=w def predict(self,x): x=np.insert(x, 0, values=1, axis=1) return sigmoid(x.dot(self.w)) if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data)",
"np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y) import sklearn.metrics",
"self.iter=int(niter) def fit(self,x,y): x=np.insert(x, 0, values=1, axis=1) w=np.random.uniform(size=(x.shape[1])) for i in range(self.iter): p",
"as f: for i in range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) ''' with open('acc_lr.csv','w') as",
"i in range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) ''' with open('acc_lr.csv','w') as f: for i",
"as np np.random.seed(10) def sigmoid(x): return 1 / (1 + np.exp(-x)) class LogisticsReg():",
"axis=1) return sigmoid(x.dot(self.w)) if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1]",
"sigmoid(x): return 1 / (1 + np.exp(-x)) class LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter)",
"__init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter) def fit(self,x,y): x=np.insert(x, 0, values=1, axis=1) w=np.random.uniform(size=(x.shape[1])) for i in",
"import numpy as np np.random.seed(10) def sigmoid(x): return 1 / (1 + np.exp(-x))",
"axis=1) w=np.random.uniform(size=(x.shape[1])) for i in range(self.iter): p = sigmoid(x.dot(w)) w -= self.lr *",
"def fit(self,x,y): x=np.insert(x, 0, values=1, axis=1) w=np.random.uniform(size=(x.shape[1])) for i in range(self.iter): p =",
"x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y) import sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with open('acc_thres.csv','w') as",
"np.random.seed(10) def sigmoid(x): return 1 / (1 + np.exp(-x)) class LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000):",
"x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y) import sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with open('acc_thres.csv','w') as f: for",
"sigmoid(x.dot(w)) w -= self.lr * x.T.dot(p - y) self.w=w def predict(self,x): x=np.insert(x, 0,",
"- y) self.w=w def predict(self,x): x=np.insert(x, 0, values=1, axis=1) return sigmoid(x.dot(self.w)) if __name__=='__main__':",
"1 / (1 + np.exp(-x)) class LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter) def fit(self,x,y):",
"sigmoid(x.dot(self.w)) if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std",
"+ np.exp(-x)) class LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter) def fit(self,x,y): x=np.insert(x, 0, values=1,",
"__name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y)",
"<reponame>xyk2000/LogisticsRegression<filename>lr.py import numpy as np np.random.seed(10) def sigmoid(x): return 1 / (1 +",
"values=1, axis=1) w=np.random.uniform(size=(x.shape[1])) for i in range(self.iter): p = sigmoid(x.dot(w)) w -= self.lr",
"y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y) import sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with open('acc_thres.csv','w') as f:",
"pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) ''' with open('acc_lr.csv','w') as f: for i in range(-10,1): model=LogisticsReg(10**i)",
"model=LogisticsReg() model.fit(x,y) import sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with open('acc_thres.csv','w') as f: for i",
"with open('acc_lr.csv','w') as f: for i in range(-10,1): model=LogisticsReg(10**i) model.fit(x,y) pred=model.predict(x_val)>0.5 acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(10**i,acc))",
"data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y) import",
"predict(self,x): x=np.insert(x, 0, values=1, axis=1) return sigmoid(x.dot(self.w)) if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1]",
"x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y) import sklearn.metrics pred=model.predict(x_val)",
"values=1, axis=1) return sigmoid(x.dot(self.w)) if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std",
"acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) ''' with open('acc_lr.csv','w') as f: for i in range(-10,1): model=LogisticsReg(10**i) model.fit(x,y)",
"open('acc_thres.csv','w') as f: for i in range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) ''' with open('acc_lr.csv','w')",
"in range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) ''' with open('acc_lr.csv','w') as f: for i in",
"mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y) import sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) '''",
"std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y) import sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with",
"def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter) def fit(self,x,y): x=np.insert(x, 0, values=1, axis=1) w=np.random.uniform(size=(x.shape[1])) for i",
"print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with open('acc_thres.csv','w') as f: for i in range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc))",
"x.T.dot(p - y) self.w=w def predict(self,x): x=np.insert(x, 0, values=1, axis=1) return sigmoid(x.dot(self.w)) if",
"y) self.w=w def predict(self,x): x=np.insert(x, 0, values=1, axis=1) return sigmoid(x.dot(self.w)) if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1)",
"self.lr * x.T.dot(p - y) self.w=w def predict(self,x): x=np.insert(x, 0, values=1, axis=1) return",
"LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter) def fit(self,x,y): x=np.insert(x, 0, values=1, axis=1) w=np.random.uniform(size=(x.shape[1])) for",
"for i in range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) ''' with open('acc_lr.csv','w') as f: for",
"w=np.random.uniform(size=(x.shape[1])) for i in range(self.iter): p = sigmoid(x.dot(w)) w -= self.lr * x.T.dot(p",
"p = sigmoid(x.dot(w)) w -= self.lr * x.T.dot(p - y) self.w=w def predict(self,x):",
"''' with open('acc_lr.csv','w') as f: for i in range(-10,1): model=LogisticsReg(10**i) model.fit(x,y) pred=model.predict(x_val)>0.5 acc=sklearn.metrics.accuracy_score(y_val,pred)",
"0, values=1, axis=1) w=np.random.uniform(size=(x.shape[1])) for i in range(self.iter): p = sigmoid(x.dot(w)) w -=",
"return 1 / (1 + np.exp(-x)) class LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter) def",
"-= self.lr * x.T.dot(p - y) self.w=w def predict(self,x): x=np.insert(x, 0, values=1, axis=1)",
"np np.random.seed(10) def sigmoid(x): return 1 / (1 + np.exp(-x)) class LogisticsReg(): def",
"sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with open('acc_thres.csv','w') as f: for i in range(100): pred=model.predict(x_val)>(i/100)",
"x=np.insert(x, 0, values=1, axis=1) w=np.random.uniform(size=(x.shape[1])) for i in range(self.iter): p = sigmoid(x.dot(w)) w",
"fit(self,x,y): x=np.insert(x, 0, values=1, axis=1) w=np.random.uniform(size=(x.shape[1])) for i in range(self.iter): p = sigmoid(x.dot(w))",
"range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) ''' with open('acc_lr.csv','w') as f: for i in range(-10,1):",
"for i in range(self.iter): p = sigmoid(x.dot(w)) w -= self.lr * x.T.dot(p -",
"range(self.iter): p = sigmoid(x.dot(w)) w -= self.lr * x.T.dot(p - y) self.w=w def",
"''' with open('acc_thres.csv','w') as f: for i in range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) '''",
"numpy as np np.random.seed(10) def sigmoid(x): return 1 / (1 + np.exp(-x)) class",
"if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg()",
"f: for i in range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) ''' with open('acc_lr.csv','w') as f:",
"= sigmoid(x.dot(w)) w -= self.lr * x.T.dot(p - y) self.w=w def predict(self,x): x=np.insert(x,",
"x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y) import sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with open('acc_thres.csv','w')",
"self.lr=learn_rate self.iter=int(niter) def fit(self,x,y): x=np.insert(x, 0, values=1, axis=1) w=np.random.uniform(size=(x.shape[1])) for i in range(self.iter):",
"class LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter) def fit(self,x,y): x=np.insert(x, 0, values=1, axis=1) w=np.random.uniform(size=(x.shape[1]))",
"return sigmoid(x.dot(self.w)) if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1]",
"w -= self.lr * x.T.dot(p - y) self.w=w def predict(self,x): x=np.insert(x, 0, values=1,",
"f.write('%s,%s\\n'%(i/100,acc)) ''' with open('acc_lr.csv','w') as f: for i in range(-10,1): model=LogisticsReg(10**i) model.fit(x,y) pred=model.predict(x_val)>0.5",
"model.fit(x,y) import sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with open('acc_thres.csv','w') as f: for i in",
"0, values=1, axis=1) return sigmoid(x.dot(self.w)) if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1] y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0)",
"y=data[:600,-1] mean=np.mean(x,axis=0) std=np.std(x,axis=0) x=(x-mean)/std x_val=data[600:,:-1] y_val=data[600:,-1] x_val=(x_val-mean)/std model=LogisticsReg() model.fit(x,y) import sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred))",
"in range(self.iter): p = sigmoid(x.dot(w)) w -= self.lr * x.T.dot(p - y) self.w=w",
"import sklearn.metrics pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with open('acc_thres.csv','w') as f: for i in range(100):",
"with open('acc_thres.csv','w') as f: for i in range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred) f.write('%s,%s\\n'%(i/100,acc)) ''' with",
"def predict(self,x): x=np.insert(x, 0, values=1, axis=1) return sigmoid(x.dot(self.w)) if __name__=='__main__': data=np.loadtxt('data.csv',delimiter=',',skiprows=1) np.random.shuffle(data) x=data[:600,:-1]",
"def sigmoid(x): return 1 / (1 + np.exp(-x)) class LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate",
"(1 + np.exp(-x)) class LogisticsReg(): def __init__(self,learn_rate=1e-3,niter=100000): self.lr=learn_rate self.iter=int(niter) def fit(self,x,y): x=np.insert(x, 0,",
"pred=model.predict(x_val) print(sklearn.metrics.roc_auc_score(y_val,pred)) ''' with open('acc_thres.csv','w') as f: for i in range(100): pred=model.predict(x_val)>(i/100) acc=sklearn.metrics.accuracy_score(y_val,pred)",
"* x.T.dot(p - y) self.w=w def predict(self,x): x=np.insert(x, 0, values=1, axis=1) return sigmoid(x.dot(self.w))"
] |
[
"!= ' ': self.layers[layerNumber + 0][key] = baseKey if shiftKey != ' ':",
"in dead_keys: if dk['char'] in self.dead_keys: self.dk_index.append(dk['char']) # remove unused characters in self.dead_keys[].{base,alt}",
"layer_has_char(base[i], 1): used_base += base[i] used_alt += alt[i] self.dead_keys[dk_id]['base'] = used_base self.dead_keys[dk_id]['alt'] =",
"self.dead_keys: base = self.dead_keys[dk_id]['base'] alt = self.dead_keys[dk_id]['alt'] used_base = '' used_alt = ''",
"out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, True)) return out ### # JSON output: keymap",
"token, value): exp = re.compile('\\\\$\\\\{' + token + '(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value, text) def",
"4) # space bar spc = SPACEBAR.copy() if 'spacebar' in cfg: for k",
"for i in range(len(base)): if layer_has_char(base[i], 0) or layer_has_char(base[i], 1): used_base += base[i]",
"for k in cfg['spacebar']: spc[k] = cfg['spacebar'][k] self.layers[0]['spce'] = ' ' self.layers[1]['spce'] =",
"enumerate(osx_keymap(self)): out = substitute_lines(out, 'LAYER_' + str(i), layer) out = substitute_lines(out, 'ACTIONS', osx_actions(self))",
"base_char odk['alt'] += alt_char def _parse_template(self, template, dead_keys, rows, layerNumber): \"\"\" Extract a",
"base_char != ODK_ID: odk['base'] += base_char odk['alt'] += alt_char def _parse_template(self, template, dead_keys,",
"'\\u2193': '\\u21d3', # ↓ ⇓ '\\u00b5': ' ', # µ (to avoid getting",
"↓ ⇓ '\\u00b5': ' ', # µ (to avoid getting `Μ` as uppercase)",
"in self.layers[0]: if self.layers[0][key] == ODK_ID: odk['alt_self'] = self.layers[2][key] break # copy the",
"self.layers[4]['spce'] = spc['altgr'] self.layers[5]['spce'] = spc['altgr_shift'] # active dead keys: self.dk_index for dk",
"and base_char != ODK_ID: odk['base'] += base_char odk['alt'] += alt_char def _parse_template(self, template,",
"dead_shift: shift[i-1] = '*' i += 6 template[2 + j * 3] =",
"name='ISO'): \"\"\" `geometry` view of the requested layers. \"\"\" rows = GEOMETRY[name]['rows'] template",
"keys: self.dk_index for dk in dead_keys: if dk['char'] in self.dead_keys: self.dk_index.append(dk['char']) # remove",
"- 1] == '*' else '') + base[i] shiftKey = ('*' if shift[i",
"DEFAULT_DEAD_KEYS: found = any((d for d in dead_keys if d['char'] == dk['char'])) if",
"= self.dead_keys[dk_id]['base'] alt = self.dead_keys[dk_id]['alt'] used_base = '' used_alt = '' for i",
"return False for dk_id in self.dead_keys: base = self.dead_keys[dk_id]['base'] alt = self.dead_keys[dk_id]['alt'] used_base",
"in self.layers[i + 2].items(): base_char = self.layers[i][name] if name != 'spce' and base_char",
"'*' else '') + base[i] shiftKey = ('*' if shift[i - 1] ==",
"klc_dk_index(self)) out = substitute_token(out, 'encoding', 'utf-16le') return out @property def xkb(self): # will",
"if self.has_altgr: self.layers[4]['spce'] = spc['altgr'] self.layers[5]['spce'] = spc['altgr_shift'] # active dead keys: self.dk_index",
"'encoding', 'utf-16le') return out @property def xkb(self): # will not work with Wayland",
"U+0027 APOSTROPHE } GEOMETRY = load_data('geometry.yaml') ### # Main # class KeyboardLayout: \"\"\"",
"rows, 4) # space bar spc = SPACEBAR.copy() if 'spacebar' in cfg: for",
"!= 'spce' and base_char != ODK_ID: odk['base'] += base_char odk['alt'] += alt_char def",
"web_deadkeys from .utils import open_local_file, load_data, text_to_lines, lines_to_text, \\ DEFAULT_DEAD_KEYS, ODK_ID ### #",
"keyboard layout to instanciate the object. \"\"\" # initialize a blank layout self.layers",
"= substitute_lines(out, 'GEOMETRY_altgr', layout.altgr) for key, value in layout.meta.items(): out = substitute_token(out, key,",
"= GEOMETRY[self.meta['geometry']]['rows'] if 'full' in cfg: full = text_to_lines(cfg['full']) self._parse_template(full, dead_keys, rows, 0)",
"6 j += 1 ### # Geometry: base, full, altgr # def _fill_template(self,",
"> ≥ '\\u2020': '\\u2021', # † ‡ '\\u2190': '\\u21d0', # ← ⇐ '\\u2191':",
"if dead_shift: shift[i-1] = '*' i += 6 template[2 + j * 3]",
"substitute_lines(out, 'ACTIONS', osx_actions(self)) out = substitute_lines(out, 'TERMINATORS', osx_terminators(self)) return out @property def klc(self):",
"if 'shift_1dk' in spc \\ else spc['1dk'] if self.has_altgr: self.layers[4]['spce'] = spc['altgr'] self.layers[5]['spce']",
"= baseKey[-1] if dead_base: base[i-1] = '*' if upper_key(baseKey) != shiftKey: shift[i] =",
"lines_to_text, \\ DEFAULT_DEAD_KEYS, ODK_ID ### # Helpers # def upper_key(letter): if len(letter) !=",
"'spacebar' in cfg: for k in cfg['spacebar']: spc[k] = cfg['spacebar'][k] self.layers[0]['spce'] = '",
"'GEOMETRY_full', layout.full) out = substitute_lines(out, 'GEOMETRY_altgr', layout.altgr) for key, value in layout.meta.items(): out",
"os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] = cfg['name'] if 'name' in cfg else filename self.meta['name8'] = cfg['name8']",
"= True else: # AltGr or 1dk colOffset = 2 shiftPrevails = False",
"klc_deadkeys(self)) out = substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self)) out = substitute_token(out, 'encoding', 'utf-16le') return out",
"= True self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows, 4) # space bar spc = SPACEBAR.copy() if",
"layout self.layers = [{}, {}, {}, {}, {}, {}] self.dead_keys = {} #",
"shiftKey.lower() if layerNumber != 0 and shiftKey == ' ': shiftKey = upper_key(baseKey)",
"GNU/Linux driver (standalone / user-space) \"\"\" out = load_tpl(self, '.xkb') out = substitute_lines(out,",
"[{}, {}, {}, {}, {}, {}] self.dead_keys = {} # dictionary subset of",
"ODK_ID: odk['base'] += base_char odk['alt'] += alt_char def _parse_template(self, template, dead_keys, rows, layerNumber):",
"rows, layerNumber): \"\"\" Fill a template with a keyboard layer. \"\"\" if layerNumber",
"+ str(i), layer) out = substitute_lines(out, 'ACTIONS', osx_actions(self)) out = substitute_lines(out, 'TERMINATORS', osx_terminators(self))",
"dead_shift = len(shiftKey) == 2 and shiftKey[0] == '*' if shiftPrevails: shift[i] =",
"for i in layers: template = self._fill_template(template, rows, i) return template @property def",
"yaml.load(open(filepath), Loader=yaml.SafeLoader) if 'extends' in cfg: path = os.path.join(os.path.dirname(filepath), cfg['extends']) ext = yaml.load(open(path),",
"shiftKey == ' ': shiftKey = upper_key(baseKey) if baseKey != ' ': self.layers[layerNumber",
"self.dk_index for dk in dead_keys: if dk['char'] in self.dead_keys: self.dk_index.append(dk['char']) # remove unused",
"keyboard layout: base + 1dk + altgr layers. \"\"\" def __init__(self, filepath): \"\"\"",
"ODK_ID ### # Helpers # def upper_key(letter): if len(letter) != 1: # dead",
"osx_terminators(self)) return out @property def klc(self): \"\"\" Windows driver (warning: requires CR/LF +",
"shift[i-1] = '*' i += 6 template[2 + j * 3] = ''.join(base)",
"† ‡ '\\u2190': '\\u21d0', # ← ⇐ '\\u2191': '\\u21d1', # ↑ ⇑ '\\u2192':",
"def keylayout(self): \"\"\" Mac OSX driver \"\"\" out = load_tpl(self, '.keylayout') for i,",
"GEOMETRY = load_data('geometry.yaml') ### # Main # class KeyboardLayout: \"\"\" Lafayette-style keyboard layout:",
"dk_id in self.dead_keys: base = self.dead_keys[dk_id]['base'] alt = self.dead_keys[dk_id]['alt'] used_base = '' used_alt",
"colOffset = 2 j = 0 for row in rows: i = row['offset']",
"= ' ' if key in self.layers[layerNumber]: baseKey = self.layers[layerNumber][key] shiftKey = '",
"cfg['deadkeys'] for dk in DEFAULT_DEAD_KEYS: found = any((d for d in dead_keys if",
"' if key in self.layers[layerNumber + 1]: shiftKey = self.layers[layerNumber + 1][key] dead_base",
"* 3]) for key in keys: baseKey = ' ' if key in",
"self.layers[layerNumber]: baseKey = self.layers[layerNumber][key] shiftKey = ' ' if key in self.layers[layerNumber +",
"= substitute_lines(out, 'LAYER_' + str(i), layer) out = substitute_lines(out, 'ACTIONS', osx_actions(self)) out =",
"for (name, alt_char) in self.layers[i + 2].items(): base_char = self.layers[i][name] if name !=",
"out @property def xkb(self): # will not work with Wayland \"\"\" GNU/Linux driver",
"load_data, text_to_lines, lines_to_text, \\ DEFAULT_DEAD_KEYS, ODK_ID ### # Helpers # def upper_key(letter): if",
"!= ' ': self.layers[layerNumber + 1][key] = shiftKey for dk in dead_keys: if",
"= load_tpl(self, '.keylayout') for i, layer in enumerate(osx_keymap(self)): out = substitute_lines(out, 'LAYER_' +",
"not in ['base', 'full', 'altgr', 'spacebar', 'deadkeys']: self.meta[k] = cfg[k] filename = os.path.splitext(os.path.basename(filepath))[0]",
"self.meta['fileName'] = self.meta['name8'].lower() self.meta['lastChange'] = datetime.date.today().isoformat() dead_keys = {} if 'deadkeys' in cfg:",
"+ j * 3]) for key in keys: baseKey = ' ' if",
"base_char = self.layers[i][name] if name != 'spce' and base_char != ODK_ID: odk['base'] +=",
"for d in dead_keys if d['char'] == dk['char'])) if not found: dead_keys.append(dk) #",
"APOSTROPHE } GEOMETRY = load_data('geometry.yaml') ### # Main # class KeyboardLayout: \"\"\" Lafayette-style",
"self.has_1dk = False # load the YAML data (and its ancessor, if any)",
"# ↓ ⇓ '\\u00b5': ' ', # µ (to avoid getting `Μ` as",
"# µ (to avoid getting `Μ` as uppercase) } if letter in customAlpha:",
"!= 1: # dead key? return ' ' customAlpha = { '\\u00df': '\\u1e9e',",
"self.layers[layerNumber + 1]: shiftKey = self.layers[layerNumber + 1][key] dead_base = len(baseKey) == 2",
"text_to_lines, lines_to_text, \\ DEFAULT_DEAD_KEYS, ODK_ID ### # Helpers # def upper_key(letter): if len(letter)",
"= cfg['deadkeys'] for dk in DEFAULT_DEAD_KEYS: found = any((d for d in dead_keys",
"full = text_to_lines(cfg['full']) self._parse_template(full, dead_keys, rows, 0) self._parse_template(full, dead_keys, rows, 4) self.has_altgr =",
"'\\u00b5': ' ', # µ (to avoid getting `Μ` as uppercase) } if",
"for line in text.split('\\n'): m = exp.match(line) if m: indent = m.group().split(prefix)[0] break",
"keymap (base+altgr layers) and dead keys # @property def json(self): return { 'name':",
"# 1dk behavior if ODK_ID in self.dead_keys: self.has_1dk = True odk = self.dead_keys[ODK_ID]",
"'\\u2264', # < ≤ '\\u003e': '\\u2265', # > ≥ '\\u2020': '\\u2021', # †",
"the object. \"\"\" # initialize a blank layout self.layers = [{}, {}, {},",
"= list(template[1 + j * 3]) for key in keys: baseKey = '",
"'\\u2020': '\\u2021', # † ‡ '\\u2190': '\\u21d0', # ← ⇐ '\\u2191': '\\u21d1', #",
"\"\"\" Lafayette-style keyboard layout: base + 1dk + altgr layers. \"\"\" def __init__(self,",
"shiftKey[0] == '*' if shiftPrevails: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*'",
"(standalone / user-space) \"\"\" out = load_tpl(self, '.xkb') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self,",
"'deadkeys']: self.meta[k] = cfg[k] filename = os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] = cfg['name'] if 'name' in",
"= '' for i in range(len(base)): if layer_has_char(base[i], 0) or layer_has_char(base[i], 1): used_base",
"shiftKey: base[i] = baseKey[-1] if dead_base: base[i-1] = '*' else: base[i] = baseKey[-1]",
"yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg) cfg = ext except Exception as e: print('File could not",
"layout to instanciate the object. \"\"\" # initialize a blank layout self.layers =",
"1dk + altgr layers. \"\"\" def __init__(self, filepath): \"\"\" Import a keyboard layout",
"= substitute_token(out, key, value) return out ### # Constants # CONFIG = {",
"= row['keys'] base = list(template[2 + j * 3]) shift = list(template[1 +",
"in self.dead_keys: base = self.dead_keys[dk_id]['base'] alt = self.dead_keys[dk_id]['alt'] used_base = '' used_alt =",
"shiftPrevails: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*' if upper_key(baseKey) != shiftKey:",
"or 1dk colOffset = 2 j = 0 for row in rows: i",
"rows = GEOMETRY[self.meta['geometry']]['rows'] if 'full' in cfg: full = text_to_lines(cfg['full']) self._parse_template(full, dead_keys, rows,",
"'\\u00a6', # | ¦ '\\u003c': '\\u2264', # < ≤ '\\u003e': '\\u2265', # >",
"- Do What The Fuck You Want Public License', 'geometry': 'ISO' } SPACEBAR",
"@property def full(self): return self._get_geometry([0, 4]) # base + altgr @property def altgr(self):",
"k in cfg: if k not in ['base', 'full', 'altgr', 'spacebar', 'deadkeys']: self.meta[k]",
"= shiftKey[-1] if dead_shift: shift[i-1] = '*' if upper_key(baseKey) != shiftKey: base[i] =",
"cfg['name8'] if 'name8' in cfg \\ else self.meta['name'][0:8] self.meta['fileName'] = self.meta['name8'].lower() self.meta['lastChange'] =",
"(name, alt_char) in self.layers[i + 2].items(): base_char = self.layers[i][name] if name != 'spce'",
"if d['char'] == dk['char'])) if not found: dead_keys.append(dk) # keyboard layers: self.layers &",
"template def _get_geometry(self, layers=[0], name='ISO'): \"\"\" `geometry` view of the requested layers. \"\"\"",
"driver (system patch) \"\"\" out = load_tpl(self, '.xkb_patch') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self,",
"exp.match(line) if m: indent = m.group().split(prefix)[0] break return exp.sub(lines_to_text(lines, indent), text) def substitute_token(text,",
"Do What The Fuck You Want Public License', 'geometry': 'ISO' } SPACEBAR =",
"def load_tpl(layout, ext): tpl = 'base' if layout.has_altgr: tpl = 'full' if layout.has_1dk",
"prevails baseKey = shiftKey.lower() if layerNumber != 0 and shiftKey == ' ':",
"base[i - 1] == '*' else '') + base[i] shiftKey = ('*' if",
"not be parsed.') print('Error: {}.'.format(e)) sys.exit(1) # metadata: self.meta for k in cfg:",
"if shiftKey != ' ': self.layers[layerNumber + 1][key] = shiftKey for dk in",
"shiftPrevails = True else: # AltGr or 1dk colOffset = 2 shiftPrevails =",
"' ', # µ (to avoid getting `Μ` as uppercase) } if letter",
"(base+altgr layers) and dead keys # @property def json(self): return { 'name': self.meta['name'],",
"rows, i) return template @property def base(self): return self._get_geometry([0, 2]) # base +",
"‡ '\\u2190': '\\u21d0', # ← ⇐ '\\u2191': '\\u21d1', # ↑ ⇑ '\\u2192': '\\u21d2',",
"6 template[2 + j * 3] = ''.join(base) template[1 + j * 3]",
"out = substitute_lines(out, 'GEOMETRY_base', layout.base) out = substitute_lines(out, 'GEOMETRY_full', layout.full) out = substitute_lines(out,",
"= any((d for d in dead_keys if d['char'] == dk['char'])) if not found:",
"'\\u21d2', # → ⇒ '\\u2193': '\\u21d3', # ↓ ⇓ '\\u00b5': ' ', #",
"('*' if base[i - 1] == '*' else '') + base[i] shiftKey =",
"def xkb(self): # will not work with Wayland \"\"\" GNU/Linux driver (standalone /",
"break return exp.sub(lines_to_text(lines, indent), text) def substitute_token(text, token, value): exp = re.compile('\\\\$\\\\{' +",
"layer_has_char(base[i], 0) or layer_has_char(base[i], 1): used_base += base[i] used_alt += alt[i] self.dead_keys[dk_id]['base'] =",
"dead keys # @property def json(self): return { 'name': self.meta['name'], 'description': self.meta['description'], 'geometry':",
"in dead_keys: if baseKey == dk['char']: self.dead_keys[baseKey] = dk.copy() if shiftKey == dk['char']:",
"layout.has_altgr: tpl = 'full' if layout.has_1dk and ext.startswith('.xkb'): tpl = 'full_1dk' out =",
"substitute_lines(out, 'TERMINATORS', osx_terminators(self)) return out @property def klc(self): \"\"\" Windows driver (warning: requires",
"for key in keys: baseKey = ' ' if key in self.layers[layerNumber]: baseKey",
"def __init__(self, filepath): \"\"\" Import a keyboard layout to instanciate the object. \"\"\"",
"only ### # OS-specific drivers: keylayout, klc, xkb, xkb_patch # @property def keylayout(self):",
"\"\"\" out = load_tpl(self, '.xkb') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, False)) return out",
"# ← ⇐ '\\u2191': '\\u21d1', # ↑ ⇑ '\\u2192': '\\u21d2', # → ⇒",
"KeyboardLayout: \"\"\" Lafayette-style keyboard layout: base + 1dk + altgr layers. \"\"\" def",
"= self._fill_template(template, rows, i) return template @property def base(self): return self._get_geometry([0, 2]) #",
"'altgr' in cfg: self.has_altgr = True self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows, 4) # space bar",
"{} # dictionary subset of DEAD_KEYS self.dk_index = [] # ordered keys of",
"'name8' in cfg \\ else self.meta['name'][0:8] self.meta['fileName'] = self.meta['name8'].lower() self.meta['lastChange'] = datetime.date.today().isoformat() dead_keys",
"U+0020 SPACE 'altgr_shift': \" \", # U+0020 SPACE '1dk': \"'\", # U+0027 APOSTROPHE",
"def _parse_template(self, template, dead_keys, rows, layerNumber): \"\"\" Extract a keyboard layer from a",
"remove unused characters in self.dead_keys[].{base,alt} def layer_has_char(char, layer_index): for id in self.layers[layer_index]: if",
"= ' ' self.layers[1]['spce'] = spc['shift'] self.layers[2]['spce'] = spc['1dk'] self.layers[3]['spce'] = spc['shift_1dk'] if",
"and 3rd layers to the dead key for i in [0, 1]: for",
"== 2 and shiftKey[0] == '*' if shiftPrevails: shift[i] = shiftKey[-1] if dead_shift:",
"\\ osx_keymap, osx_actions, osx_terminators, \\ klc_keymap, klc_deadkeys, klc_dk_index, \\ web_keymap, web_deadkeys from .utils",
"for key in keys: baseKey = ('*' if base[i - 1] == '*'",
"def base(self): return self._get_geometry([0, 2]) # base + 1dk @property def full(self): return",
"layout.meta.items(): out = substitute_token(out, key, value) return out ### # Constants # CONFIG",
"'\\u003c': '\\u2264', # < ≤ '\\u003e': '\\u2265', # > ≥ '\\u2020': '\\u2021', #",
"== char: return True return False for dk_id in self.dead_keys: base = self.dead_keys[dk_id]['base']",
"+ 1]: shiftKey = self.layers[layerNumber + 1][key] dead_base = len(baseKey) == 2 and",
"shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*' i += 6 template[2 +",
"token + '(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value, text) def load_tpl(layout, ext): tpl = 'base' if",
"0) or layer_has_char(base[i], 1): used_base += base[i] used_alt += alt[i] self.dead_keys[dk_id]['base'] = used_base",
"and dead keys # @property def json(self): return { 'name': self.meta['name'], 'description': self.meta['description'],",
"substitute_lines(out, 'GEOMETRY_full', layout.full) out = substitute_lines(out, 'GEOMETRY_altgr', layout.altgr) for key, value in layout.meta.items():",
"self.layers[1]['spce'] = spc['shift'] self.layers[2]['spce'] = spc['1dk'] self.layers[3]['spce'] = spc['shift_1dk'] if 'shift_1dk' in spc",
"line in text.split('\\n'): m = exp.match(line) if m: indent = m.group().split(prefix)[0] break return",
"Fill a template with a keyboard layer. \"\"\" if layerNumber == 0: #",
"'LAYER_' + str(i), layer) out = substitute_lines(out, 'ACTIONS', osx_actions(self)) out = substitute_lines(out, 'TERMINATORS',",
"'*' dead_shift = len(shiftKey) == 2 and shiftKey[0] == '*' if shiftPrevails: shift[i]",
"spc['1dk'] self.layers[3]['spce'] = spc['shift_1dk'] if 'shift_1dk' in spc \\ else spc['1dk'] if self.has_altgr:",
"[] # ordered keys of the above dictionary self.meta = CONFIG.copy() # default",
"1 return template def _get_geometry(self, layers=[0], name='ISO'): \"\"\" `geometry` view of the requested",
"layers: template = self._fill_template(template, rows, i) return template @property def base(self): return self._get_geometry([0,",
"ODK_ID in self.dead_keys: self.has_1dk = True odk = self.dead_keys[ODK_ID] # alt_self (double-press), alt_space",
"a template. \"\"\" if layerNumber == 0: # base layer colOffset = 0",
"keys of the above dictionary self.meta = CONFIG.copy() # default parameters, hardcoded self.has_altgr",
"'') + shift[i] if layerNumber == 0 and baseKey == ' ': #",
"exp = re.compile('\\\\$\\\\{' + token + '(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value, text) def load_tpl(layout, ext):",
"'' for line in text.split('\\n'): m = exp.match(line) if m: indent = m.group().split(prefix)[0]",
"_parse_template(self, template, dead_keys, rows, layerNumber): \"\"\" Extract a keyboard layer from a template.",
"@property def base(self): return self._get_geometry([0, 2]) # base + 1dk @property def full(self):",
"else filename self.meta['name8'] = cfg['name8'] if 'name8' in cfg \\ else self.meta['name'][0:8] self.meta['fileName']",
"self.dead_keys[dk_id]['alt'] = used_alt # 1dk behavior if ODK_ID in self.dead_keys: self.has_1dk = True",
"You Want Public License', 'geometry': 'ISO' } SPACEBAR = { 'shift': \" \",",
"\", # U+0020 SPACE '1dk': \"'\", # U+0027 APOSTROPHE '1dk_shift': \"'\" # U+0027",
"if 'extends' in cfg: path = os.path.join(os.path.dirname(filepath), cfg['extends']) ext = yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg)",
"base = list(template[2 + j * 3]) shift = list(template[1 + j *",
"key? return ' ' customAlpha = { '\\u00df': '\\u1e9e', # ß ẞ '\\u007c':",
"if dk['char'] in self.dead_keys: self.dk_index.append(dk['char']) # remove unused characters in self.dead_keys[].{base,alt} def layer_has_char(char,",
"if layerNumber == 0: # base layer colOffset = 0 else: # AltGr",
"dk['char'])) if not found: dead_keys.append(dk) # keyboard layers: self.layers & self.dead_keys rows =",
"i in layers: template = self._fill_template(template, rows, i) return template @property def base(self):",
"substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self)) out = substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self)) out = substitute_token(out, 'encoding', 'utf-16le')",
"def altgr(self): return self._get_geometry([4]) # altgr only ### # OS-specific drivers: keylayout, klc,",
"used_alt # 1dk behavior if ODK_ID in self.dead_keys: self.has_1dk = True odk =",
"letter.upper() else: return ' ' def substitute_lines(text, variable, lines): prefix = 'KALAMINE::' exp",
"output: keymap (base+altgr layers) and dead keys # @property def json(self): return {",
"base + 1dk + altgr layers. \"\"\" def __init__(self, filepath): \"\"\" Import a",
"dead_keys, rows, 2) if 'altgr' in cfg: self.has_altgr = True self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows,",
"keylayout, klc, xkb, xkb_patch # @property def keylayout(self): \"\"\" Mac OSX driver \"\"\"",
"keyboard layer. \"\"\" if layerNumber == 0: # base layer colOffset = 0",
"DEAD_KEYS self.dk_index = [] # ordered keys of the above dictionary self.meta =",
"Exception as e: print('File could not be parsed.') print('Error: {}.'.format(e)) sys.exit(1) # metadata:",
"of the above dictionary self.meta = CONFIG.copy() # default parameters, hardcoded self.has_altgr =",
"} SPACEBAR = { 'shift': \" \", # U+0020 SPACE 'altgr': \" \",",
"self.layers[5]['spce'] = spc['altgr_shift'] # active dead keys: self.dk_index for dk in dead_keys: if",
"baseKey = ' ' if key in self.layers[layerNumber]: baseKey = self.layers[layerNumber][key] shiftKey =",
"rows, 4) self.has_altgr = True else: base = text_to_lines(cfg['base']) self._parse_template(base, dead_keys, rows, 0)",
"layer in enumerate(osx_keymap(self)): out = substitute_lines(out, 'LAYER_' + str(i), layer) out = substitute_lines(out,",
"requires CR/LF + UTF16LE encoding) \"\"\" out = load_tpl(self, '.klc') out = substitute_lines(out,",
"in cfg \\ else self.meta['name'][0:8] self.meta['fileName'] = self.meta['name8'].lower() self.meta['lastChange'] = datetime.date.today().isoformat() dead_keys =",
"### # Main # class KeyboardLayout: \"\"\" Lafayette-style keyboard layout: base + 1dk",
"sys.exit(1) # metadata: self.meta for k in cfg: if k not in ['base',",
"Windows driver (warning: requires CR/LF + UTF16LE encoding) \"\"\" out = load_tpl(self, '.klc')",
"dk['char']: self.dead_keys[baseKey] = dk.copy() if shiftKey == dk['char']: self.dead_keys[shiftKey] = dk.copy() i +=",
"else: base[i] = baseKey[-1] if dead_base: base[i-1] = '*' if upper_key(baseKey) != shiftKey:",
"self.layers = [{}, {}, {}, {}, {}, {}] self.dead_keys = {} # dictionary",
"0 shiftPrevails = True else: # AltGr or 1dk colOffset = 2 shiftPrevails",
"import sys import yaml from .template import xkb_keymap, \\ osx_keymap, osx_actions, osx_terminators, \\",
"= len(shiftKey) == 2 and shiftKey[0] == '*' if shiftPrevails: shift[i] = shiftKey[-1]",
"layers. \"\"\" def __init__(self, filepath): \"\"\" Import a keyboard layout to instanciate the",
"a keyboard layer from a template. \"\"\" if layerNumber == 0: # base",
"= cfg[k] filename = os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] = cfg['name'] if 'name' in cfg else",
"layers=[0], name='ISO'): \"\"\" `geometry` view of the requested layers. \"\"\" rows = GEOMETRY[name]['rows']",
"row['keys'] base = list(template[2 + j * 3]) shift = list(template[1 + j",
"if not found: dead_keys.append(dk) # keyboard layers: self.layers & self.dead_keys rows = GEOMETRY[self.meta['geometry']]['rows']",
"xkb_keymap(self, False)) return out @property def xkb_patch(self): \"\"\" GNU/Linux driver (system patch) \"\"\"",
"= shiftKey[-1] if dead_shift: shift[i-1] = '*' i += 6 template[2 + j",
"dead_base: base[i-1] = '*' if upper_key(baseKey) != shiftKey: shift[i] = shiftKey[-1] if dead_shift:",
"web_keymap, web_deadkeys from .utils import open_local_file, load_data, text_to_lines, lines_to_text, \\ DEFAULT_DEAD_KEYS, ODK_ID ###",
"License', 'geometry': 'ISO' } SPACEBAR = { 'shift': \" \", # U+0020 SPACE",
"altgr only ### # OS-specific drivers: keylayout, klc, xkb, xkb_patch # @property def",
"+= alt_char def _parse_template(self, template, dead_keys, rows, layerNumber): \"\"\" Extract a keyboard layer",
"layout: base + 1dk + altgr layers. \"\"\" def __init__(self, filepath): \"\"\" Import",
"= self.meta['name8'].lower() self.meta['lastChange'] = datetime.date.today().isoformat() dead_keys = {} if 'deadkeys' in cfg: dead_keys",
"keylayout(self): \"\"\" Mac OSX driver \"\"\" out = load_tpl(self, '.keylayout') for i, layer",
"⇒ '\\u2193': '\\u21d3', # ↓ ⇓ '\\u00b5': ' ', # µ (to avoid",
"odk['base'] += base_char odk['alt'] += alt_char def _parse_template(self, template, dead_keys, rows, layerNumber): \"\"\"",
"for key, value in layout.meta.items(): out = substitute_token(out, key, value) return out ###",
"baseKey == ' ': # 'shift' prevails baseKey = shiftKey.lower() if layerNumber !=",
"2 shiftPrevails = False j = 0 for row in rows: i =",
"self.dead_keys[].{base,alt} def layer_has_char(char, layer_index): for id in self.layers[layer_index]: if self.layers[layer_index][id] == char: return",
"!= 0 and shiftKey == ' ': shiftKey = upper_key(baseKey) if baseKey !=",
"osx_terminators, \\ klc_keymap, klc_deadkeys, klc_dk_index, \\ web_keymap, web_deadkeys from .utils import open_local_file, load_data,",
"# base + 1dk @property def full(self): return self._get_geometry([0, 4]) # base +",
"out = substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self)) out = substitute_token(out, 'encoding', 'utf-16le') return out @property",
"== 0 and baseKey == ' ': # 'shift' prevails baseKey = shiftKey.lower()",
"unused characters in self.dead_keys[].{base,alt} def layer_has_char(char, layer_index): for id in self.layers[layer_index]: if self.layers[layer_index][id]",
"* 3]) for key in keys: baseKey = ('*' if base[i - 1]",
"above dictionary self.meta = CONFIG.copy() # default parameters, hardcoded self.has_altgr = False self.has_1dk",
"driver (standalone / user-space) \"\"\" out = load_tpl(self, '.xkb') out = substitute_lines(out, 'LAYOUT',",
".utils import open_local_file, load_data, text_to_lines, lines_to_text, \\ DEFAULT_DEAD_KEYS, ODK_ID ### # Helpers #",
"\"'\" # U+0027 APOSTROPHE } GEOMETRY = load_data('geometry.yaml') ### # Main # class",
"and baseKey == ' ': # 'shift' prevails baseKey = shiftKey.lower() if layerNumber",
"'deadkeys' in cfg: dead_keys = cfg['deadkeys'] for dk in DEFAULT_DEAD_KEYS: found = any((d",
"= False # load the YAML data (and its ancessor, if any) try:",
"key, value in layout.meta.items(): out = substitute_token(out, key, value) return out ### #",
"Geometry: base, full, altgr # def _fill_template(self, template, rows, layerNumber): \"\"\" Fill a",
"+ variable + '.*') indent = '' for line in text.split('\\n'): m =",
"'geometry': 'ISO' } SPACEBAR = { 'shift': \" \", # U+0020 SPACE 'altgr':",
"OSX driver \"\"\" out = load_tpl(self, '.keylayout') for i, layer in enumerate(osx_keymap(self)): out",
"python3 import datetime import os import re import sys import yaml from .template",
"cfg: dead_keys = cfg['deadkeys'] for dk in DEFAULT_DEAD_KEYS: found = any((d for d",
"uppercase) } if letter in customAlpha: return customAlpha[letter] elif letter.upper() != letter.lower(): return",
"spc[k] = cfg['spacebar'][k] self.layers[0]['spce'] = ' ' self.layers[1]['spce'] = spc['shift'] self.layers[2]['spce'] = spc['1dk']",
"if baseKey == dk['char']: self.dead_keys[baseKey] = dk.copy() if shiftKey == dk['char']: self.dead_keys[shiftKey] =",
"= baseKey if shiftKey != ' ': self.layers[layerNumber + 1][key] = shiftKey for",
"if k not in ['base', 'full', 'altgr', 'spacebar', 'deadkeys']: self.meta[k] = cfg[k] filename",
"# default parameters, hardcoded self.has_altgr = False self.has_1dk = False # load the",
"xkb_patch # @property def keylayout(self): \"\"\" Mac OSX driver \"\"\" out = load_tpl(self,",
"getting `Μ` as uppercase) } if letter in customAlpha: return customAlpha[letter] elif letter.upper()",
"'\\u2192': '\\u21d2', # → ⇒ '\\u2193': '\\u21d3', # ↓ ⇓ '\\u00b5': ' ',",
"or 1dk colOffset = 2 shiftPrevails = False j = 0 for row",
"' if key in self.layers[layerNumber]: baseKey = self.layers[layerNumber][key] shiftKey = ' ' if",
"= baseKey[-1] if dead_base: base[i-1] = '*' else: base[i] = baseKey[-1] if dead_base:",
"template = self._fill_template(template, rows, i) return template @property def base(self): return self._get_geometry([0, 2])",
"text) def substitute_token(text, token, value): exp = re.compile('\\\\$\\\\{' + token + '(=[^\\\\}]*){0,1}\\\\}') return",
"_fill_template(self, template, rows, layerNumber): \"\"\" Fill a template with a keyboard layer. \"\"\"",
"(to avoid getting `Μ` as uppercase) } if letter in customAlpha: return customAlpha[letter]",
"_get_geometry(self, layers=[0], name='ISO'): \"\"\" `geometry` view of the requested layers. \"\"\" rows =",
"{}, {}, {}, {}, {}] self.dead_keys = {} # dictionary subset of DEAD_KEYS",
"= { 'shift': \" \", # U+0020 SPACE 'altgr': \" \", # U+0020",
"2 j = 0 for row in rows: i = row['offset'] + colOffset",
"0 and shiftKey == ' ': shiftKey = upper_key(baseKey) if baseKey != '",
"import yaml from .template import xkb_keymap, \\ osx_keymap, osx_actions, osx_terminators, \\ klc_keymap, klc_deadkeys,",
"cfg else filename self.meta['name8'] = cfg['name8'] if 'name8' in cfg \\ else self.meta['name'][0:8]",
"(and its ancessor, if any) try: cfg = yaml.load(open(filepath), Loader=yaml.SafeLoader) if 'extends' in",
"layer_has_char(char, layer_index): for id in self.layers[layer_index]: if self.layers[layer_index][id] == char: return True return",
"ordered keys of the above dictionary self.meta = CONFIG.copy() # default parameters, hardcoded",
"j * 3]) for key in keys: baseKey = ' ' if key",
"try: cfg = yaml.load(open(filepath), Loader=yaml.SafeLoader) if 'extends' in cfg: path = os.path.join(os.path.dirname(filepath), cfg['extends'])",
"datetime.date.today().isoformat() dead_keys = {} if 'deadkeys' in cfg: dead_keys = cfg['deadkeys'] for dk",
"cfg = ext except Exception as e: print('File could not be parsed.') print('Error:",
"DEFAULT_DEAD_KEYS, ODK_ID ### # Helpers # def upper_key(letter): if len(letter) != 1: #",
"import re import sys import yaml from .template import xkb_keymap, \\ osx_keymap, osx_actions,",
"\"\"\" Import a keyboard layout to instanciate the object. \"\"\" # initialize a",
"Fuck You Want Public License', 'geometry': 'ISO' } SPACEBAR = { 'shift': \"",
"'altgr', 'spacebar', 'deadkeys']: self.meta[k] = cfg[k] filename = os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] = cfg['name'] if",
"elif letter.upper() != letter.lower(): return letter.upper() else: return ' ' def substitute_lines(text, variable,",
"used_alt = '' for i in range(len(base)): if layer_has_char(base[i], 0) or layer_has_char(base[i], 1):",
"ẞ '\\u007c': '\\u00a6', # | ¦ '\\u003c': '\\u2264', # < ≤ '\\u003e': '\\u2265',",
"[0, 1]: for (name, alt_char) in self.layers[i + 2].items(): base_char = self.layers[i][name] if",
"# base + altgr @property def altgr(self): return self._get_geometry([4]) # altgr only ###",
"'*' else: base[i] = baseKey[-1] if dead_base: base[i-1] = '*' if upper_key(baseKey) !=",
"= '*' if upper_key(baseKey) != shiftKey: base[i] = baseKey[-1] if dead_base: base[i-1] =",
"* 3] = ''.join(shift) j += 1 return template def _get_geometry(self, layers=[0], name='ISO'):",
"out = substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self)) out = substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self)) out = substitute_token(out,",
"text_to_lines(cfg['base']) self._parse_template(base, dead_keys, rows, 0) self._parse_template(base, dead_keys, rows, 2) if 'altgr' in cfg:",
"layers: self.layers & self.dead_keys rows = GEOMETRY[self.meta['geometry']]['rows'] if 'full' in cfg: full =",
"4) self.has_altgr = True else: base = text_to_lines(cfg['base']) self._parse_template(base, dead_keys, rows, 0) self._parse_template(base,",
"j * 3]) shift = list(template[1 + j * 3]) for key in",
"re import sys import yaml from .template import xkb_keymap, \\ osx_keymap, osx_actions, osx_terminators,",
"in cfg: self.has_altgr = True self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows, 4) # space bar spc",
"i = row['offset'] + colOffset keys = row['keys'] base = list(template[2 + j",
"user-space) \"\"\" out = load_tpl(self, '.xkb') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, False)) return",
"#!/usr/bin/env python3 import datetime import os import re import sys import yaml from",
"layerNumber): \"\"\" Fill a template with a keyboard layer. \"\"\" if layerNumber ==",
"found: dead_keys.append(dk) # keyboard layers: self.layers & self.dead_keys rows = GEOMETRY[self.meta['geometry']]['rows'] if 'full'",
"'full_1dk' out = open_local_file(os.path.join('tpl', tpl + ext)).read() out = substitute_lines(out, 'GEOMETRY_base', layout.base) out",
"if layerNumber == 0: # base layer colOffset = 0 shiftPrevails = True",
"'ACTIONS', osx_actions(self)) out = substitute_lines(out, 'TERMINATORS', osx_terminators(self)) return out @property def klc(self): \"\"\"",
"= load_tpl(self, '.klc') out = substitute_lines(out, 'LAYOUT', klc_keymap(self)) out = substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self))",
"= load_tpl(self, '.xkb') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, False)) return out @property def",
"layer colOffset = 0 shiftPrevails = True else: # AltGr or 1dk colOffset",
"template[2 + j * 3] = ''.join(base) template[1 + j * 3] =",
"return out ### # Constants # CONFIG = { 'author': '<NAME>', 'license': 'WTFPL",
"and shiftKey == ' ': shiftKey = upper_key(baseKey) if baseKey != ' ':",
"# CONFIG = { 'author': '<NAME>', 'license': 'WTFPL - Do What The Fuck",
"variable, lines): prefix = 'KALAMINE::' exp = re.compile('.*' + prefix + variable +",
"in keys: baseKey = ('*' if base[i - 1] == '*' else '')",
"if 'full' in cfg: full = text_to_lines(cfg['full']) self._parse_template(full, dead_keys, rows, 0) self._parse_template(full, dead_keys,",
"i) return template @property def base(self): return self._get_geometry([0, 2]) # base + 1dk",
"else '') + shift[i] if layerNumber == 0 and baseKey == ' ':",
"True odk = self.dead_keys[ODK_ID] # alt_self (double-press), alt_space (1dk+space) odk['alt_space'] = spc['1dk'] for",
"return template def _get_geometry(self, layers=[0], name='ISO'): \"\"\" `geometry` view of the requested layers.",
"for i, layer in enumerate(osx_keymap(self)): out = substitute_lines(out, 'LAYER_' + str(i), layer) out",
"in cfg: if k not in ['base', 'full', 'altgr', 'spacebar', 'deadkeys']: self.meta[k] =",
"if base[i - 1] == '*' else '') + base[i] shiftKey = ('*'",
"cfg: self.has_altgr = True self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows, 4) # space bar spc =",
"\"\"\" Fill a template with a keyboard layer. \"\"\" if layerNumber == 0:",
"out = substitute_lines(out, 'LAYER_' + str(i), layer) out = substitute_lines(out, 'ACTIONS', osx_actions(self)) out",
"as uppercase) } if letter in customAlpha: return customAlpha[letter] elif letter.upper() != letter.lower():",
"' self.layers[1]['spce'] = spc['shift'] self.layers[2]['spce'] = spc['1dk'] self.layers[3]['spce'] = spc['shift_1dk'] if 'shift_1dk' in",
"= list(template[1 + j * 3]) for key in keys: baseKey = ('*'",
"# AltGr or 1dk colOffset = 2 j = 0 for row in",
"load_tpl(self, '.xkb_patch') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, True)) return out ### # JSON",
"be parsed.') print('Error: {}.'.format(e)) sys.exit(1) # metadata: self.meta for k in cfg: if",
"odk['alt'] += alt_char def _parse_template(self, template, dead_keys, rows, layerNumber): \"\"\" Extract a keyboard",
"base[i-1] = '*' if upper_key(baseKey) != shiftKey: shift[i] = shiftKey[-1] if dead_shift: shift[i-1]",
"{ 'author': '<NAME>', 'license': 'WTFPL - Do What The Fuck You Want Public",
"# U+0027 APOSTROPHE } GEOMETRY = load_data('geometry.yaml') ### # Main # class KeyboardLayout:",
"if shiftKey == dk['char']: self.dead_keys[shiftKey] = dk.copy() i += 6 j += 1",
"layer from a template. \"\"\" if layerNumber == 0: # base layer colOffset",
"in cfg: path = os.path.join(os.path.dirname(filepath), cfg['extends']) ext = yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg) cfg =",
"'.keylayout') for i, layer in enumerate(osx_keymap(self)): out = substitute_lines(out, 'LAYER_' + str(i), layer)",
"in cfg: full = text_to_lines(cfg['full']) self._parse_template(full, dead_keys, rows, 0) self._parse_template(full, dead_keys, rows, 4)",
"exp = re.compile('.*' + prefix + variable + '.*') indent = '' for",
"tpl = 'base' if layout.has_altgr: tpl = 'full' if layout.has_1dk and ext.startswith('.xkb'): tpl",
"Want Public License', 'geometry': 'ISO' } SPACEBAR = { 'shift': \" \", #",
"k in cfg['spacebar']: spc[k] = cfg['spacebar'][k] self.layers[0]['spce'] = ' ' self.layers[1]['spce'] = spc['shift']",
"default parameters, hardcoded self.has_altgr = False self.has_1dk = False # load the YAML",
"1][key] = shiftKey for dk in dead_keys: if baseKey == dk['char']: self.dead_keys[baseKey] =",
"if dead_base: base[i-1] = '*' else: base[i] = baseKey[-1] if dead_base: base[i-1] =",
"substitute_lines(out, 'LAYER_' + str(i), layer) out = substitute_lines(out, 'ACTIONS', osx_actions(self)) out = substitute_lines(out,",
"== ' ': # 'shift' prevails baseKey = shiftKey.lower() if layerNumber != 0",
"rows, layerNumber): \"\"\" Extract a keyboard layer from a template. \"\"\" if layerNumber",
"dead_keys, rows, 0) self._parse_template(base, dead_keys, rows, 2) if 'altgr' in cfg: self.has_altgr =",
"j = 0 for row in rows: i = row['offset'] + colOffset keys",
"= substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self)) out = substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self)) out = substitute_token(out, 'encoding',",
"= '*' i += 6 template[2 + j * 3] = ''.join(base) template[1",
"in cfg: for k in cfg['spacebar']: spc[k] = cfg['spacebar'][k] self.layers[0]['spce'] = ' '",
"view of the requested layers. \"\"\" rows = GEOMETRY[name]['rows'] template = GEOMETRY[name]['template'].split('\\n')[:-1] for",
"# copy the 2nd and 3rd layers to the dead key for i",
"j * 3] = ''.join(base) template[1 + j * 3] = ''.join(shift) j",
"SPACE 'altgr_shift': \" \", # U+0020 SPACE '1dk': \"'\", # U+0027 APOSTROPHE '1dk_shift':",
"+= base[i] used_alt += alt[i] self.dead_keys[dk_id]['base'] = used_base self.dead_keys[dk_id]['alt'] = used_alt # 1dk",
"+ ext)).read() out = substitute_lines(out, 'GEOMETRY_base', layout.base) out = substitute_lines(out, 'GEOMETRY_full', layout.full) out",
"= '*' else: base[i] = baseKey[-1] if dead_base: base[i-1] = '*' if upper_key(baseKey)",
"Lafayette-style keyboard layout: base + 1dk + altgr layers. \"\"\" def __init__(self, filepath):",
"d in dead_keys if d['char'] == dk['char'])) if not found: dead_keys.append(dk) # keyboard",
"GEOMETRY[self.meta['geometry']]['rows'] if 'full' in cfg: full = text_to_lines(cfg['full']) self._parse_template(full, dead_keys, rows, 0) self._parse_template(full,",
"char: return True return False for dk_id in self.dead_keys: base = self.dead_keys[dk_id]['base'] alt",
"\\ DEFAULT_DEAD_KEYS, ODK_ID ### # Helpers # def upper_key(letter): if len(letter) != 1:",
"m: indent = m.group().split(prefix)[0] break return exp.sub(lines_to_text(lines, indent), text) def substitute_token(text, token, value):",
"= substitute_lines(out, 'LAYOUT', xkb_keymap(self, True)) return out ### # JSON output: keymap (base+altgr",
"in cfg['spacebar']: spc[k] = cfg['spacebar'][k] self.layers[0]['spce'] = ' ' self.layers[1]['spce'] = spc['shift'] self.layers[2]['spce']",
"in layout.meta.items(): out = substitute_token(out, key, value) return out ### # Constants #",
"# altgr only ### # OS-specific drivers: keylayout, klc, xkb, xkb_patch # @property",
"'utf-16le') return out @property def xkb(self): # will not work with Wayland \"\"\"",
"key in keys: baseKey = ' ' if key in self.layers[layerNumber]: baseKey =",
"keyboard layers: self.layers & self.dead_keys rows = GEOMETRY[self.meta['geometry']]['rows'] if 'full' in cfg: full",
"template. \"\"\" if layerNumber == 0: # base layer colOffset = 0 else:",
"self.meta = CONFIG.copy() # default parameters, hardcoded self.has_altgr = False self.has_1dk = False",
"or layer_has_char(base[i], 1): used_base += base[i] used_alt += alt[i] self.dead_keys[dk_id]['base'] = used_base self.dead_keys[dk_id]['alt']",
"def layer_has_char(char, layer_index): for id in self.layers[layer_index]: if self.layers[layer_index][id] == char: return True",
"layer. \"\"\" if layerNumber == 0: # base layer colOffset = 0 shiftPrevails",
"keys # @property def json(self): return { 'name': self.meta['name'], 'description': self.meta['description'], 'geometry': self.meta['geometry'].lower(),",
"substitute_lines(text, variable, lines): prefix = 'KALAMINE::' exp = re.compile('.*' + prefix + variable",
"value) return out ### # Constants # CONFIG = { 'author': '<NAME>', 'license':",
"self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows, 4) # space bar spc = SPACEBAR.copy() if 'spacebar' in",
"base = text_to_lines(cfg['base']) self._parse_template(base, dead_keys, rows, 0) self._parse_template(base, dead_keys, rows, 2) if 'altgr'",
"+ altgr layers. \"\"\" def __init__(self, filepath): \"\"\" Import a keyboard layout to",
"if shiftPrevails: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*' if upper_key(baseKey) !=",
"≥ '\\u2020': '\\u2021', # † ‡ '\\u2190': '\\u21d0', # ← ⇐ '\\u2191': '\\u21d1',",
"= upper_key(baseKey) if baseKey != ' ': self.layers[layerNumber + 0][key] = baseKey if",
"sys import yaml from .template import xkb_keymap, \\ osx_keymap, osx_actions, osx_terminators, \\ klc_keymap,",
"odk['alt_space'] = spc['1dk'] for key in self.layers[0]: if self.layers[0][key] == ODK_ID: odk['alt_self'] =",
"key in keys: baseKey = ('*' if base[i - 1] == '*' else",
"cfg: full = text_to_lines(cfg['full']) self._parse_template(full, dead_keys, rows, 0) self._parse_template(full, dead_keys, rows, 4) self.has_altgr",
"self.dk_index.append(dk['char']) # remove unused characters in self.dead_keys[].{base,alt} def layer_has_char(char, layer_index): for id in",
"shiftKey = self.layers[layerNumber + 1][key] dead_base = len(baseKey) == 2 and baseKey[0] ==",
"in text.split('\\n'): m = exp.match(line) if m: indent = m.group().split(prefix)[0] break return exp.sub(lines_to_text(lines,",
"== dk['char']: self.dead_keys[baseKey] = dk.copy() if shiftKey == dk['char']: self.dead_keys[shiftKey] = dk.copy() i",
"### # OS-specific drivers: keylayout, klc, xkb, xkb_patch # @property def keylayout(self): \"\"\"",
"{}.'.format(e)) sys.exit(1) # metadata: self.meta for k in cfg: if k not in",
"xkb_keymap, \\ osx_keymap, osx_actions, osx_terminators, \\ klc_keymap, klc_deadkeys, klc_dk_index, \\ web_keymap, web_deadkeys from",
"in layers: template = self._fill_template(template, rows, i) return template @property def base(self): return",
"return out @property def klc(self): \"\"\" Windows driver (warning: requires CR/LF + UTF16LE",
"exp.sub(lines_to_text(lines, indent), text) def substitute_token(text, token, value): exp = re.compile('\\\\$\\\\{' + token +",
"= 'KALAMINE::' exp = re.compile('.*' + prefix + variable + '.*') indent =",
"os.path.join(os.path.dirname(filepath), cfg['extends']) ext = yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg) cfg = ext except Exception as",
"out = substitute_token(out, 'encoding', 'utf-16le') return out @property def xkb(self): # will not",
"'\\u2265', # > ≥ '\\u2020': '\\u2021', # † ‡ '\\u2190': '\\u21d0', # ←",
"+= 1 return template def _get_geometry(self, layers=[0], name='ISO'): \"\"\" `geometry` view of the",
"# < ≤ '\\u003e': '\\u2265', # > ≥ '\\u2020': '\\u2021', # † ‡",
"j += 1 return template def _get_geometry(self, layers=[0], name='ISO'): \"\"\" `geometry` view of",
"@property def keylayout(self): \"\"\" Mac OSX driver \"\"\" out = load_tpl(self, '.keylayout') for",
"'WTFPL - Do What The Fuck You Want Public License', 'geometry': 'ISO' }",
"= substitute_lines(out, 'LAYOUT', xkb_keymap(self, False)) return out @property def xkb_patch(self): \"\"\" GNU/Linux driver",
"3]) shift = list(template[1 + j * 3]) for key in keys: baseKey",
"1dk behavior if ODK_ID in self.dead_keys: self.has_1dk = True odk = self.dead_keys[ODK_ID] #",
"self.layers[layerNumber + 0][key] = baseKey if shiftKey != ' ': self.layers[layerNumber + 1][key]",
"== dk['char'])) if not found: dead_keys.append(dk) # keyboard layers: self.layers & self.dead_keys rows",
"shiftKey = upper_key(baseKey) if baseKey != ' ': self.layers[layerNumber + 0][key] = baseKey",
"shift = list(template[1 + j * 3]) for key in keys: baseKey =",
"self.dead_keys: self.has_1dk = True odk = self.dead_keys[ODK_ID] # alt_self (double-press), alt_space (1dk+space) odk['alt_space']",
"shift[i] if layerNumber == 0 and baseKey == ' ': # 'shift' prevails",
"customAlpha = { '\\u00df': '\\u1e9e', # ß ẞ '\\u007c': '\\u00a6', # | ¦",
"+ colOffset keys = row['keys'] base = list(template[2 + j * 3]) shift",
"= cfg['spacebar'][k] self.layers[0]['spce'] = ' ' self.layers[1]['spce'] = spc['shift'] self.layers[2]['spce'] = spc['1dk'] self.layers[3]['spce']",
"⇓ '\\u00b5': ' ', # µ (to avoid getting `Μ` as uppercase) }",
"shiftKey: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*' i += 6 template[2",
"= CONFIG.copy() # default parameters, hardcoded self.has_altgr = False self.has_1dk = False #",
"3] = ''.join(base) template[1 + j * 3] = ''.join(shift) j += 1",
"`Μ` as uppercase) } if letter in customAlpha: return customAlpha[letter] elif letter.upper() !=",
"(1dk+space) odk['alt_space'] = spc['1dk'] for key in self.layers[0]: if self.layers[0][key] == ODK_ID: odk['alt_self']",
"else spc['1dk'] if self.has_altgr: self.layers[4]['spce'] = spc['altgr'] self.layers[5]['spce'] = spc['altgr_shift'] # active dead",
"\"\"\" out = load_tpl(self, '.klc') out = substitute_lines(out, 'LAYOUT', klc_keymap(self)) out = substitute_lines(out,",
"= { 'author': '<NAME>', 'license': 'WTFPL - Do What The Fuck You Want",
"used_base += base[i] used_alt += alt[i] self.dead_keys[dk_id]['base'] = used_base self.dead_keys[dk_id]['alt'] = used_alt #",
"= spc['1dk'] for key in self.layers[0]: if self.layers[0][key] == ODK_ID: odk['alt_self'] = self.layers[2][key]",
"1 ### # Geometry: base, full, altgr # def _fill_template(self, template, rows, layerNumber):",
"\"\"\" out = load_tpl(self, '.xkb_patch') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, True)) return out",
"' ' if key in self.layers[layerNumber + 1]: shiftKey = self.layers[layerNumber + 1][key]",
"# ordered keys of the above dictionary self.meta = CONFIG.copy() # default parameters,",
"⇐ '\\u2191': '\\u21d1', # ↑ ⇑ '\\u2192': '\\u21d2', # → ⇒ '\\u2193': '\\u21d3',",
"the above dictionary self.meta = CONFIG.copy() # default parameters, hardcoded self.has_altgr = False",
"# class KeyboardLayout: \"\"\" Lafayette-style keyboard layout: base + 1dk + altgr layers.",
"= False j = 0 for row in rows: i = row['offset'] +",
"1]: for (name, alt_char) in self.layers[i + 2].items(): base_char = self.layers[i][name] if name",
"instanciate the object. \"\"\" # initialize a blank layout self.layers = [{}, {},",
"base + 1dk @property def full(self): return self._get_geometry([0, 4]) # base + altgr",
"Main # class KeyboardLayout: \"\"\" Lafayette-style keyboard layout: base + 1dk + altgr",
"yaml from .template import xkb_keymap, \\ osx_keymap, osx_actions, osx_terminators, \\ klc_keymap, klc_deadkeys, klc_dk_index,",
"= load_tpl(self, '.xkb_patch') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, True)) return out ### #",
"'GEOMETRY_base', layout.base) out = substitute_lines(out, 'GEOMETRY_full', layout.full) out = substitute_lines(out, 'GEOMETRY_altgr', layout.altgr) for",
"spc['shift_1dk'] if 'shift_1dk' in spc \\ else spc['1dk'] if self.has_altgr: self.layers[4]['spce'] = spc['altgr']",
"if letter in customAlpha: return customAlpha[letter] elif letter.upper() != letter.lower(): return letter.upper() else:",
"YAML data (and its ancessor, if any) try: cfg = yaml.load(open(filepath), Loader=yaml.SafeLoader) if",
"cfg['spacebar'][k] self.layers[0]['spce'] = ' ' self.layers[1]['spce'] = spc['shift'] self.layers[2]['spce'] = spc['1dk'] self.layers[3]['spce'] =",
"for dk_id in self.dead_keys: base = self.dead_keys[dk_id]['base'] alt = self.dead_keys[dk_id]['alt'] used_base = ''",
"= substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self)) out = substitute_token(out, 'encoding', 'utf-16le') return out @property def",
"parameters, hardcoded self.has_altgr = False self.has_1dk = False # load the YAML data",
"False self.has_1dk = False # load the YAML data (and its ancessor, if",
"spc = SPACEBAR.copy() if 'spacebar' in cfg: for k in cfg['spacebar']: spc[k] =",
"import open_local_file, load_data, text_to_lines, lines_to_text, \\ DEFAULT_DEAD_KEYS, ODK_ID ### # Helpers # def",
"# space bar spc = SPACEBAR.copy() if 'spacebar' in cfg: for k in",
"return out @property def xkb_patch(self): \"\"\" GNU/Linux driver (system patch) \"\"\" out =",
"= substitute_lines(out, 'GEOMETRY_full', layout.full) out = substitute_lines(out, 'GEOMETRY_altgr', layout.altgr) for key, value in",
"(double-press), alt_space (1dk+space) odk['alt_space'] = spc['1dk'] for key in self.layers[0]: if self.layers[0][key] ==",
"in self.layers[layerNumber + 1]: shiftKey = self.layers[layerNumber + 1][key] dead_base = len(baseKey) ==",
"self.layers[0]: if self.layers[0][key] == ODK_ID: odk['alt_self'] = self.layers[2][key] break # copy the 2nd",
"< ≤ '\\u003e': '\\u2265', # > ≥ '\\u2020': '\\u2021', # † ‡ '\\u2190':",
"indent), text) def substitute_token(text, token, value): exp = re.compile('\\\\$\\\\{' + token + '(=[^\\\\}]*){0,1}\\\\}')",
"== dk['char']: self.dead_keys[shiftKey] = dk.copy() i += 6 j += 1 ### #",
"= { '\\u00df': '\\u1e9e', # ß ẞ '\\u007c': '\\u00a6', # | ¦ '\\u003c':",
"'\\u2190': '\\u21d0', # ← ⇐ '\\u2191': '\\u21d1', # ↑ ⇑ '\\u2192': '\\u21d2', #",
"= spc['shift'] self.layers[2]['spce'] = spc['1dk'] self.layers[3]['spce'] = spc['shift_1dk'] if 'shift_1dk' in spc \\",
"\"\"\" if layerNumber == 0: # base layer colOffset = 0 else: #",
"= text_to_lines(cfg['base']) self._parse_template(base, dead_keys, rows, 0) self._parse_template(base, dead_keys, rows, 2) if 'altgr' in",
"== ' ': shiftKey = upper_key(baseKey) if baseKey != ' ': self.layers[layerNumber +",
"xkb, xkb_patch # @property def keylayout(self): \"\"\" Mac OSX driver \"\"\" out =",
"characters in self.dead_keys[].{base,alt} def layer_has_char(char, layer_index): for id in self.layers[layer_index]: if self.layers[layer_index][id] ==",
"return out ### # JSON output: keymap (base+altgr layers) and dead keys #",
"len(shiftKey) == 2 and shiftKey[0] == '*' if shiftPrevails: shift[i] = shiftKey[-1] if",
"'shift' prevails baseKey = shiftKey.lower() if layerNumber != 0 and shiftKey == '",
"= '' for line in text.split('\\n'): m = exp.match(line) if m: indent =",
"': self.layers[layerNumber + 1][key] = shiftKey for dk in dead_keys: if baseKey ==",
"1: # dead key? return ' ' customAlpha = { '\\u00df': '\\u1e9e', #",
"substitute_lines(out, 'LAYOUT', xkb_keymap(self, True)) return out ### # JSON output: keymap (base+altgr layers)",
"ext): tpl = 'base' if layout.has_altgr: tpl = 'full' if layout.has_1dk and ext.startswith('.xkb'):",
"\"'\", # U+0027 APOSTROPHE '1dk_shift': \"'\" # U+0027 APOSTROPHE } GEOMETRY = load_data('geometry.yaml')",
"list(template[2 + j * 3]) shift = list(template[1 + j * 3]) for",
"to instanciate the object. \"\"\" # initialize a blank layout self.layers = [{},",
"and baseKey[0] == '*' dead_shift = len(shiftKey) == 2 and shiftKey[0] == '*'",
"for dk in DEFAULT_DEAD_KEYS: found = any((d for d in dead_keys if d['char']",
"!= shiftKey: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*' i += 6",
"= self.layers[i][name] if name != 'spce' and base_char != ODK_ID: odk['base'] += base_char",
"'\\u2191': '\\u21d1', # ↑ ⇑ '\\u2192': '\\u21d2', # → ⇒ '\\u2193': '\\u21d3', #",
"= substitute_token(out, 'encoding', 'utf-16le') return out @property def xkb(self): # will not work",
"baseKey[-1] if dead_base: base[i-1] = '*' if upper_key(baseKey) != shiftKey: shift[i] = shiftKey[-1]",
"= 'full_1dk' out = open_local_file(os.path.join('tpl', tpl + ext)).read() out = substitute_lines(out, 'GEOMETRY_base', layout.base)",
"# ↑ ⇑ '\\u2192': '\\u21d2', # → ⇒ '\\u2193': '\\u21d3', # ↓ ⇓",
"open_local_file, load_data, text_to_lines, lines_to_text, \\ DEFAULT_DEAD_KEYS, ODK_ID ### # Helpers # def upper_key(letter):",
"out = load_tpl(self, '.keylayout') for i, layer in enumerate(osx_keymap(self)): out = substitute_lines(out, 'LAYER_'",
"if dead_base: base[i-1] = '*' if upper_key(baseKey) != shiftKey: shift[i] = shiftKey[-1] if",
"self._parse_template(base, dead_keys, rows, 0) self._parse_template(base, dead_keys, rows, 2) if 'altgr' in cfg: self.has_altgr",
"= exp.match(line) if m: indent = m.group().split(prefix)[0] break return exp.sub(lines_to_text(lines, indent), text) def",
"self.dead_keys = {} # dictionary subset of DEAD_KEYS self.dk_index = [] # ordered",
"', # µ (to avoid getting `Μ` as uppercase) } if letter in",
"{}] self.dead_keys = {} # dictionary subset of DEAD_KEYS self.dk_index = [] #",
"== 0: # base layer colOffset = 0 shiftPrevails = True else: #",
"1): used_base += base[i] used_alt += alt[i] self.dead_keys[dk_id]['base'] = used_base self.dead_keys[dk_id]['alt'] = used_alt",
"'\\u1e9e', # ß ẞ '\\u007c': '\\u00a6', # | ¦ '\\u003c': '\\u2264', # <",
"# Constants # CONFIG = { 'author': '<NAME>', 'license': 'WTFPL - Do What",
"j += 1 ### # Geometry: base, full, altgr # def _fill_template(self, template,",
"exp.sub(value, text) def load_tpl(layout, ext): tpl = 'base' if layout.has_altgr: tpl = 'full'",
"### # Geometry: base, full, altgr # def _fill_template(self, template, rows, layerNumber): \"\"\"",
"klc, xkb, xkb_patch # @property def keylayout(self): \"\"\" Mac OSX driver \"\"\" out",
"if any) try: cfg = yaml.load(open(filepath), Loader=yaml.SafeLoader) if 'extends' in cfg: path =",
"2 and shiftKey[0] == '*' if shiftPrevails: shift[i] = shiftKey[-1] if dead_shift: shift[i-1]",
"# U+0020 SPACE 'altgr_shift': \" \", # U+0020 SPACE '1dk': \"'\", # U+0027",
"'shift_1dk' in spc \\ else spc['1dk'] if self.has_altgr: self.layers[4]['spce'] = spc['altgr'] self.layers[5]['spce'] =",
"if self.layers[0][key] == ODK_ID: odk['alt_self'] = self.layers[2][key] break # copy the 2nd and",
"GEOMETRY[name]['template'].split('\\n')[:-1] for i in layers: template = self._fill_template(template, rows, i) return template @property",
"prefix + variable + '.*') indent = '' for line in text.split('\\n'): m",
"2) if 'altgr' in cfg: self.has_altgr = True self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows, 4) #",
"'DEAD_KEY_INDEX', klc_dk_index(self)) out = substitute_token(out, 'encoding', 'utf-16le') return out @property def xkb(self): #",
"substitute_token(out, 'encoding', 'utf-16le') return out @property def xkb(self): # will not work with",
"base[i] = baseKey[-1] if dead_base: base[i-1] = '*' else: base[i] = baseKey[-1] if",
"True self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows, 4) # space bar spc = SPACEBAR.copy() if 'spacebar'",
"if upper_key(baseKey) != shiftKey: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*' i",
"load_data('geometry.yaml') ### # Main # class KeyboardLayout: \"\"\" Lafayette-style keyboard layout: base +",
"# initialize a blank layout self.layers = [{}, {}, {}, {}, {}, {}]",
"= GEOMETRY[name]['rows'] template = GEOMETRY[name]['template'].split('\\n')[:-1] for i in layers: template = self._fill_template(template, rows,",
"layerNumber == 0 and baseKey == ' ': # 'shift' prevails baseKey =",
"'(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value, text) def load_tpl(layout, ext): tpl = 'base' if layout.has_altgr: tpl",
"out ### # Constants # CONFIG = { 'author': '<NAME>', 'license': 'WTFPL -",
"str(i), layer) out = substitute_lines(out, 'ACTIONS', osx_actions(self)) out = substitute_lines(out, 'TERMINATORS', osx_terminators(self)) return",
"Public License', 'geometry': 'ISO' } SPACEBAR = { 'shift': \" \", # U+0020",
"SPACE '1dk': \"'\", # U+0027 APOSTROPHE '1dk_shift': \"'\" # U+0027 APOSTROPHE } GEOMETRY",
"0 and baseKey == ' ': # 'shift' prevails baseKey = shiftKey.lower() if",
"layout.full) out = substitute_lines(out, 'GEOMETRY_altgr', layout.altgr) for key, value in layout.meta.items(): out =",
"in dead_keys if d['char'] == dk['char'])) if not found: dead_keys.append(dk) # keyboard layers:",
"# | ¦ '\\u003c': '\\u2264', # < ≤ '\\u003e': '\\u2265', # > ≥",
"else: base = text_to_lines(cfg['base']) self._parse_template(base, dead_keys, rows, 0) self._parse_template(base, dead_keys, rows, 2) if",
"len(baseKey) == 2 and baseKey[0] == '*' dead_shift = len(shiftKey) == 2 and",
"\\ klc_keymap, klc_deadkeys, klc_dk_index, \\ web_keymap, web_deadkeys from .utils import open_local_file, load_data, text_to_lines,",
"return ' ' customAlpha = { '\\u00df': '\\u1e9e', # ß ẞ '\\u007c': '\\u00a6',",
"'*' else '') + shift[i] if layerNumber == 0 and baseKey == '",
"odk = self.dead_keys[ODK_ID] # alt_self (double-press), alt_space (1dk+space) odk['alt_space'] = spc['1dk'] for key",
"self.layers[0]['spce'] = ' ' self.layers[1]['spce'] = spc['shift'] self.layers[2]['spce'] = spc['1dk'] self.layers[3]['spce'] = spc['shift_1dk']",
"= m.group().split(prefix)[0] break return exp.sub(lines_to_text(lines, indent), text) def substitute_token(text, token, value): exp =",
"driver \"\"\" out = load_tpl(self, '.keylayout') for i, layer in enumerate(osx_keymap(self)): out =",
"' def substitute_lines(text, variable, lines): prefix = 'KALAMINE::' exp = re.compile('.*' + prefix",
"shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*' if upper_key(baseKey) != shiftKey: base[i]",
"dead_keys, rows, 4) self.has_altgr = True else: base = text_to_lines(cfg['base']) self._parse_template(base, dead_keys, rows,",
"if layout.has_altgr: tpl = 'full' if layout.has_1dk and ext.startswith('.xkb'): tpl = 'full_1dk' out",
"self.layers[layerNumber][key] shiftKey = ' ' if key in self.layers[layerNumber + 1]: shiftKey =",
"alt_char def _parse_template(self, template, dead_keys, rows, layerNumber): \"\"\" Extract a keyboard layer from",
"': shiftKey = upper_key(baseKey) if baseKey != ' ': self.layers[layerNumber + 0][key] =",
"if m: indent = m.group().split(prefix)[0] break return exp.sub(lines_to_text(lines, indent), text) def substitute_token(text, token,",
"= self.layers[layerNumber + 1][key] dead_base = len(baseKey) == 2 and baseKey[0] == '*'",
"in self.layers[layerNumber]: baseKey = self.layers[layerNumber][key] shiftKey = ' ' if key in self.layers[layerNumber",
"= 'full' if layout.has_1dk and ext.startswith('.xkb'): tpl = 'full_1dk' out = open_local_file(os.path.join('tpl', tpl",
"{}, {}, {}] self.dead_keys = {} # dictionary subset of DEAD_KEYS self.dk_index =",
"' ': # 'shift' prevails baseKey = shiftKey.lower() if layerNumber != 0 and",
"dk in dead_keys: if baseKey == dk['char']: self.dead_keys[baseKey] = dk.copy() if shiftKey ==",
"'shift': \" \", # U+0020 SPACE 'altgr': \" \", # U+0020 SPACE 'altgr_shift':",
"colOffset = 2 shiftPrevails = False j = 0 for row in rows:",
"'.xkb_patch') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, True)) return out ### # JSON output:",
"# > ≥ '\\u2020': '\\u2021', # † ‡ '\\u2190': '\\u21d0', # ← ⇐",
"space bar spc = SPACEBAR.copy() if 'spacebar' in cfg: for k in cfg['spacebar']:",
"keys = row['keys'] base = list(template[2 + j * 3]) shift = list(template[1",
"!= letter.lower(): return letter.upper() else: return ' ' def substitute_lines(text, variable, lines): prefix",
"['base', 'full', 'altgr', 'spacebar', 'deadkeys']: self.meta[k] = cfg[k] filename = os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] =",
"if 'spacebar' in cfg: for k in cfg['spacebar']: spc[k] = cfg['spacebar'][k] self.layers[0]['spce'] =",
"+ UTF16LE encoding) \"\"\" out = load_tpl(self, '.klc') out = substitute_lines(out, 'LAYOUT', klc_keymap(self))",
"= self.dead_keys[ODK_ID] # alt_self (double-press), alt_space (1dk+space) odk['alt_space'] = spc['1dk'] for key in",
"# OS-specific drivers: keylayout, klc, xkb, xkb_patch # @property def keylayout(self): \"\"\" Mac",
"baseKey[-1] if dead_base: base[i-1] = '*' else: base[i] = baseKey[-1] if dead_base: base[i-1]",
"\"\"\" rows = GEOMETRY[name]['rows'] template = GEOMETRY[name]['template'].split('\\n')[:-1] for i in layers: template =",
"'' for i in range(len(base)): if layer_has_char(base[i], 0) or layer_has_char(base[i], 1): used_base +=",
"out @property def xkb_patch(self): \"\"\" GNU/Linux driver (system patch) \"\"\" out = load_tpl(self,",
"SPACEBAR.copy() if 'spacebar' in cfg: for k in cfg['spacebar']: spc[k] = cfg['spacebar'][k] self.layers[0]['spce']",
"SPACE 'altgr': \" \", # U+0020 SPACE 'altgr_shift': \" \", # U+0020 SPACE",
"shift[i-1] = '*' if upper_key(baseKey) != shiftKey: base[i] = baseKey[-1] if dead_base: base[i-1]",
"xkb_patch(self): \"\"\" GNU/Linux driver (system patch) \"\"\" out = load_tpl(self, '.xkb_patch') out =",
"from a template. \"\"\" if layerNumber == 0: # base layer colOffset =",
"self._parse_template(full, dead_keys, rows, 4) self.has_altgr = True else: base = text_to_lines(cfg['base']) self._parse_template(base, dead_keys,",
"'full' if layout.has_1dk and ext.startswith('.xkb'): tpl = 'full_1dk' out = open_local_file(os.path.join('tpl', tpl +",
"datetime import os import re import sys import yaml from .template import xkb_keymap,",
"True else: # AltGr or 1dk colOffset = 2 shiftPrevails = False j",
"⇑ '\\u2192': '\\u21d2', # → ⇒ '\\u2193': '\\u21d3', # ↓ ⇓ '\\u00b5': '",
"'LAYOUT', xkb_keymap(self, True)) return out ### # JSON output: keymap (base+altgr layers) and",
"# ß ẞ '\\u007c': '\\u00a6', # | ¦ '\\u003c': '\\u2264', # < ≤",
"= 2 j = 0 for row in rows: i = row['offset'] +",
"2nd and 3rd layers to the dead key for i in [0, 1]:",
"baseKey = ('*' if base[i - 1] == '*' else '') + base[i]",
"spc \\ else spc['1dk'] if self.has_altgr: self.layers[4]['spce'] = spc['altgr'] self.layers[5]['spce'] = spc['altgr_shift'] #",
"alt_self (double-press), alt_space (1dk+space) odk['alt_space'] = spc['1dk'] for key in self.layers[0]: if self.layers[0][key]",
"rows = GEOMETRY[name]['rows'] template = GEOMETRY[name]['template'].split('\\n')[:-1] for i in layers: template = self._fill_template(template,",
"'spce' and base_char != ODK_ID: odk['base'] += base_char odk['alt'] += alt_char def _parse_template(self,",
"not work with Wayland \"\"\" GNU/Linux driver (standalone / user-space) \"\"\" out =",
"altgr(self): return self._get_geometry([4]) # altgr only ### # OS-specific drivers: keylayout, klc, xkb,",
"letter.upper() != letter.lower(): return letter.upper() else: return ' ' def substitute_lines(text, variable, lines):",
"self.layers[2][key] break # copy the 2nd and 3rd layers to the dead key",
"!= ODK_ID: odk['base'] += base_char odk['alt'] += alt_char def _parse_template(self, template, dead_keys, rows,",
"re.compile('\\\\$\\\\{' + token + '(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value, text) def load_tpl(layout, ext): tpl =",
"hardcoded self.has_altgr = False self.has_1dk = False # load the YAML data (and",
"shiftKey[-1] if dead_shift: shift[i-1] = '*' if upper_key(baseKey) != shiftKey: base[i] = baseKey[-1]",
"in ['base', 'full', 'altgr', 'spacebar', 'deadkeys']: self.meta[k] = cfg[k] filename = os.path.splitext(os.path.basename(filepath))[0] self.meta['name']",
"if upper_key(baseKey) != shiftKey: base[i] = baseKey[-1] if dead_base: base[i-1] = '*' else:",
"= 'base' if layout.has_altgr: tpl = 'full' if layout.has_1dk and ext.startswith('.xkb'): tpl =",
"= ext except Exception as e: print('File could not be parsed.') print('Error: {}.'.format(e))",
"layout.altgr) for key, value in layout.meta.items(): out = substitute_token(out, key, value) return out",
"spc['1dk'] if self.has_altgr: self.layers[4]['spce'] = spc['altgr'] self.layers[5]['spce'] = spc['altgr_shift'] # active dead keys:",
"if dead_shift: shift[i-1] = '*' if upper_key(baseKey) != shiftKey: base[i] = baseKey[-1] if",
"# dictionary subset of DEAD_KEYS self.dk_index = [] # ordered keys of the",
"in keys: baseKey = ' ' if key in self.layers[layerNumber]: baseKey = self.layers[layerNumber][key]",
"copy the 2nd and 3rd layers to the dead key for i in",
"shiftPrevails = False j = 0 for row in rows: i = row['offset']",
"in customAlpha: return customAlpha[letter] elif letter.upper() != letter.lower(): return letter.upper() else: return '",
"OS-specific drivers: keylayout, klc, xkb, xkb_patch # @property def keylayout(self): \"\"\" Mac OSX",
"used_base = '' used_alt = '' for i in range(len(base)): if layer_has_char(base[i], 0)",
"work with Wayland \"\"\" GNU/Linux driver (standalone / user-space) \"\"\" out = load_tpl(self,",
"key in self.layers[0]: if self.layers[0][key] == ODK_ID: odk['alt_self'] = self.layers[2][key] break # copy",
"with a keyboard layer. \"\"\" if layerNumber == 0: # base layer colOffset",
"{} if 'deadkeys' in cfg: dead_keys = cfg['deadkeys'] for dk in DEFAULT_DEAD_KEYS: found",
"0][key] = baseKey if shiftKey != ' ': self.layers[layerNumber + 1][key] = shiftKey",
"baseKey = self.layers[layerNumber][key] shiftKey = ' ' if key in self.layers[layerNumber + 1]:",
"dk in dead_keys: if dk['char'] in self.dead_keys: self.dk_index.append(dk['char']) # remove unused characters in",
"'1dk_shift': \"'\" # U+0027 APOSTROPHE } GEOMETRY = load_data('geometry.yaml') ### # Main #",
"@property def xkb(self): # will not work with Wayland \"\"\" GNU/Linux driver (standalone",
"== ODK_ID: odk['alt_self'] = self.layers[2][key] break # copy the 2nd and 3rd layers",
"template with a keyboard layer. \"\"\" if layerNumber == 0: # base layer",
"alt_space (1dk+space) odk['alt_space'] = spc['1dk'] for key in self.layers[0]: if self.layers[0][key] == ODK_ID:",
"* 3] = ''.join(base) template[1 + j * 3] = ''.join(shift) j +=",
"' ': shiftKey = upper_key(baseKey) if baseKey != ' ': self.layers[layerNumber + 0][key]",
"= used_base self.dead_keys[dk_id]['alt'] = used_alt # 1dk behavior if ODK_ID in self.dead_keys: self.has_1dk",
"return ' ' def substitute_lines(text, variable, lines): prefix = 'KALAMINE::' exp = re.compile('.*'",
"if key in self.layers[layerNumber]: baseKey = self.layers[layerNumber][key] shiftKey = ' ' if key",
"will not work with Wayland \"\"\" GNU/Linux driver (standalone / user-space) \"\"\" out",
"in self.dead_keys: self.dk_index.append(dk['char']) # remove unused characters in self.dead_keys[].{base,alt} def layer_has_char(char, layer_index): for",
"load_tpl(self, '.klc') out = substitute_lines(out, 'LAYOUT', klc_keymap(self)) out = substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self)) out",
"any) try: cfg = yaml.load(open(filepath), Loader=yaml.SafeLoader) if 'extends' in cfg: path = os.path.join(os.path.dirname(filepath),",
"for dk in dead_keys: if dk['char'] in self.dead_keys: self.dk_index.append(dk['char']) # remove unused characters",
"cfg[k] filename = os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] = cfg['name'] if 'name' in cfg else filename",
"+ 1dk + altgr layers. \"\"\" def __init__(self, filepath): \"\"\" Import a keyboard",
"initialize a blank layout self.layers = [{}, {}, {}, {}, {}, {}] self.dead_keys",
"\\ else spc['1dk'] if self.has_altgr: self.layers[4]['spce'] = spc['altgr'] self.layers[5]['spce'] = spc['altgr_shift'] # active",
"True return False for dk_id in self.dead_keys: base = self.dead_keys[dk_id]['base'] alt = self.dead_keys[dk_id]['alt']",
"shift[i - 1] == '*' else '') + shift[i] if layerNumber == 0",
"self.meta['name8'] = cfg['name8'] if 'name8' in cfg \\ else self.meta['name'][0:8] self.meta['fileName'] = self.meta['name8'].lower()",
"U+0027 APOSTROPHE '1dk_shift': \"'\" # U+0027 APOSTROPHE } GEOMETRY = load_data('geometry.yaml') ### #",
"out = substitute_token(out, key, value) return out ### # Constants # CONFIG =",
"in enumerate(osx_keymap(self)): out = substitute_lines(out, 'LAYER_' + str(i), layer) out = substitute_lines(out, 'ACTIONS',",
"\"\"\" GNU/Linux driver (system patch) \"\"\" out = load_tpl(self, '.xkb_patch') out = substitute_lines(out,",
"= datetime.date.today().isoformat() dead_keys = {} if 'deadkeys' in cfg: dead_keys = cfg['deadkeys'] for",
"template, rows, layerNumber): \"\"\" Fill a template with a keyboard layer. \"\"\" if",
"'license': 'WTFPL - Do What The Fuck You Want Public License', 'geometry': 'ISO'",
"klc_dk_index, \\ web_keymap, web_deadkeys from .utils import open_local_file, load_data, text_to_lines, lines_to_text, \\ DEFAULT_DEAD_KEYS,",
"alt_char) in self.layers[i + 2].items(): base_char = self.layers[i][name] if name != 'spce' and",
"in DEFAULT_DEAD_KEYS: found = any((d for d in dead_keys if d['char'] == dk['char']))",
"dk.copy() if shiftKey == dk['char']: self.dead_keys[shiftKey] = dk.copy() i += 6 j +=",
"out = open_local_file(os.path.join('tpl', tpl + ext)).read() out = substitute_lines(out, 'GEOMETRY_base', layout.base) out =",
"self.has_altgr: self.layers[4]['spce'] = spc['altgr'] self.layers[5]['spce'] = spc['altgr_shift'] # active dead keys: self.dk_index for",
"of DEAD_KEYS self.dk_index = [] # ordered keys of the above dictionary self.meta",
"customAlpha: return customAlpha[letter] elif letter.upper() != letter.lower(): return letter.upper() else: return ' '",
"= re.compile('.*' + prefix + variable + '.*') indent = '' for line",
"= shiftKey for dk in dead_keys: if baseKey == dk['char']: self.dead_keys[baseKey] = dk.copy()",
"\"\"\" out = load_tpl(self, '.keylayout') for i, layer in enumerate(osx_keymap(self)): out = substitute_lines(out,",
"self.layers[0][key] == ODK_ID: odk['alt_self'] = self.layers[2][key] break # copy the 2nd and 3rd",
"baseKey if shiftKey != ' ': self.layers[layerNumber + 1][key] = shiftKey for dk",
"= substitute_lines(out, 'ACTIONS', osx_actions(self)) out = substitute_lines(out, 'TERMINATORS', osx_terminators(self)) return out @property def",
"indent = '' for line in text.split('\\n'): m = exp.match(line) if m: indent",
"== '*' else '') + shift[i] if layerNumber == 0 and baseKey ==",
"'*' if upper_key(baseKey) != shiftKey: base[i] = baseKey[-1] if dead_base: base[i-1] = '*'",
".template import xkb_keymap, \\ osx_keymap, osx_actions, osx_terminators, \\ klc_keymap, klc_deadkeys, klc_dk_index, \\ web_keymap,",
"shiftKey = ('*' if shift[i - 1] == '*' else '') + shift[i]",
"def xkb_patch(self): \"\"\" GNU/Linux driver (system patch) \"\"\" out = load_tpl(self, '.xkb_patch') out",
"1] == '*' else '') + base[i] shiftKey = ('*' if shift[i -",
"# alt_self (double-press), alt_space (1dk+space) odk['alt_space'] = spc['1dk'] for key in self.layers[0]: if",
"load_tpl(layout, ext): tpl = 'base' if layout.has_altgr: tpl = 'full' if layout.has_1dk and",
"text.split('\\n'): m = exp.match(line) if m: indent = m.group().split(prefix)[0] break return exp.sub(lines_to_text(lines, indent),",
"' ' self.layers[1]['spce'] = spc['shift'] self.layers[2]['spce'] = spc['1dk'] self.layers[3]['spce'] = spc['shift_1dk'] if 'shift_1dk'",
"shiftKey for dk in dead_keys: if baseKey == dk['char']: self.dead_keys[baseKey] = dk.copy() if",
"# JSON output: keymap (base+altgr layers) and dead keys # @property def json(self):",
"= self.dead_keys[dk_id]['alt'] used_base = '' used_alt = '' for i in range(len(base)): if",
"← ⇐ '\\u2191': '\\u21d1', # ↑ ⇑ '\\u2192': '\\u21d2', # → ⇒ '\\u2193':",
"baseKey == dk['char']: self.dead_keys[baseKey] = dk.copy() if shiftKey == dk['char']: self.dead_keys[shiftKey] = dk.copy()",
"JSON output: keymap (base+altgr layers) and dead keys # @property def json(self): return",
"self.layers[3]['spce'] = spc['shift_1dk'] if 'shift_1dk' in spc \\ else spc['1dk'] if self.has_altgr: self.layers[4]['spce']",
"CR/LF + UTF16LE encoding) \"\"\" out = load_tpl(self, '.klc') out = substitute_lines(out, 'LAYOUT',",
"= dk.copy() i += 6 j += 1 ### # Geometry: base, full,",
"/ user-space) \"\"\" out = load_tpl(self, '.xkb') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, False))",
"0) self._parse_template(full, dead_keys, rows, 4) self.has_altgr = True else: base = text_to_lines(cfg['base']) self._parse_template(base,",
"\" \", # U+0020 SPACE 'altgr_shift': \" \", # U+0020 SPACE '1dk': \"'\",",
"template = GEOMETRY[name]['template'].split('\\n')[:-1] for i in layers: template = self._fill_template(template, rows, i) return",
"spc['altgr_shift'] # active dead keys: self.dk_index for dk in dead_keys: if dk['char'] in",
"the requested layers. \"\"\" rows = GEOMETRY[name]['rows'] template = GEOMETRY[name]['template'].split('\\n')[:-1] for i in",
"load_tpl(self, '.xkb') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, False)) return out @property def xkb_patch(self):",
"= dk.copy() if shiftKey == dk['char']: self.dead_keys[shiftKey] = dk.copy() i += 6 j",
"re.compile('.*' + prefix + variable + '.*') indent = '' for line in",
"osx_actions(self)) out = substitute_lines(out, 'TERMINATORS', osx_terminators(self)) return out @property def klc(self): \"\"\" Windows",
"'author': '<NAME>', 'license': 'WTFPL - Do What The Fuck You Want Public License',",
"### # Helpers # def upper_key(letter): if len(letter) != 1: # dead key?",
"The Fuck You Want Public License', 'geometry': 'ISO' } SPACEBAR = { 'shift':",
"if layerNumber == 0 and baseKey == ' ': # 'shift' prevails baseKey",
"'\\u007c': '\\u00a6', # | ¦ '\\u003c': '\\u2264', # < ≤ '\\u003e': '\\u2265', #",
"U+0020 SPACE '1dk': \"'\", # U+0027 APOSTROPHE '1dk_shift': \"'\" # U+0027 APOSTROPHE }",
"self.dead_keys[baseKey] = dk.copy() if shiftKey == dk['char']: self.dead_keys[shiftKey] = dk.copy() i += 6",
"# metadata: self.meta for k in cfg: if k not in ['base', 'full',",
"'KALAMINE::' exp = re.compile('.*' + prefix + variable + '.*') indent = ''",
"d['char'] == dk['char'])) if not found: dead_keys.append(dk) # keyboard layers: self.layers & self.dead_keys",
"out = load_tpl(self, '.klc') out = substitute_lines(out, 'LAYOUT', klc_keymap(self)) out = substitute_lines(out, 'DEAD_KEYS',",
"shiftKey != ' ': self.layers[layerNumber + 1][key] = shiftKey for dk in dead_keys:",
"for row in rows: i = row['offset'] + colOffset keys = row['keys'] base",
"= load_data('geometry.yaml') ### # Main # class KeyboardLayout: \"\"\" Lafayette-style keyboard layout: base",
"if self.layers[layer_index][id] == char: return True return False for dk_id in self.dead_keys: base",
"'full' in cfg: full = text_to_lines(cfg['full']) self._parse_template(full, dead_keys, rows, 0) self._parse_template(full, dead_keys, rows,",
"': self.layers[layerNumber + 0][key] = baseKey if shiftKey != ' ': self.layers[layerNumber +",
"self.dead_keys[dk_id]['base'] alt = self.dead_keys[dk_id]['alt'] used_base = '' used_alt = '' for i in",
"= spc['shift_1dk'] if 'shift_1dk' in spc \\ else spc['1dk'] if self.has_altgr: self.layers[4]['spce'] =",
"Import a keyboard layout to instanciate the object. \"\"\" # initialize a blank",
"substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self)) out = substitute_token(out, 'encoding', 'utf-16le') return out @property def xkb(self):",
"# will not work with Wayland \"\"\" GNU/Linux driver (standalone / user-space) \"\"\"",
"path = os.path.join(os.path.dirname(filepath), cfg['extends']) ext = yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg) cfg = ext except",
"0 else: # AltGr or 1dk colOffset = 2 j = 0 for",
"= used_alt # 1dk behavior if ODK_ID in self.dead_keys: self.has_1dk = True odk",
"base[i] used_alt += alt[i] self.dead_keys[dk_id]['base'] = used_base self.dead_keys[dk_id]['alt'] = used_alt # 1dk behavior",
"= ('*' if shift[i - 1] == '*' else '') + shift[i] if",
"' ' def substitute_lines(text, variable, lines): prefix = 'KALAMINE::' exp = re.compile('.*' +",
"'\\u2021', # † ‡ '\\u2190': '\\u21d0', # ← ⇐ '\\u2191': '\\u21d1', # ↑",
"if shift[i - 1] == '*' else '') + shift[i] if layerNumber ==",
"GNU/Linux driver (system patch) \"\"\" out = load_tpl(self, '.xkb_patch') out = substitute_lines(out, 'LAYOUT',",
"+ '(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value, text) def load_tpl(layout, ext): tpl = 'base' if layout.has_altgr:",
"False for dk_id in self.dead_keys: base = self.dead_keys[dk_id]['base'] alt = self.dead_keys[dk_id]['alt'] used_base =",
"'' used_alt = '' for i in range(len(base)): if layer_has_char(base[i], 0) or layer_has_char(base[i],",
"__init__(self, filepath): \"\"\" Import a keyboard layout to instanciate the object. \"\"\" #",
"tpl + ext)).read() out = substitute_lines(out, 'GEOMETRY_base', layout.base) out = substitute_lines(out, 'GEOMETRY_full', layout.full)",
"print('File could not be parsed.') print('Error: {}.'.format(e)) sys.exit(1) # metadata: self.meta for k",
"base[i] shiftKey = ('*' if shift[i - 1] == '*' else '') +",
"in range(len(base)): if layer_has_char(base[i], 0) or layer_has_char(base[i], 1): used_base += base[i] used_alt +=",
"3]) for key in keys: baseKey = ('*' if base[i - 1] ==",
"layer) out = substitute_lines(out, 'ACTIONS', osx_actions(self)) out = substitute_lines(out, 'TERMINATORS', osx_terminators(self)) return out",
"def upper_key(letter): if len(letter) != 1: # dead key? return ' ' customAlpha",
"out = substitute_lines(out, 'GEOMETRY_full', layout.full) out = substitute_lines(out, 'GEOMETRY_altgr', layout.altgr) for key, value",
"len(letter) != 1: # dead key? return ' ' customAlpha = { '\\u00df':",
"= SPACEBAR.copy() if 'spacebar' in cfg: for k in cfg['spacebar']: spc[k] = cfg['spacebar'][k]",
"value): exp = re.compile('\\\\$\\\\{' + token + '(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value, text) def load_tpl(layout,",
"self.dead_keys[dk_id]['base'] = used_base self.dead_keys[dk_id]['alt'] = used_alt # 1dk behavior if ODK_ID in self.dead_keys:",
"\"\"\" if layerNumber == 0: # base layer colOffset = 0 shiftPrevails =",
"1][key] dead_base = len(baseKey) == 2 and baseKey[0] == '*' dead_shift = len(shiftKey)",
"layer_index): for id in self.layers[layer_index]: if self.layers[layer_index][id] == char: return True return False",
"# def _fill_template(self, template, rows, layerNumber): \"\"\" Fill a template with a keyboard",
"= shiftKey.lower() if layerNumber != 0 and shiftKey == ' ': shiftKey =",
"in [0, 1]: for (name, alt_char) in self.layers[i + 2].items(): base_char = self.layers[i][name]",
"e: print('File could not be parsed.') print('Error: {}.'.format(e)) sys.exit(1) # metadata: self.meta for",
"1dk colOffset = 2 shiftPrevails = False j = 0 for row in",
"self.layers[layer_index][id] == char: return True return False for dk_id in self.dead_keys: base =",
"patch) \"\"\" out = load_tpl(self, '.xkb_patch') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, True)) return",
"self.dead_keys rows = GEOMETRY[self.meta['geometry']]['rows'] if 'full' in cfg: full = text_to_lines(cfg['full']) self._parse_template(full, dead_keys,",
"+ j * 3]) shift = list(template[1 + j * 3]) for key",
"def _get_geometry(self, layers=[0], name='ISO'): \"\"\" `geometry` view of the requested layers. \"\"\" rows",
"klc_deadkeys, klc_dk_index, \\ web_keymap, web_deadkeys from .utils import open_local_file, load_data, text_to_lines, lines_to_text, \\",
"'base' if layout.has_altgr: tpl = 'full' if layout.has_1dk and ext.startswith('.xkb'): tpl = 'full_1dk'",
"# load the YAML data (and its ancessor, if any) try: cfg =",
"* 3]) shift = list(template[1 + j * 3]) for key in keys:",
"in self.dead_keys[].{base,alt} def layer_has_char(char, layer_index): for id in self.layers[layer_index]: if self.layers[layer_index][id] == char:",
"# Helpers # def upper_key(letter): if len(letter) != 1: # dead key? return",
"alt = self.dead_keys[dk_id]['alt'] used_base = '' used_alt = '' for i in range(len(base)):",
"ext except Exception as e: print('File could not be parsed.') print('Error: {}.'.format(e)) sys.exit(1)",
"for i in [0, 1]: for (name, alt_char) in self.layers[i + 2].items(): base_char",
"base, full, altgr # def _fill_template(self, template, rows, layerNumber): \"\"\" Fill a template",
"if baseKey != ' ': self.layers[layerNumber + 0][key] = baseKey if shiftKey !=",
"(system patch) \"\"\" out = load_tpl(self, '.xkb_patch') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, True))",
"'LAYOUT', xkb_keymap(self, False)) return out @property def xkb_patch(self): \"\"\" GNU/Linux driver (system patch)",
"load the YAML data (and its ancessor, if any) try: cfg = yaml.load(open(filepath),",
"= cfg['name8'] if 'name8' in cfg \\ else self.meta['name'][0:8] self.meta['fileName'] = self.meta['name8'].lower() self.meta['lastChange']",
"layerNumber): \"\"\" Extract a keyboard layer from a template. \"\"\" if layerNumber ==",
"j * 3]) for key in keys: baseKey = ('*' if base[i -",
"= True odk = self.dead_keys[ODK_ID] # alt_self (double-press), alt_space (1dk+space) odk['alt_space'] = spc['1dk']",
"layerNumber == 0: # base layer colOffset = 0 else: # AltGr or",
"1dk @property def full(self): return self._get_geometry([0, 4]) # base + altgr @property def",
"else: return ' ' def substitute_lines(text, variable, lines): prefix = 'KALAMINE::' exp =",
"self.meta['lastChange'] = datetime.date.today().isoformat() dead_keys = {} if 'deadkeys' in cfg: dead_keys = cfg['deadkeys']",
"for id in self.layers[layer_index]: if self.layers[layer_index][id] == char: return True return False for",
"xkb(self): # will not work with Wayland \"\"\" GNU/Linux driver (standalone / user-space)",
"spc['altgr'] self.layers[5]['spce'] = spc['altgr_shift'] # active dead keys: self.dk_index for dk in dead_keys:",
"behavior if ODK_ID in self.dead_keys: self.has_1dk = True odk = self.dead_keys[ODK_ID] # alt_self",
"the dead key for i in [0, 1]: for (name, alt_char) in self.layers[i",
"= re.compile('\\\\$\\\\{' + token + '(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value, text) def load_tpl(layout, ext): tpl",
"# U+0027 APOSTROPHE '1dk_shift': \"'\" # U+0027 APOSTROPHE } GEOMETRY = load_data('geometry.yaml') ###",
"object. \"\"\" # initialize a blank layout self.layers = [{}, {}, {}, {},",
"# U+0020 SPACE '1dk': \"'\", # U+0027 APOSTROPHE '1dk_shift': \"'\" # U+0027 APOSTROPHE",
"'TERMINATORS', osx_terminators(self)) return out @property def klc(self): \"\"\" Windows driver (warning: requires CR/LF",
"keys: baseKey = ('*' if base[i - 1] == '*' else '') +",
"('*' if shift[i - 1] == '*' else '') + shift[i] if layerNumber",
"layout.base) out = substitute_lines(out, 'GEOMETRY_full', layout.full) out = substitute_lines(out, 'GEOMETRY_altgr', layout.altgr) for key,",
"alt[i] self.dead_keys[dk_id]['base'] = used_base self.dead_keys[dk_id]['alt'] = used_alt # 1dk behavior if ODK_ID in",
"cfg['spacebar']: spc[k] = cfg['spacebar'][k] self.layers[0]['spce'] = ' ' self.layers[1]['spce'] = spc['shift'] self.layers[2]['spce'] =",
"colOffset = 0 shiftPrevails = True else: # AltGr or 1dk colOffset =",
"# base layer colOffset = 0 else: # AltGr or 1dk colOffset =",
"dead_keys: if baseKey == dk['char']: self.dead_keys[baseKey] = dk.copy() if shiftKey == dk['char']: self.dead_keys[shiftKey]",
"klc_keymap(self)) out = substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self)) out = substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self)) out =",
"# keyboard layers: self.layers & self.dead_keys rows = GEOMETRY[self.meta['geometry']]['rows'] if 'full' in cfg:",
"AltGr or 1dk colOffset = 2 shiftPrevails = False j = 0 for",
"self.has_altgr = True self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows, 4) # space bar spc = SPACEBAR.copy()",
"= {} if 'deadkeys' in cfg: dead_keys = cfg['deadkeys'] for dk in DEFAULT_DEAD_KEYS:",
"''.join(base) template[1 + j * 3] = ''.join(shift) j += 1 return template",
"\" \", # U+0020 SPACE '1dk': \"'\", # U+0027 APOSTROPHE '1dk_shift': \"'\" #",
"3] = ''.join(shift) j += 1 return template def _get_geometry(self, layers=[0], name='ISO'): \"\"\"",
"UTF16LE encoding) \"\"\" out = load_tpl(self, '.klc') out = substitute_lines(out, 'LAYOUT', klc_keymap(self)) out",
"'altgr_shift': \" \", # U+0020 SPACE '1dk': \"'\", # U+0027 APOSTROPHE '1dk_shift': \"'\"",
"\"\"\" Extract a keyboard layer from a template. \"\"\" if layerNumber == 0:",
"dk in DEFAULT_DEAD_KEYS: found = any((d for d in dead_keys if d['char'] ==",
"self.layers[2]['spce'] = spc['1dk'] self.layers[3]['spce'] = spc['shift_1dk'] if 'shift_1dk' in spc \\ else spc['1dk']",
"+ base[i] shiftKey = ('*' if shift[i - 1] == '*' else '')",
"' ': self.layers[layerNumber + 0][key] = baseKey if shiftKey != ' ': self.layers[layerNumber",
"return letter.upper() else: return ' ' def substitute_lines(text, variable, lines): prefix = 'KALAMINE::'",
"dead_keys = cfg['deadkeys'] for dk in DEFAULT_DEAD_KEYS: found = any((d for d in",
"¦ '\\u003c': '\\u2264', # < ≤ '\\u003e': '\\u2265', # > ≥ '\\u2020': '\\u2021',",
"dead_keys: if dk['char'] in self.dead_keys: self.dk_index.append(dk['char']) # remove unused characters in self.dead_keys[].{base,alt} def",
"+= 1 ### # Geometry: base, full, altgr # def _fill_template(self, template, rows,",
"} GEOMETRY = load_data('geometry.yaml') ### # Main # class KeyboardLayout: \"\"\" Lafayette-style keyboard",
"import os import re import sys import yaml from .template import xkb_keymap, \\",
"filename = os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] = cfg['name'] if 'name' in cfg else filename self.meta['name8']",
"self._parse_template(full, dead_keys, rows, 0) self._parse_template(full, dead_keys, rows, 4) self.has_altgr = True else: base",
"xkb_keymap(self, True)) return out ### # JSON output: keymap (base+altgr layers) and dead",
"rows, 2) if 'altgr' in cfg: self.has_altgr = True self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows, 4)",
"out ### # JSON output: keymap (base+altgr layers) and dead keys # @property",
"a template with a keyboard layer. \"\"\" if layerNumber == 0: # base",
"Wayland \"\"\" GNU/Linux driver (standalone / user-space) \"\"\" out = load_tpl(self, '.xkb') out",
"2]) # base + 1dk @property def full(self): return self._get_geometry([0, 4]) # base",
"row['offset'] + colOffset keys = row['keys'] base = list(template[2 + j * 3])",
"0: # base layer colOffset = 0 shiftPrevails = True else: # AltGr",
"' customAlpha = { '\\u00df': '\\u1e9e', # ß ẞ '\\u007c': '\\u00a6', # |",
"dead_keys = {} if 'deadkeys' in cfg: dead_keys = cfg['deadkeys'] for dk in",
"self.dead_keys: self.dk_index.append(dk['char']) # remove unused characters in self.dead_keys[].{base,alt} def layer_has_char(char, layer_index): for id",
"if len(letter) != 1: # dead key? return ' ' customAlpha = {",
"+ token + '(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value, text) def load_tpl(layout, ext): tpl = 'base'",
"self.layers[i + 2].items(): base_char = self.layers[i][name] if name != 'spce' and base_char !=",
"return exp.sub(lines_to_text(lines, indent), text) def substitute_token(text, token, value): exp = re.compile('\\\\$\\\\{' + token",
"CONFIG = { 'author': '<NAME>', 'license': 'WTFPL - Do What The Fuck You",
"for k in cfg: if k not in ['base', 'full', 'altgr', 'spacebar', 'deadkeys']:",
"True else: base = text_to_lines(cfg['base']) self._parse_template(base, dead_keys, rows, 0) self._parse_template(base, dead_keys, rows, 2)",
"3rd layers to the dead key for i in [0, 1]: for (name,",
"= 0 else: # AltGr or 1dk colOffset = 2 j = 0",
"self.dead_keys[ODK_ID] # alt_self (double-press), alt_space (1dk+space) odk['alt_space'] = spc['1dk'] for key in self.layers[0]:",
"self._get_geometry([0, 4]) # base + altgr @property def altgr(self): return self._get_geometry([4]) # altgr",
"osx_actions, osx_terminators, \\ klc_keymap, klc_deadkeys, klc_dk_index, \\ web_keymap, web_deadkeys from .utils import open_local_file,",
"\"\"\" GNU/Linux driver (standalone / user-space) \"\"\" out = load_tpl(self, '.xkb') out =",
"substitute_lines(out, 'LAYOUT', xkb_keymap(self, False)) return out @property def xkb_patch(self): \"\"\" GNU/Linux driver (system",
"dk.copy() i += 6 j += 1 ### # Geometry: base, full, altgr",
"↑ ⇑ '\\u2192': '\\u21d2', # → ⇒ '\\u2193': '\\u21d3', # ↓ ⇓ '\\u00b5':",
"= False self.has_1dk = False # load the YAML data (and its ancessor,",
"used_base self.dead_keys[dk_id]['alt'] = used_alt # 1dk behavior if ODK_ID in self.dead_keys: self.has_1dk =",
"= ('*' if base[i - 1] == '*' else '') + base[i] shiftKey",
"class KeyboardLayout: \"\"\" Lafayette-style keyboard layout: base + 1dk + altgr layers. \"\"\"",
"ODK_ID: odk['alt_self'] = self.layers[2][key] break # copy the 2nd and 3rd layers to",
"and shiftKey[0] == '*' if shiftPrevails: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] =",
"1dk colOffset = 2 j = 0 for row in rows: i =",
"@property def altgr(self): return self._get_geometry([4]) # altgr only ### # OS-specific drivers: keylayout,",
"altgr # def _fill_template(self, template, rows, layerNumber): \"\"\" Fill a template with a",
"keys: baseKey = ' ' if key in self.layers[layerNumber]: baseKey = self.layers[layerNumber][key] shiftKey",
"m = exp.match(line) if m: indent = m.group().split(prefix)[0] break return exp.sub(lines_to_text(lines, indent), text)",
"in self.layers[layer_index]: if self.layers[layer_index][id] == char: return True return False for dk_id in",
"+ j * 3] = ''.join(base) template[1 + j * 3] = ''.join(shift)",
"self.has_1dk = True odk = self.dead_keys[ODK_ID] # alt_self (double-press), alt_space (1dk+space) odk['alt_space'] =",
"if 'deadkeys' in cfg: dead_keys = cfg['deadkeys'] for dk in DEFAULT_DEAD_KEYS: found =",
"Constants # CONFIG = { 'author': '<NAME>', 'license': 'WTFPL - Do What The",
"in cfg else filename self.meta['name8'] = cfg['name8'] if 'name8' in cfg \\ else",
"= '*' if upper_key(baseKey) != shiftKey: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] =",
"\"\"\" `geometry` view of the requested layers. \"\"\" rows = GEOMETRY[name]['rows'] template =",
"'\\u00df': '\\u1e9e', # ß ẞ '\\u007c': '\\u00a6', # | ¦ '\\u003c': '\\u2264', #",
"= 0 for row in rows: i = row['offset'] + colOffset keys =",
"self.has_altgr = False self.has_1dk = False # load the YAML data (and its",
"2].items(): base_char = self.layers[i][name] if name != 'spce' and base_char != ODK_ID: odk['base']",
"i += 6 template[2 + j * 3] = ''.join(base) template[1 + j",
"Loader=yaml.SafeLoader) if 'extends' in cfg: path = os.path.join(os.path.dirname(filepath), cfg['extends']) ext = yaml.load(open(path), Loader=yaml.SafeLoader)",
"load_tpl(self, '.keylayout') for i, layer in enumerate(osx_keymap(self)): out = substitute_lines(out, 'LAYER_' + str(i),",
"- 1] == '*' else '') + shift[i] if layerNumber == 0 and",
"parsed.') print('Error: {}.'.format(e)) sys.exit(1) # metadata: self.meta for k in cfg: if k",
"except Exception as e: print('File could not be parsed.') print('Error: {}.'.format(e)) sys.exit(1) #",
"self._parse_template(base, dead_keys, rows, 2) if 'altgr' in cfg: self.has_altgr = True self._parse_template(text_to_lines(cfg['altgr']), dead_keys,",
"= row['offset'] + colOffset keys = row['keys'] base = list(template[2 + j *",
"@property def json(self): return { 'name': self.meta['name'], 'description': self.meta['description'], 'geometry': self.meta['geometry'].lower(), 'keymap': web_keymap(self),",
"{}, {}] self.dead_keys = {} # dictionary subset of DEAD_KEYS self.dk_index = []",
"2 and baseKey[0] == '*' dead_shift = len(shiftKey) == 2 and shiftKey[0] ==",
"' ': self.layers[layerNumber + 1][key] = shiftKey for dk in dead_keys: if baseKey",
"Mac OSX driver \"\"\" out = load_tpl(self, '.keylayout') for i, layer in enumerate(osx_keymap(self)):",
"' ' if key in self.layers[layerNumber]: baseKey = self.layers[layerNumber][key] shiftKey = ' '",
"self.meta['name'][0:8] self.meta['fileName'] = self.meta['name8'].lower() self.meta['lastChange'] = datetime.date.today().isoformat() dead_keys = {} if 'deadkeys' in",
"upper_key(baseKey) if baseKey != ' ': self.layers[layerNumber + 0][key] = baseKey if shiftKey",
"import datetime import os import re import sys import yaml from .template import",
"j * 3] = ''.join(shift) j += 1 return template def _get_geometry(self, layers=[0],",
"'.klc') out = substitute_lines(out, 'LAYOUT', klc_keymap(self)) out = substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self)) out =",
"+ 1dk @property def full(self): return self._get_geometry([0, 4]) # base + altgr @property",
"from .utils import open_local_file, load_data, text_to_lines, lines_to_text, \\ DEFAULT_DEAD_KEYS, ODK_ID ### # Helpers",
"== '*' dead_shift = len(shiftKey) == 2 and shiftKey[0] == '*' if shiftPrevails:",
"substitute_lines(out, 'GEOMETRY_base', layout.base) out = substitute_lines(out, 'GEOMETRY_full', layout.full) out = substitute_lines(out, 'GEOMETRY_altgr', layout.altgr)",
"self.meta[k] = cfg[k] filename = os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] = cfg['name'] if 'name' in cfg",
"base layer colOffset = 0 shiftPrevails = True else: # AltGr or 1dk",
"µ (to avoid getting `Μ` as uppercase) } if letter in customAlpha: return",
"out = load_tpl(self, '.xkb_patch') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, True)) return out ###",
"substitute_token(out, key, value) return out ### # Constants # CONFIG = { 'author':",
"and ext.startswith('.xkb'): tpl = 'full_1dk' out = open_local_file(os.path.join('tpl', tpl + ext)).read() out =",
"self.has_altgr = True else: base = text_to_lines(cfg['base']) self._parse_template(base, dead_keys, rows, 0) self._parse_template(base, dead_keys,",
"False # load the YAML data (and its ancessor, if any) try: cfg",
"found = any((d for d in dead_keys if d['char'] == dk['char'])) if not",
"return out @property def xkb(self): # will not work with Wayland \"\"\" GNU/Linux",
"self.layers[layerNumber + 1][key] = shiftKey for dk in dead_keys: if baseKey == dk['char']:",
"GEOMETRY[name]['rows'] template = GEOMETRY[name]['template'].split('\\n')[:-1] for i in layers: template = self._fill_template(template, rows, i)",
"in spc \\ else spc['1dk'] if self.has_altgr: self.layers[4]['spce'] = spc['altgr'] self.layers[5]['spce'] = spc['altgr_shift']",
"requested layers. \"\"\" rows = GEOMETRY[name]['rows'] template = GEOMETRY[name]['template'].split('\\n')[:-1] for i in layers:",
"klc_keymap, klc_deadkeys, klc_dk_index, \\ web_keymap, web_deadkeys from .utils import open_local_file, load_data, text_to_lines, lines_to_text,",
"return customAlpha[letter] elif letter.upper() != letter.lower(): return letter.upper() else: return ' ' def",
"text_to_lines(cfg['full']) self._parse_template(full, dead_keys, rows, 0) self._parse_template(full, dead_keys, rows, 4) self.has_altgr = True else:",
"i in [0, 1]: for (name, alt_char) in self.layers[i + 2].items(): base_char =",
"row in rows: i = row['offset'] + colOffset keys = row['keys'] base =",
"= text_to_lines(cfg['full']) self._parse_template(full, dead_keys, rows, 0) self._parse_template(full, dead_keys, rows, 4) self.has_altgr = True",
"'.*') indent = '' for line in text.split('\\n'): m = exp.match(line) if m:",
"'altgr': \" \", # U+0020 SPACE 'altgr_shift': \" \", # U+0020 SPACE '1dk':",
"'*' i += 6 template[2 + j * 3] = ''.join(base) template[1 +",
"'name' in cfg else filename self.meta['name8'] = cfg['name8'] if 'name8' in cfg \\",
"any((d for d in dead_keys if d['char'] == dk['char'])) if not found: dead_keys.append(dk)",
"base = self.dead_keys[dk_id]['base'] alt = self.dead_keys[dk_id]['alt'] used_base = '' used_alt = '' for",
"if 'name' in cfg else filename self.meta['name8'] = cfg['name8'] if 'name8' in cfg",
"= spc['1dk'] self.layers[3]['spce'] = spc['shift_1dk'] if 'shift_1dk' in spc \\ else spc['1dk'] if",
"### # Constants # CONFIG = { 'author': '<NAME>', 'license': 'WTFPL - Do",
"4]) # base + altgr @property def altgr(self): return self._get_geometry([4]) # altgr only",
"= substitute_lines(out, 'TERMINATORS', osx_terminators(self)) return out @property def klc(self): \"\"\" Windows driver (warning:",
"dead_keys, rows, 4) # space bar spc = SPACEBAR.copy() if 'spacebar' in cfg:",
"the YAML data (and its ancessor, if any) try: cfg = yaml.load(open(filepath), Loader=yaml.SafeLoader)",
"'name': self.meta['name'], 'description': self.meta['description'], 'geometry': self.meta['geometry'].lower(), 'keymap': web_keymap(self), 'deadkeys': web_deadkeys(self), 'altgr': self.has_altgr }",
"encoding) \"\"\" out = load_tpl(self, '.klc') out = substitute_lines(out, 'LAYOUT', klc_keymap(self)) out =",
"out @property def klc(self): \"\"\" Windows driver (warning: requires CR/LF + UTF16LE encoding)",
"full(self): return self._get_geometry([0, 4]) # base + altgr @property def altgr(self): return self._get_geometry([4])",
"= [{}, {}, {}, {}, {}, {}] self.dead_keys = {} # dictionary subset",
"return self._get_geometry([0, 4]) # base + altgr @property def altgr(self): return self._get_geometry([4]) #",
"# U+0020 SPACE 'altgr': \" \", # U+0020 SPACE 'altgr_shift': \" \", #",
"'*' if shiftPrevails: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*' if upper_key(baseKey)",
"\\ else self.meta['name'][0:8] self.meta['fileName'] = self.meta['name8'].lower() self.meta['lastChange'] = datetime.date.today().isoformat() dead_keys = {} if",
"{ 'shift': \" \", # U+0020 SPACE 'altgr': \" \", # U+0020 SPACE",
"dictionary self.meta = CONFIG.copy() # default parameters, hardcoded self.has_altgr = False self.has_1dk =",
"i += 6 j += 1 ### # Geometry: base, full, altgr #",
"# Geometry: base, full, altgr # def _fill_template(self, template, rows, layerNumber): \"\"\" Fill",
"Loader=yaml.SafeLoader) ext.update(cfg) cfg = ext except Exception as e: print('File could not be",
"# † ‡ '\\u2190': '\\u21d0', # ← ⇐ '\\u2191': '\\u21d1', # ↑ ⇑",
"substitute_lines(out, 'GEOMETRY_altgr', layout.altgr) for key, value in layout.meta.items(): out = substitute_token(out, key, value)",
"3]) for key in keys: baseKey = ' ' if key in self.layers[layerNumber]:",
"base layer colOffset = 0 else: # AltGr or 1dk colOffset = 2",
"{ '\\u00df': '\\u1e9e', # ß ẞ '\\u007c': '\\u00a6', # | ¦ '\\u003c': '\\u2264',",
"out = substitute_lines(out, 'ACTIONS', osx_actions(self)) out = substitute_lines(out, 'TERMINATORS', osx_terminators(self)) return out @property",
"key for i in [0, 1]: for (name, alt_char) in self.layers[i + 2].items():",
"data (and its ancessor, if any) try: cfg = yaml.load(open(filepath), Loader=yaml.SafeLoader) if 'extends'",
"\"\"\" # initialize a blank layout self.layers = [{}, {}, {}, {}, {},",
"else: # AltGr or 1dk colOffset = 2 shiftPrevails = False j =",
"' ' customAlpha = { '\\u00df': '\\u1e9e', # ß ẞ '\\u007c': '\\u00a6', #",
"open_local_file(os.path.join('tpl', tpl + ext)).read() out = substitute_lines(out, 'GEOMETRY_base', layout.base) out = substitute_lines(out, 'GEOMETRY_full',",
"APOSTROPHE '1dk_shift': \"'\" # U+0027 APOSTROPHE } GEOMETRY = load_data('geometry.yaml') ### # Main",
"\"\"\" def __init__(self, filepath): \"\"\" Import a keyboard layout to instanciate the object.",
"\"\"\" Mac OSX driver \"\"\" out = load_tpl(self, '.keylayout') for i, layer in",
"spc['shift'] self.layers[2]['spce'] = spc['1dk'] self.layers[3]['spce'] = spc['shift_1dk'] if 'shift_1dk' in spc \\ else",
"dk['char'] in self.dead_keys: self.dk_index.append(dk['char']) # remove unused characters in self.dead_keys[].{base,alt} def layer_has_char(char, layer_index):",
"# AltGr or 1dk colOffset = 2 shiftPrevails = False j = 0",
"SPACEBAR = { 'shift': \" \", # U+0020 SPACE 'altgr': \" \", #",
"dead keys: self.dk_index for dk in dead_keys: if dk['char'] in self.dead_keys: self.dk_index.append(dk['char']) #",
"could not be parsed.') print('Error: {}.'.format(e)) sys.exit(1) # metadata: self.meta for k in",
"\", # U+0020 SPACE 'altgr': \" \", # U+0020 SPACE 'altgr_shift': \" \",",
"keyboard layer from a template. \"\"\" if layerNumber == 0: # base layer",
"out = substitute_lines(out, 'TERMINATORS', osx_terminators(self)) return out @property def klc(self): \"\"\" Windows driver",
"'.xkb') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, False)) return out @property def xkb_patch(self): \"\"\"",
"cfg: if k not in ['base', 'full', 'altgr', 'spacebar', 'deadkeys']: self.meta[k] = cfg[k]",
"colOffset keys = row['keys'] base = list(template[2 + j * 3]) shift =",
"= substitute_lines(out, 'LAYOUT', klc_keymap(self)) out = substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self)) out = substitute_lines(out, 'DEAD_KEY_INDEX',",
"'1dk': \"'\", # U+0027 APOSTROPHE '1dk_shift': \"'\" # U+0027 APOSTROPHE } GEOMETRY =",
"in cfg: dead_keys = cfg['deadkeys'] for dk in DEFAULT_DEAD_KEYS: found = any((d for",
"} if letter in customAlpha: return customAlpha[letter] elif letter.upper() != letter.lower(): return letter.upper()",
"'LAYOUT', klc_keymap(self)) out = substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self)) out = substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self)) out",
"@property def klc(self): \"\"\" Windows driver (warning: requires CR/LF + UTF16LE encoding) \"\"\"",
"substitute_token(text, token, value): exp = re.compile('\\\\$\\\\{' + token + '(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value, text)",
"# @property def keylayout(self): \"\"\" Mac OSX driver \"\"\" out = load_tpl(self, '.keylayout')",
"'<NAME>', 'license': 'WTFPL - Do What The Fuck You Want Public License', 'geometry':",
"# dead key? return ' ' customAlpha = { '\\u00df': '\\u1e9e', # ß",
"'') + base[i] shiftKey = ('*' if shift[i - 1] == '*' else",
"key in self.layers[layerNumber]: baseKey = self.layers[layerNumber][key] shiftKey = ' ' if key in",
"@property def xkb_patch(self): \"\"\" GNU/Linux driver (system patch) \"\"\" out = load_tpl(self, '.xkb_patch')",
"the 2nd and 3rd layers to the dead key for i in [0,",
"out = substitute_lines(out, 'LAYOUT', klc_keymap(self)) out = substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self)) out = substitute_lines(out,",
"= True else: base = text_to_lines(cfg['base']) self._parse_template(base, dead_keys, rows, 0) self._parse_template(base, dead_keys, rows,",
"+ 2].items(): base_char = self.layers[i][name] if name != 'spce' and base_char != ODK_ID:",
"def json(self): return { 'name': self.meta['name'], 'description': self.meta['description'], 'geometry': self.meta['geometry'].lower(), 'keymap': web_keymap(self), 'deadkeys':",
"cfg \\ else self.meta['name'][0:8] self.meta['fileName'] = self.meta['name8'].lower() self.meta['lastChange'] = datetime.date.today().isoformat() dead_keys = {}",
"rows, 0) self._parse_template(base, dead_keys, rows, 2) if 'altgr' in cfg: self.has_altgr = True",
"{}, {}, {}, {}] self.dead_keys = {} # dictionary subset of DEAD_KEYS self.dk_index",
"dead_keys, rows, layerNumber): \"\"\" Extract a keyboard layer from a template. \"\"\" if",
"tpl = 'full_1dk' out = open_local_file(os.path.join('tpl', tpl + ext)).read() out = substitute_lines(out, 'GEOMETRY_base',",
"'DEAD_KEYS', klc_deadkeys(self)) out = substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self)) out = substitute_token(out, 'encoding', 'utf-16le') return",
"if layer_has_char(base[i], 0) or layer_has_char(base[i], 1): used_base += base[i] used_alt += alt[i] self.dead_keys[dk_id]['base']",
"value in layout.meta.items(): out = substitute_token(out, key, value) return out ### # Constants",
"ext.startswith('.xkb'): tpl = 'full_1dk' out = open_local_file(os.path.join('tpl', tpl + ext)).read() out = substitute_lines(out,",
"| ¦ '\\u003c': '\\u2264', # < ≤ '\\u003e': '\\u2265', # > ≥ '\\u2020':",
"list(template[1 + j * 3]) for key in keys: baseKey = ('*' if",
"def _fill_template(self, template, rows, layerNumber): \"\"\" Fill a template with a keyboard layer.",
"ext = yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg) cfg = ext except Exception as e: print('File",
"1]: shiftKey = self.layers[layerNumber + 1][key] dead_base = len(baseKey) == 2 and baseKey[0]",
"= self.layers[2][key] break # copy the 2nd and 3rd layers to the dead",
"avoid getting `Μ` as uppercase) } if letter in customAlpha: return customAlpha[letter] elif",
"dead key? return ' ' customAlpha = { '\\u00df': '\\u1e9e', # ß ẞ",
"dead_base = len(baseKey) == 2 and baseKey[0] == '*' dead_shift = len(shiftKey) ==",
"self.layers[layer_index]: if self.layers[layer_index][id] == char: return True return False for dk_id in self.dead_keys:",
"!= shiftKey: base[i] = baseKey[-1] if dead_base: base[i-1] = '*' else: base[i] =",
"in rows: i = row['offset'] + colOffset keys = row['keys'] base = list(template[2",
"self.layers[i][name] if name != 'spce' and base_char != ODK_ID: odk['base'] += base_char odk['alt']",
"its ancessor, if any) try: cfg = yaml.load(open(filepath), Loader=yaml.SafeLoader) if 'extends' in cfg:",
"# Main # class KeyboardLayout: \"\"\" Lafayette-style keyboard layout: base + 1dk +",
"m.group().split(prefix)[0] break return exp.sub(lines_to_text(lines, indent), text) def substitute_token(text, token, value): exp = re.compile('\\\\$\\\\{'",
"What The Fuck You Want Public License', 'geometry': 'ISO' } SPACEBAR = {",
"# base layer colOffset = 0 shiftPrevails = True else: # AltGr or",
"drivers: keylayout, klc, xkb, xkb_patch # @property def keylayout(self): \"\"\" Mac OSX driver",
"# 'shift' prevails baseKey = shiftKey.lower() if layerNumber != 0 and shiftKey ==",
"layer colOffset = 0 else: # AltGr or 1dk colOffset = 2 j",
"in self.dead_keys: self.has_1dk = True odk = self.dead_keys[ODK_ID] # alt_self (double-press), alt_space (1dk+space)",
"blank layout self.layers = [{}, {}, {}, {}, {}, {}] self.dead_keys = {}",
"& self.dead_keys rows = GEOMETRY[self.meta['geometry']]['rows'] if 'full' in cfg: full = text_to_lines(cfg['full']) self._parse_template(full,",
"break # copy the 2nd and 3rd layers to the dead key for",
"'\\u21d1', # ↑ ⇑ '\\u2192': '\\u21d2', # → ⇒ '\\u2193': '\\u21d3', # ↓",
"prefix = 'KALAMINE::' exp = re.compile('.*' + prefix + variable + '.*') indent",
"'extends' in cfg: path = os.path.join(os.path.dirname(filepath), cfg['extends']) ext = yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg) cfg",
"return template @property def base(self): return self._get_geometry([0, 2]) # base + 1dk @property",
"True)) return out ### # JSON output: keymap (base+altgr layers) and dead keys",
"\", # U+0020 SPACE 'altgr_shift': \" \", # U+0020 SPACE '1dk': \"'\", #",
"if 'altgr' in cfg: self.has_altgr = True self._parse_template(text_to_lines(cfg['altgr']), dead_keys, rows, 4) # space",
"active dead keys: self.dk_index for dk in dead_keys: if dk['char'] in self.dead_keys: self.dk_index.append(dk['char'])",
"layerNumber == 0: # base layer colOffset = 0 shiftPrevails = True else:",
"dead_shift: shift[i-1] = '*' if upper_key(baseKey) != shiftKey: base[i] = baseKey[-1] if dead_base:",
"self.meta['name8'].lower() self.meta['lastChange'] = datetime.date.today().isoformat() dead_keys = {} if 'deadkeys' in cfg: dead_keys =",
"`geometry` view of the requested layers. \"\"\" rows = GEOMETRY[name]['rows'] template = GEOMETRY[name]['template'].split('\\n')[:-1]",
"= {} # dictionary subset of DEAD_KEYS self.dk_index = [] # ordered keys",
"shiftKey = ' ' if key in self.layers[layerNumber + 1]: shiftKey = self.layers[layerNumber",
"+ j * 3]) for key in keys: baseKey = ('*' if base[i",
"base[i] = baseKey[-1] if dead_base: base[i-1] = '*' if upper_key(baseKey) != shiftKey: shift[i]",
"+ j * 3] = ''.join(shift) j += 1 return template def _get_geometry(self,",
"osx_keymap, osx_actions, osx_terminators, \\ klc_keymap, klc_deadkeys, klc_dk_index, \\ web_keymap, web_deadkeys from .utils import",
"else: # AltGr or 1dk colOffset = 2 j = 0 for row",
"upper_key(baseKey) != shiftKey: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*' i +=",
"base + altgr @property def altgr(self): return self._get_geometry([4]) # altgr only ### #",
"ext.update(cfg) cfg = ext except Exception as e: print('File could not be parsed.')",
"→ ⇒ '\\u2193': '\\u21d3', # ↓ ⇓ '\\u00b5': ' ', # µ (to",
"ancessor, if any) try: cfg = yaml.load(open(filepath), Loader=yaml.SafeLoader) if 'extends' in cfg: path",
"self.meta['name'] = cfg['name'] if 'name' in cfg else filename self.meta['name8'] = cfg['name8'] if",
"0 for row in rows: i = row['offset'] + colOffset keys = row['keys']",
"bar spc = SPACEBAR.copy() if 'spacebar' in cfg: for k in cfg['spacebar']: spc[k]",
"filepath): \"\"\" Import a keyboard layout to instanciate the object. \"\"\" # initialize",
"dead_keys if d['char'] == dk['char'])) if not found: dead_keys.append(dk) # keyboard layers: self.layers",
"return self._get_geometry([0, 2]) # base + 1dk @property def full(self): return self._get_geometry([0, 4])",
"= 0 shiftPrevails = True else: # AltGr or 1dk colOffset = 2",
"substitute_lines(out, 'LAYOUT', klc_keymap(self)) out = substitute_lines(out, 'DEAD_KEYS', klc_deadkeys(self)) out = substitute_lines(out, 'DEAD_KEY_INDEX', klc_dk_index(self))",
"used_alt += alt[i] self.dead_keys[dk_id]['base'] = used_base self.dead_keys[dk_id]['alt'] = used_alt # 1dk behavior if",
"# active dead keys: self.dk_index for dk in dead_keys: if dk['char'] in self.dead_keys:",
"return True return False for dk_id in self.dead_keys: base = self.dead_keys[dk_id]['base'] alt =",
"for key in self.layers[0]: if self.layers[0][key] == ODK_ID: odk['alt_self'] = self.layers[2][key] break #",
"customAlpha[letter] elif letter.upper() != letter.lower(): return letter.upper() else: return ' ' def substitute_lines(text,",
"layers to the dead key for i in [0, 1]: for (name, alt_char)",
"key, value) return out ### # Constants # CONFIG = { 'author': '<NAME>',",
"U+0020 SPACE 'altgr': \" \", # U+0020 SPACE 'altgr_shift': \" \", # U+0020",
"+= alt[i] self.dead_keys[dk_id]['base'] = used_base self.dead_keys[dk_id]['alt'] = used_alt # 1dk behavior if ODK_ID",
"AltGr or 1dk colOffset = 2 j = 0 for row in rows:",
"metadata: self.meta for k in cfg: if k not in ['base', 'full', 'altgr',",
"self.dk_index = [] # ordered keys of the above dictionary self.meta = CONFIG.copy()",
"+ prefix + variable + '.*') indent = '' for line in text.split('\\n'):",
"def klc(self): \"\"\" Windows driver (warning: requires CR/LF + UTF16LE encoding) \"\"\" out",
"from .template import xkb_keymap, \\ osx_keymap, osx_actions, osx_terminators, \\ klc_keymap, klc_deadkeys, klc_dk_index, \\",
"== '*' else '') + base[i] shiftKey = ('*' if shift[i - 1]",
"baseKey != ' ': self.layers[layerNumber + 0][key] = baseKey if shiftKey != '",
"False)) return out @property def xkb_patch(self): \"\"\" GNU/Linux driver (system patch) \"\"\" out",
"self._get_geometry([4]) # altgr only ### # OS-specific drivers: keylayout, klc, xkb, xkb_patch #",
"odk['alt_self'] = self.layers[2][key] break # copy the 2nd and 3rd layers to the",
"= GEOMETRY[name]['template'].split('\\n')[:-1] for i in layers: template = self._fill_template(template, rows, i) return template",
"tpl = 'full' if layout.has_1dk and ext.startswith('.xkb'): tpl = 'full_1dk' out = open_local_file(os.path.join('tpl',",
"CONFIG.copy() # default parameters, hardcoded self.has_altgr = False self.has_1dk = False # load",
"+ shift[i] if layerNumber == 0 and baseKey == ' ': # 'shift'",
"template[1 + j * 3] = ''.join(shift) j += 1 return template def",
"return self._get_geometry([4]) # altgr only ### # OS-specific drivers: keylayout, klc, xkb, xkb_patch",
"# def upper_key(letter): if len(letter) != 1: # dead key? return ' '",
"a blank layout self.layers = [{}, {}, {}, {}, {}, {}] self.dead_keys =",
"if ODK_ID in self.dead_keys: self.has_1dk = True odk = self.dead_keys[ODK_ID] # alt_self (double-press),",
"# @property def json(self): return { 'name': self.meta['name'], 'description': self.meta['description'], 'geometry': self.meta['geometry'].lower(), 'keymap':",
"'\\u21d0', # ← ⇐ '\\u2191': '\\u21d1', # ↑ ⇑ '\\u2192': '\\u21d2', # →",
"json(self): return { 'name': self.meta['name'], 'description': self.meta['description'], 'geometry': self.meta['geometry'].lower(), 'keymap': web_keymap(self), 'deadkeys': web_deadkeys(self),",
"layers. \"\"\" rows = GEOMETRY[name]['rows'] template = GEOMETRY[name]['template'].split('\\n')[:-1] for i in layers: template",
"= open_local_file(os.path.join('tpl', tpl + ext)).read() out = substitute_lines(out, 'GEOMETRY_base', layout.base) out = substitute_lines(out,",
"name != 'spce' and base_char != ODK_ID: odk['base'] += base_char odk['alt'] += alt_char",
"upper_key(letter): if len(letter) != 1: # dead key? return ' ' customAlpha =",
"range(len(base)): if layer_has_char(base[i], 0) or layer_has_char(base[i], 1): used_base += base[i] used_alt += alt[i]",
"# remove unused characters in self.dead_keys[].{base,alt} def layer_has_char(char, layer_index): for id in self.layers[layer_index]:",
"full, altgr # def _fill_template(self, template, rows, layerNumber): \"\"\" Fill a template with",
"a keyboard layout to instanciate the object. \"\"\" # initialize a blank layout",
"cfg['name'] if 'name' in cfg else filename self.meta['name8'] = cfg['name8'] if 'name8' in",
"'full', 'altgr', 'spacebar', 'deadkeys']: self.meta[k] = cfg[k] filename = os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] = cfg['name']",
"base[i-1] = '*' else: base[i] = baseKey[-1] if dead_base: base[i-1] = '*' if",
"{ 'name': self.meta['name'], 'description': self.meta['description'], 'geometry': self.meta['geometry'].lower(), 'keymap': web_keymap(self), 'deadkeys': web_deadkeys(self), 'altgr': self.has_altgr",
"0: # base layer colOffset = 0 else: # AltGr or 1dk colOffset",
"'\\u003e': '\\u2265', # > ≥ '\\u2020': '\\u2021', # † ‡ '\\u2190': '\\u21d0', #",
"= '' used_alt = '' for i in range(len(base)): if layer_has_char(base[i], 0) or",
"+ '.*') indent = '' for line in text.split('\\n'): m = exp.match(line) if",
"Helpers # def upper_key(letter): if len(letter) != 1: # dead key? return '",
"= yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg) cfg = ext except Exception as e: print('File could",
"= cfg['name'] if 'name' in cfg else filename self.meta['name8'] = cfg['name8'] if 'name8'",
"= len(baseKey) == 2 and baseKey[0] == '*' dead_shift = len(shiftKey) == 2",
"= yaml.load(open(filepath), Loader=yaml.SafeLoader) if 'extends' in cfg: path = os.path.join(os.path.dirname(filepath), cfg['extends']) ext =",
"+ 1][key] = shiftKey for dk in dead_keys: if baseKey == dk['char']: self.dead_keys[baseKey]",
"self._get_geometry([0, 2]) # base + 1dk @property def full(self): return self._get_geometry([0, 4]) #",
"### # JSON output: keymap (base+altgr layers) and dead keys # @property def",
"def full(self): return self._get_geometry([0, 4]) # base + altgr @property def altgr(self): return",
"shiftKey == dk['char']: self.dead_keys[shiftKey] = dk.copy() i += 6 j += 1 ###",
"key in self.layers[layerNumber + 1]: shiftKey = self.layers[layerNumber + 1][key] dead_base = len(baseKey)",
"dead_base: base[i-1] = '*' else: base[i] = baseKey[-1] if dead_base: base[i-1] = '*'",
"for dk in dead_keys: if baseKey == dk['char']: self.dead_keys[baseKey] = dk.copy() if shiftKey",
"1] == '*' else '') + shift[i] if layerNumber == 0 and baseKey",
"self.layers[layerNumber + 1][key] dead_base = len(baseKey) == 2 and baseKey[0] == '*' dead_shift",
"if layout.has_1dk and ext.startswith('.xkb'): tpl = 'full_1dk' out = open_local_file(os.path.join('tpl', tpl + ext)).read()",
"letter in customAlpha: return customAlpha[letter] elif letter.upper() != letter.lower(): return letter.upper() else: return",
"lines): prefix = 'KALAMINE::' exp = re.compile('.*' + prefix + variable + '.*')",
"'spacebar', 'deadkeys']: self.meta[k] = cfg[k] filename = os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] = cfg['name'] if 'name'",
"if layerNumber != 0 and shiftKey == ' ': shiftKey = upper_key(baseKey) if",
"out = substitute_lines(out, 'GEOMETRY_altgr', layout.altgr) for key, value in layout.meta.items(): out = substitute_token(out,",
"= [] # ordered keys of the above dictionary self.meta = CONFIG.copy() #",
"cfg = yaml.load(open(filepath), Loader=yaml.SafeLoader) if 'extends' in cfg: path = os.path.join(os.path.dirname(filepath), cfg['extends']) ext",
"= spc['altgr'] self.layers[5]['spce'] = spc['altgr_shift'] # active dead keys: self.dk_index for dk in",
"indent = m.group().split(prefix)[0] break return exp.sub(lines_to_text(lines, indent), text) def substitute_token(text, token, value): exp",
"self.dead_keys[shiftKey] = dk.copy() i += 6 j += 1 ### # Geometry: base,",
"altgr layers. \"\"\" def __init__(self, filepath): \"\"\" Import a keyboard layout to instanciate",
"+= 6 j += 1 ### # Geometry: base, full, altgr # def",
"rows: i = row['offset'] + colOffset keys = row['keys'] base = list(template[2 +",
"else self.meta['name'][0:8] self.meta['fileName'] = self.meta['name8'].lower() self.meta['lastChange'] = datetime.date.today().isoformat() dead_keys = {} if 'deadkeys'",
"# → ⇒ '\\u2193': '\\u21d3', # ↓ ⇓ '\\u00b5': ' ', # µ",
"dead_keys.append(dk) # keyboard layers: self.layers & self.dead_keys rows = GEOMETRY[self.meta['geometry']]['rows'] if 'full' in",
"return { 'name': self.meta['name'], 'description': self.meta['description'], 'geometry': self.meta['geometry'].lower(), 'keymap': web_keymap(self), 'deadkeys': web_deadkeys(self), 'altgr':",
"': # 'shift' prevails baseKey = shiftKey.lower() if layerNumber != 0 and shiftKey",
"self.meta for k in cfg: if k not in ['base', 'full', 'altgr', 'spacebar',",
"\" \", # U+0020 SPACE 'altgr': \" \", # U+0020 SPACE 'altgr_shift': \"",
"upper_key(baseKey) != shiftKey: base[i] = baseKey[-1] if dead_base: base[i-1] = '*' else: base[i]",
"+= base_char odk['alt'] += alt_char def _parse_template(self, template, dead_keys, rows, layerNumber): \"\"\" Extract",
"import xkb_keymap, \\ osx_keymap, osx_actions, osx_terminators, \\ klc_keymap, klc_deadkeys, klc_dk_index, \\ web_keymap, web_deadkeys",
"base(self): return self._get_geometry([0, 2]) # base + 1dk @property def full(self): return self._get_geometry([0,",
"'GEOMETRY_altgr', layout.altgr) for key, value in layout.meta.items(): out = substitute_token(out, key, value) return",
"''.join(shift) j += 1 return template def _get_geometry(self, layers=[0], name='ISO'): \"\"\" `geometry` view",
"rows, 0) self._parse_template(full, dead_keys, rows, 4) self.has_altgr = True else: base = text_to_lines(cfg['base'])",
"return exp.sub(value, text) def load_tpl(layout, ext): tpl = 'base' if layout.has_altgr: tpl =",
"letter.lower(): return letter.upper() else: return ' ' def substitute_lines(text, variable, lines): prefix =",
"'\\u21d3', # ↓ ⇓ '\\u00b5': ' ', # µ (to avoid getting `Μ`",
"klc(self): \"\"\" Windows driver (warning: requires CR/LF + UTF16LE encoding) \"\"\" out =",
"template, dead_keys, rows, layerNumber): \"\"\" Extract a keyboard layer from a template. \"\"\"",
"+ 1][key] dead_base = len(baseKey) == 2 and baseKey[0] == '*' dead_shift =",
"dictionary subset of DEAD_KEYS self.dk_index = [] # ordered keys of the above",
"= list(template[2 + j * 3]) shift = list(template[1 + j * 3])",
"template @property def base(self): return self._get_geometry([0, 2]) # base + 1dk @property def",
"self._fill_template(template, rows, i) return template @property def base(self): return self._get_geometry([0, 2]) # base",
"with Wayland \"\"\" GNU/Linux driver (standalone / user-space) \"\"\" out = load_tpl(self, '.xkb')",
"dead key for i in [0, 1]: for (name, alt_char) in self.layers[i +",
"of the requested layers. \"\"\" rows = GEOMETRY[name]['rows'] template = GEOMETRY[name]['template'].split('\\n')[:-1] for i",
"baseKey[0] == '*' dead_shift = len(shiftKey) == 2 and shiftKey[0] == '*' if",
"= ' ' if key in self.layers[layerNumber + 1]: shiftKey = self.layers[layerNumber +",
"driver (warning: requires CR/LF + UTF16LE encoding) \"\"\" out = load_tpl(self, '.klc') out",
"variable + '.*') indent = '' for line in text.split('\\n'): m = exp.match(line)",
"== 0: # base layer colOffset = 0 else: # AltGr or 1dk",
"not found: dead_keys.append(dk) # keyboard layers: self.layers & self.dead_keys rows = GEOMETRY[self.meta['geometry']]['rows'] if",
"out = load_tpl(self, '.xkb') out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, False)) return out @property",
"os import re import sys import yaml from .template import xkb_keymap, \\ osx_keymap,",
"ß ẞ '\\u007c': '\\u00a6', # | ¦ '\\u003c': '\\u2264', # < ≤ '\\u003e':",
"= os.path.splitext(os.path.basename(filepath))[0] self.meta['name'] = cfg['name'] if 'name' in cfg else filename self.meta['name8'] =",
"baseKey = shiftKey.lower() if layerNumber != 0 and shiftKey == ' ': shiftKey",
"out = substitute_lines(out, 'LAYOUT', xkb_keymap(self, False)) return out @property def xkb_patch(self): \"\"\" GNU/Linux",
"text) def load_tpl(layout, ext): tpl = 'base' if layout.has_altgr: tpl = 'full' if",
"cfg: for k in cfg['spacebar']: spc[k] = cfg['spacebar'][k] self.layers[0]['spce'] = ' ' self.layers[1]['spce']",
"print('Error: {}.'.format(e)) sys.exit(1) # metadata: self.meta for k in cfg: if k not",
"'*' if upper_key(baseKey) != shiftKey: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*'",
"shiftKey[-1] if dead_shift: shift[i-1] = '*' i += 6 template[2 + j *",
"list(template[1 + j * 3]) for key in keys: baseKey = ' '",
"self.layers & self.dead_keys rows = GEOMETRY[self.meta['geometry']]['rows'] if 'full' in cfg: full = text_to_lines(cfg['full'])",
"= ''.join(base) template[1 + j * 3] = ''.join(shift) j += 1 return",
"ext)).read() out = substitute_lines(out, 'GEOMETRY_base', layout.base) out = substitute_lines(out, 'GEOMETRY_full', layout.full) out =",
"as e: print('File could not be parsed.') print('Error: {}.'.format(e)) sys.exit(1) # metadata: self.meta",
"= os.path.join(os.path.dirname(filepath), cfg['extends']) ext = yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg) cfg = ext except Exception",
"def substitute_lines(text, variable, lines): prefix = 'KALAMINE::' exp = re.compile('.*' + prefix +",
"else '') + base[i] shiftKey = ('*' if shift[i - 1] == '*'",
"(warning: requires CR/LF + UTF16LE encoding) \"\"\" out = load_tpl(self, '.klc') out =",
"= 2 shiftPrevails = False j = 0 for row in rows: i",
"layers) and dead keys # @property def json(self): return { 'name': self.meta['name'], 'description':",
"+ 0][key] = baseKey if shiftKey != ' ': self.layers[layerNumber + 1][key] =",
"Extract a keyboard layer from a template. \"\"\" if layerNumber == 0: #",
"= substitute_lines(out, 'GEOMETRY_base', layout.base) out = substitute_lines(out, 'GEOMETRY_full', layout.full) out = substitute_lines(out, 'GEOMETRY_altgr',",
"subset of DEAD_KEYS self.dk_index = [] # ordered keys of the above dictionary",
"= spc['altgr_shift'] # active dead keys: self.dk_index for dk in dead_keys: if dk['char']",
"if key in self.layers[layerNumber + 1]: shiftKey = self.layers[layerNumber + 1][key] dead_base =",
"cfg['extends']) ext = yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg) cfg = ext except Exception as e:",
"i, layer in enumerate(osx_keymap(self)): out = substitute_lines(out, 'LAYER_' + str(i), layer) out =",
"+ altgr @property def altgr(self): return self._get_geometry([4]) # altgr only ### # OS-specific",
"spc['1dk'] for key in self.layers[0]: if self.layers[0][key] == ODK_ID: odk['alt_self'] = self.layers[2][key] break",
"+= 6 template[2 + j * 3] = ''.join(base) template[1 + j *",
"filename self.meta['name8'] = cfg['name8'] if 'name8' in cfg \\ else self.meta['name'][0:8] self.meta['fileName'] =",
"False j = 0 for row in rows: i = row['offset'] + colOffset",
"layerNumber != 0 and shiftKey == ' ': shiftKey = upper_key(baseKey) if baseKey",
"= ''.join(shift) j += 1 return template def _get_geometry(self, layers=[0], name='ISO'): \"\"\" `geometry`",
"== '*' if shiftPrevails: shift[i] = shiftKey[-1] if dead_shift: shift[i-1] = '*' if",
"dk['char']: self.dead_keys[shiftKey] = dk.copy() i += 6 j += 1 ### # Geometry:",
"if name != 'spce' and base_char != ODK_ID: odk['base'] += base_char odk['alt'] +=",
"i in range(len(base)): if layer_has_char(base[i], 0) or layer_has_char(base[i], 1): used_base += base[i] used_alt",
"<reponame>qwerty-fr/kalamine #!/usr/bin/env python3 import datetime import os import re import sys import yaml",
"k not in ['base', 'full', 'altgr', 'spacebar', 'deadkeys']: self.meta[k] = cfg[k] filename =",
"cfg: path = os.path.join(os.path.dirname(filepath), cfg['extends']) ext = yaml.load(open(path), Loader=yaml.SafeLoader) ext.update(cfg) cfg = ext",
"\"\"\" Windows driver (warning: requires CR/LF + UTF16LE encoding) \"\"\" out = load_tpl(self,",
"dead_keys, rows, 0) self._parse_template(full, dead_keys, rows, 4) self.has_altgr = True else: base =",
"0) self._parse_template(base, dead_keys, rows, 2) if 'altgr' in cfg: self.has_altgr = True self._parse_template(text_to_lines(cfg['altgr']),",
"id in self.layers[layer_index]: if self.layers[layer_index][id] == char: return True return False for dk_id",
"altgr @property def altgr(self): return self._get_geometry([4]) # altgr only ### # OS-specific drivers:",
"if 'name8' in cfg \\ else self.meta['name'][0:8] self.meta['fileName'] = self.meta['name8'].lower() self.meta['lastChange'] = datetime.date.today().isoformat()",
"self.dead_keys[dk_id]['alt'] used_base = '' used_alt = '' for i in range(len(base)): if layer_has_char(base[i],",
"'ISO' } SPACEBAR = { 'shift': \" \", # U+0020 SPACE 'altgr': \"",
"colOffset = 0 else: # AltGr or 1dk colOffset = 2 j =",
"== 2 and baseKey[0] == '*' dead_shift = len(shiftKey) == 2 and shiftKey[0]",
"to the dead key for i in [0, 1]: for (name, alt_char) in",
"\\ web_keymap, web_deadkeys from .utils import open_local_file, load_data, text_to_lines, lines_to_text, \\ DEFAULT_DEAD_KEYS, ODK_ID",
"layout.has_1dk and ext.startswith('.xkb'): tpl = 'full_1dk' out = open_local_file(os.path.join('tpl', tpl + ext)).read() out",
"= self.layers[layerNumber][key] shiftKey = ' ' if key in self.layers[layerNumber + 1]: shiftKey",
"def substitute_token(text, token, value): exp = re.compile('\\\\$\\\\{' + token + '(=[^\\\\}]*){0,1}\\\\}') return exp.sub(value,",
"≤ '\\u003e': '\\u2265', # > ≥ '\\u2020': '\\u2021', # † ‡ '\\u2190': '\\u21d0',",
"a keyboard layer. \"\"\" if layerNumber == 0: # base layer colOffset ="
] |
[
"by key(elem). Analogous to itertools.group_by; however this function doesn't care about the order",
"of x, f(x), f(f(x)), ... See Clojure's iterate. \"\"\" while True: yield x",
"keys. \"\"\" d: dict[_K, list[_T]] = {} for elem in iterable: d.setdefault(key(elem), []).append(elem)",
"Iterable, TypeVar _T = TypeVar(\"_T\") _K = TypeVar(\"_K\") def empty_str(t: str) -> bool:",
"bool]) -> list[list[_T]]: after_split: list[list[_T]] = [] current: list[_T] = [] for elem",
"care about the order of the keys. \"\"\" d: dict[_K, list[_T]] = {}",
"Callable[[_T], _T], x: _T = 0) -> Generator[_T, None, None]: \"\"\"Iterate produces an",
"Callable[[_T], bool]) -> list[list[_T]]: after_split: list[list[_T]] = [] current: list[_T] = [] for",
"TypeVar _T = TypeVar(\"_T\") _K = TypeVar(\"_K\") def empty_str(t: str) -> bool: return",
"<gh_stars>0 from typing import Callable, Generator, Iterable, TypeVar _T = TypeVar(\"_T\") _K =",
"t == \"\" def split_on(seq: Iterable[_T], pred: Callable[[_T], bool]) -> list[list[_T]]: after_split: list[list[_T]]",
"Split on this element if current: after_split.append(current) current = [] else: current.append(elem) if",
"empty_str(t: str) -> bool: return t == \"\" def split_on(seq: Iterable[_T], pred: Callable[[_T],",
"return after_split def aggregate_by(iterable: Iterable[_T], key: Callable[[_T], _K]) -> dict[_K, list[_T]]: \"\"\"Groups elements",
"for elem in iterable: d.setdefault(key(elem), []).append(elem) return d def iterate(f: Callable[[_T], _T], x:",
"seq: if pred(elem): # Split on this element if current: after_split.append(current) current =",
"the order of the keys. \"\"\" d: dict[_K, list[_T]] = {} for elem",
"= 0) -> Generator[_T, None, None]: \"\"\"Iterate produces an infinite sequence of x,",
"_T = TypeVar(\"_T\") _K = TypeVar(\"_K\") def empty_str(t: str) -> bool: return t",
"x, f(x), f(f(x)), ... See Clojure's iterate. \"\"\" while True: yield x x",
"after_split.append(current) return after_split def aggregate_by(iterable: Iterable[_T], key: Callable[[_T], _K]) -> dict[_K, list[_T]]: \"\"\"Groups",
"sequence of x, f(x), f(f(x)), ... See Clojure's iterate. \"\"\" while True: yield",
"-> bool: return t == \"\" def split_on(seq: Iterable[_T], pred: Callable[[_T], bool]) ->",
"list[_T]]: \"\"\"Groups elements from an iterable by key(elem). Analogous to itertools.group_by; however this",
"[] current: list[_T] = [] for elem in seq: if pred(elem): # Split",
"iterable: d.setdefault(key(elem), []).append(elem) return d def iterate(f: Callable[[_T], _T], x: _T = 0)",
"def empty_str(t: str) -> bool: return t == \"\" def split_on(seq: Iterable[_T], pred:",
"this element if current: after_split.append(current) current = [] else: current.append(elem) if current: after_split.append(current)",
"# Split on this element if current: after_split.append(current) current = [] else: current.append(elem)",
"after_split: list[list[_T]] = [] current: list[_T] = [] for elem in seq: if",
"elements from an iterable by key(elem). Analogous to itertools.group_by; however this function doesn't",
"infinite sequence of x, f(x), f(f(x)), ... See Clojure's iterate. \"\"\" while True:",
"TypeVar(\"_T\") _K = TypeVar(\"_K\") def empty_str(t: str) -> bool: return t == \"\"",
"list[_T]] = {} for elem in iterable: d.setdefault(key(elem), []).append(elem) return d def iterate(f:",
"def split_on(seq: Iterable[_T], pred: Callable[[_T], bool]) -> list[list[_T]]: after_split: list[list[_T]] = [] current:",
"from typing import Callable, Generator, Iterable, TypeVar _T = TypeVar(\"_T\") _K = TypeVar(\"_K\")",
"f(f(x)), ... See Clojure's iterate. \"\"\" while True: yield x x = f(x)",
"on this element if current: after_split.append(current) current = [] else: current.append(elem) if current:",
"dict[_K, list[_T]] = {} for elem in iterable: d.setdefault(key(elem), []).append(elem) return d def",
"this function doesn't care about the order of the keys. \"\"\" d: dict[_K,",
"elem in seq: if pred(elem): # Split on this element if current: after_split.append(current)",
"to itertools.group_by; however this function doesn't care about the order of the keys.",
"doesn't care about the order of the keys. \"\"\" d: dict[_K, list[_T]] =",
"Generator[_T, None, None]: \"\"\"Iterate produces an infinite sequence of x, f(x), f(f(x)), ...",
"of the keys. \"\"\" d: dict[_K, list[_T]] = {} for elem in iterable:",
"list[_T] = [] for elem in seq: if pred(elem): # Split on this",
"Analogous to itertools.group_by; however this function doesn't care about the order of the",
"Iterable[_T], key: Callable[[_T], _K]) -> dict[_K, list[_T]]: \"\"\"Groups elements from an iterable by",
"iterable by key(elem). Analogous to itertools.group_by; however this function doesn't care about the",
"current: after_split.append(current) return after_split def aggregate_by(iterable: Iterable[_T], key: Callable[[_T], _K]) -> dict[_K, list[_T]]:",
"if current: after_split.append(current) return after_split def aggregate_by(iterable: Iterable[_T], key: Callable[[_T], _K]) -> dict[_K,",
"= [] current: list[_T] = [] for elem in seq: if pred(elem): #",
"import Callable, Generator, Iterable, TypeVar _T = TypeVar(\"_T\") _K = TypeVar(\"_K\") def empty_str(t:",
"dict[_K, list[_T]]: \"\"\"Groups elements from an iterable by key(elem). Analogous to itertools.group_by; however",
"after_split.append(current) current = [] else: current.append(elem) if current: after_split.append(current) return after_split def aggregate_by(iterable:",
"= TypeVar(\"_K\") def empty_str(t: str) -> bool: return t == \"\" def split_on(seq:",
"TypeVar(\"_K\") def empty_str(t: str) -> bool: return t == \"\" def split_on(seq: Iterable[_T],",
"element if current: after_split.append(current) current = [] else: current.append(elem) if current: after_split.append(current) return",
"None]: \"\"\"Iterate produces an infinite sequence of x, f(x), f(f(x)), ... See Clojure's",
"after_split def aggregate_by(iterable: Iterable[_T], key: Callable[[_T], _K]) -> dict[_K, list[_T]]: \"\"\"Groups elements from",
"current.append(elem) if current: after_split.append(current) return after_split def aggregate_by(iterable: Iterable[_T], key: Callable[[_T], _K]) ->",
"in iterable: d.setdefault(key(elem), []).append(elem) return d def iterate(f: Callable[[_T], _T], x: _T =",
"bool: return t == \"\" def split_on(seq: Iterable[_T], pred: Callable[[_T], bool]) -> list[list[_T]]:",
"however this function doesn't care about the order of the keys. \"\"\" d:",
"the keys. \"\"\" d: dict[_K, list[_T]] = {} for elem in iterable: d.setdefault(key(elem),",
"-> list[list[_T]]: after_split: list[list[_T]] = [] current: list[_T] = [] for elem in",
"function doesn't care about the order of the keys. \"\"\" d: dict[_K, list[_T]]",
"[]).append(elem) return d def iterate(f: Callable[[_T], _T], x: _T = 0) -> Generator[_T,",
"_K]) -> dict[_K, list[_T]]: \"\"\"Groups elements from an iterable by key(elem). Analogous to",
"x: _T = 0) -> Generator[_T, None, None]: \"\"\"Iterate produces an infinite sequence",
"{} for elem in iterable: d.setdefault(key(elem), []).append(elem) return d def iterate(f: Callable[[_T], _T],",
"\"\"\"Groups elements from an iterable by key(elem). Analogous to itertools.group_by; however this function",
"current: after_split.append(current) current = [] else: current.append(elem) if current: after_split.append(current) return after_split def",
"\"\" def split_on(seq: Iterable[_T], pred: Callable[[_T], bool]) -> list[list[_T]]: after_split: list[list[_T]] = []",
"from an iterable by key(elem). Analogous to itertools.group_by; however this function doesn't care",
"[] for elem in seq: if pred(elem): # Split on this element if",
"Iterable[_T], pred: Callable[[_T], bool]) -> list[list[_T]]: after_split: list[list[_T]] = [] current: list[_T] =",
"= [] for elem in seq: if pred(elem): # Split on this element",
"0) -> Generator[_T, None, None]: \"\"\"Iterate produces an infinite sequence of x, f(x),",
"Callable, Generator, Iterable, TypeVar _T = TypeVar(\"_T\") _K = TypeVar(\"_K\") def empty_str(t: str)",
"key: Callable[[_T], _K]) -> dict[_K, list[_T]]: \"\"\"Groups elements from an iterable by key(elem).",
"in seq: if pred(elem): # Split on this element if current: after_split.append(current) current",
"= TypeVar(\"_T\") _K = TypeVar(\"_K\") def empty_str(t: str) -> bool: return t ==",
"list[list[_T]]: after_split: list[list[_T]] = [] current: list[_T] = [] for elem in seq:",
"elem in iterable: d.setdefault(key(elem), []).append(elem) return d def iterate(f: Callable[[_T], _T], x: _T",
"else: current.append(elem) if current: after_split.append(current) return after_split def aggregate_by(iterable: Iterable[_T], key: Callable[[_T], _K])",
"_T], x: _T = 0) -> Generator[_T, None, None]: \"\"\"Iterate produces an infinite",
"if current: after_split.append(current) current = [] else: current.append(elem) if current: after_split.append(current) return after_split",
"return d def iterate(f: Callable[[_T], _T], x: _T = 0) -> Generator[_T, None,",
"list[list[_T]] = [] current: list[_T] = [] for elem in seq: if pred(elem):",
"pred: Callable[[_T], bool]) -> list[list[_T]]: after_split: list[list[_T]] = [] current: list[_T] = []",
"an infinite sequence of x, f(x), f(f(x)), ... See Clojure's iterate. \"\"\" while",
"d: dict[_K, list[_T]] = {} for elem in iterable: d.setdefault(key(elem), []).append(elem) return d",
"== \"\" def split_on(seq: Iterable[_T], pred: Callable[[_T], bool]) -> list[list[_T]]: after_split: list[list[_T]] =",
"None, None]: \"\"\"Iterate produces an infinite sequence of x, f(x), f(f(x)), ... See",
"iterate(f: Callable[[_T], _T], x: _T = 0) -> Generator[_T, None, None]: \"\"\"Iterate produces",
"typing import Callable, Generator, Iterable, TypeVar _T = TypeVar(\"_T\") _K = TypeVar(\"_K\") def",
"produces an infinite sequence of x, f(x), f(f(x)), ... See Clojure's iterate. \"\"\"",
"Callable[[_T], _K]) -> dict[_K, list[_T]]: \"\"\"Groups elements from an iterable by key(elem). Analogous",
"d.setdefault(key(elem), []).append(elem) return d def iterate(f: Callable[[_T], _T], x: _T = 0) ->",
"key(elem). Analogous to itertools.group_by; however this function doesn't care about the order of",
"for elem in seq: if pred(elem): # Split on this element if current:",
"\"\"\" d: dict[_K, list[_T]] = {} for elem in iterable: d.setdefault(key(elem), []).append(elem) return",
"-> dict[_K, list[_T]]: \"\"\"Groups elements from an iterable by key(elem). Analogous to itertools.group_by;",
"def aggregate_by(iterable: Iterable[_T], key: Callable[[_T], _K]) -> dict[_K, list[_T]]: \"\"\"Groups elements from an",
"about the order of the keys. \"\"\" d: dict[_K, list[_T]] = {} for",
"str) -> bool: return t == \"\" def split_on(seq: Iterable[_T], pred: Callable[[_T], bool])",
"order of the keys. \"\"\" d: dict[_K, list[_T]] = {} for elem in",
"= {} for elem in iterable: d.setdefault(key(elem), []).append(elem) return d def iterate(f: Callable[[_T],",
"_T = 0) -> Generator[_T, None, None]: \"\"\"Iterate produces an infinite sequence of",
"d def iterate(f: Callable[[_T], _T], x: _T = 0) -> Generator[_T, None, None]:",
"pred(elem): # Split on this element if current: after_split.append(current) current = [] else:",
"f(x), f(f(x)), ... See Clojure's iterate. \"\"\" while True: yield x x =",
"current: list[_T] = [] for elem in seq: if pred(elem): # Split on",
"def iterate(f: Callable[[_T], _T], x: _T = 0) -> Generator[_T, None, None]: \"\"\"Iterate",
"Generator, Iterable, TypeVar _T = TypeVar(\"_T\") _K = TypeVar(\"_K\") def empty_str(t: str) ->",
"[] else: current.append(elem) if current: after_split.append(current) return after_split def aggregate_by(iterable: Iterable[_T], key: Callable[[_T],",
"itertools.group_by; however this function doesn't care about the order of the keys. \"\"\"",
"-> Generator[_T, None, None]: \"\"\"Iterate produces an infinite sequence of x, f(x), f(f(x)),",
"return t == \"\" def split_on(seq: Iterable[_T], pred: Callable[[_T], bool]) -> list[list[_T]]: after_split:",
"= [] else: current.append(elem) if current: after_split.append(current) return after_split def aggregate_by(iterable: Iterable[_T], key:",
"if pred(elem): # Split on this element if current: after_split.append(current) current = []",
"current = [] else: current.append(elem) if current: after_split.append(current) return after_split def aggregate_by(iterable: Iterable[_T],",
"split_on(seq: Iterable[_T], pred: Callable[[_T], bool]) -> list[list[_T]]: after_split: list[list[_T]] = [] current: list[_T]",
"an iterable by key(elem). Analogous to itertools.group_by; however this function doesn't care about",
"_K = TypeVar(\"_K\") def empty_str(t: str) -> bool: return t == \"\" def",
"aggregate_by(iterable: Iterable[_T], key: Callable[[_T], _K]) -> dict[_K, list[_T]]: \"\"\"Groups elements from an iterable",
"\"\"\"Iterate produces an infinite sequence of x, f(x), f(f(x)), ... See Clojure's iterate."
] |
[
"env.observation_space.seed(seed) # return env # # return thunk class MFRL: \"\"\" Model-Free Reinforcement",
"rl.environments from rl.data.buffer import TrajBuffer, ReplayBuffer # from rl.data.buffer import TrajBuffer, ReplayBufferNP #",
"el += 1 t += 1 self.buffer.store(o, a, r, o_next, v, log_pi, el)",
"evaluate = self.configs['algorithm']['evaluation'] # Inintialize Learning environment self.learn_env = gym.make(name) self._seed_env(self.learn_env) assert isinstance",
"-10, 10)) # env = gym.wrappers.NormalizeReward(env) # env = gym.wrappers.TransformReward(env, lambda reward: np.clip(reward,",
"if el == max_el: with T.no_grad(): v = self.actor_critic.get_v(T.Tensor(o)).cpu() else: # print('v=0') v",
"# Evaluation episodic return ES = [] # Evaluation episodic score EL =",
"# # return thunk class MFRL: \"\"\" Model-Free Reinforcement Learning \"\"\" def __init__(self,",
"if evaluate: print('[ Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el = self.configs['environment']['horizon'] EZ =",
"else d # Ignore artificial termination self.buffer.store_transition(o, a, r, o_next, d) o =",
"# def thunk(): # print('in thunk') # env = gym.make(env_id) # env =",
"self.act_up_lim = self.learn_env.action_space.high self.act_low_lim = self.learn_env.action_space.low def _seed_env(self, env): env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def",
"self.actor_critic.get_action_np(o) with T.no_grad(): a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next,",
"= device def _build(self): self._set_env() self._set_buffer() def _set_env(self): name = self.configs['environment']['name'] evaluate =",
"t += 1 self.buffer.store_transition(o, a, r, d, v, log_pi, el) if d_next or",
"'mujoco-pddm-shadowhand': # for i in range(len(ES)): # ES[i] /= EL[i] return EZ, ES,",
"= TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) else: self.buffer = ReplayBuffer(self.obs_dim, self.act_dim,",
"seed) # print('init MBRL!') self.exp_prefix = exp_prefix self.configs = configs self.seed = seed",
"self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': S += info['score'] el += 1 EZ.append(Z) if self.configs['environment']['type'] ==",
"gym.make(env_id) # env = gym.wrappers.RecordEpisodeStatistics(env) # if capture_video: # if idx == 0:",
"if evaluate: # Ininialize Evaluation environment self.eval_env = gym.make(name) self._seed_env(self.eval_env) else: self.eval_env =",
"environment self.learn_env = gym.make(name) self._seed_env(self.learn_env) assert isinstance (self.learn_env.action_space, Box), \"Works only with continuous",
"= TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) def initialize_learning(self, NT, Ni): max_el",
"self.configs['environment']['horizon'] o, Z, el, t = self.learn_env.reset(), 0, 0, 0 if Ni <",
"o_next Z += r el +=1 t +=1 if d or (el ==",
"= self.configs['algorithm']['learning']['expl_epochs'] max_el = self.configs['environment']['horizon'] if n > Nx: a = self.actor_critic.get_action_np(o) #",
"evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el =",
"num_traj=400): # print('Initialize a New Buffer..') seed = self.seed device = self._device_ if",
"return ES = [] # Evaluation episodic score EL = [] # Evaluation",
"self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] # a = self.actor_critic.get_action_np(o) with T.no_grad(): a, log_pi, v",
"EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el = self.configs['environment']['horizon'] EZ = [] # Evaluation episodic return",
"\"\"\" Model-Free Reinforcement Learning \"\"\" def __init__(self, exp_prefix, configs, seed, device): # super(MFRL,",
"= False if el == max_el else d # Ignore artificial termination self.buffer.store_transition(o,",
"while not(d or (el == max_el)): # with T.no_grad(): a, _, _ =",
"if idx == 0: # env = gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") # env = gym.wrappers.ClipAction(env)",
"# env.observation_space.seed(seed) # return env # # return thunk class MFRL: \"\"\" Model-Free",
"r el +=1 t +=1 if d or (el == max_el): o, Z,",
"self._set_env() self._set_buffer() def _set_env(self): name = self.configs['environment']['name'] evaluate = self.configs['algorithm']['evaluation'] # Inintialize Learning",
"# print('Initialize a New Buffer..') seed = self.seed device = self._device_ if self.configs['algorithm']['on-policy']:",
"self.actor_critic.get_action_np(o, deterministic=True) o, r, d, info = self.eval_env.step(a) Z += r if self.configs['environment']['type']",
"0, 0 while not(d or (el == max_el)): # with T.no_grad(): a, _,",
"= self.actor_critic.get_v(T.Tensor(o)).cpu() else: # print('v=0') v = T.Tensor([0.0]) self.buffer.finish_path(el, v) # print(f'termination: t={t}",
"self.learn_env.action_space.shape[0] self.act_up_lim = self.learn_env.action_space.high self.act_low_lim = self.learn_env.action_space.low def _seed_env(self, env): env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed)",
"only with continuous action space\" if evaluate: # Ininialize Evaluation environment self.eval_env =",
"make_env(env_id, seed, idx, capture_video, run_name): # def thunk(): # print('in thunk') # env",
"= seed self._device_ = device def _build(self): self._set_env() self._set_buffer() def _set_env(self): name =",
"= self._device_ if self.configs['algorithm']['on-policy']: # num_traj = 40 horizon = 1000 max_size =",
"o = o_next Z += r el +=1 t +=1 if d or",
"self._seed_env(self.eval_env) else: self.eval_env = None # Spaces dimensions self.obs_dim = self.learn_env.observation_space.shape[0] self.act_dim =",
"import gym from gym.spaces import Box import numpy as np import torch as",
"Evaluation episodic return ES = [] # Evaluation episodic score EL = []",
"env = gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10)) # env.seed(seed) # env.action_space.seed(seed) #",
"num_traj, max_size, self.seed, device) def initialize_learning(self, NT, Ni): max_el = self.configs['environment']['horizon'] o, Z,",
"= self.actor_critic.get_action_np(o) with T.no_grad(): a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi)",
"gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10)) # env = gym.wrappers.NormalizeReward(env) # env =",
"r, d, info = self.learn_env.step(a) d = True if el == max_el else",
"v, log_pi, el) if d_next or (el == max_el): # o_next, Z, el",
"self.learn_env = gym.make(name) self._seed_env(self.learn_env) assert isinstance (self.learn_env.action_space, Box), \"Works only with continuous action",
"o, Z, el, t def evaluate_op(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation",
"np import torch as T import rl.environments from rl.data.buffer import TrajBuffer, ReplayBuffer #",
"gym from gym.spaces import Box import numpy as np import torch as T",
"d or (el == max_el): o, Z, el = self.learn_env.reset(), 0, 0 return",
"Starting') for ni in range(1, Ni+1): print(f'[ Initial exploaration ] Epoch {ni}') nt",
"score EL = [] # Evaluation episodic length for ee in range(1, EE+1):",
"rl.data.buffer import TrajBuffer, ReplayBufferNP # def make_env(env_id, seed, idx, capture_video, run_name): # def",
"max_el): o, Z, el = self.learn_env.reset(), 0, 0 return o, Z, el, t",
"o_next if d or (el == max_el): if el == max_el: with T.no_grad():",
"while nt < NT: # Random actions a = self.learn_env.action_space.sample() o_next, r, d,",
"Nx = self.configs['algorithm']['learning']['expl_epochs'] max_el = self.configs['environment']['horizon'] if n > Nx: a = self.actor_critic.get_action_np(o)",
"0, 0 with T.no_grad(): v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next, el) # print(f'termination: t={t}",
"el += 1 EZ.append(Z) if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el) # if self.configs['environment']['type']",
"internact_op(self, n, o, d, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon']",
"env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def _set_buffer(self): max_size = self.configs['data']['buffer_size'] device = self._device_ if self.configs['algorithm']['on-policy']: max_size",
"self.configs = configs self.seed = seed self._device_ = device def _build(self): self._set_env() self._set_buffer()",
"max_el = self.configs['environment']['horizon'] EZ = [] # Evaluation episodic return ES = []",
"max_size, self.seed, device) else: self.buffer = ReplayBuffer(self.obs_dim, self.act_dim, max_size, self.seed, device) def initialize_buffer(self,",
"print('in thunk') # env = gym.make(env_id) # env = gym.wrappers.RecordEpisodeStatistics(env) # if capture_video:",
"Z += r el += 1 t += 1 self.buffer.store(o, a, r, o_next,",
"= self.eval_env.reset(), False, 0, 0, 0 while not(d or (el == max_el)): #",
"d, Z, el, t def internact_opB(self, n, o, Z, el, t): Nt =",
"# return env # # return thunk class MFRL: \"\"\" Model-Free Reinforcement Learning",
"o_next, r, d, info = self.learn_env.step(a) d = True if el == max_el",
"TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) else: self.buffer = ReplayBuffer(self.obs_dim, self.act_dim, max_size,",
"gym.wrappers.NormalizeObservation(env) # env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10)) # env =",
"print(f'[ Initial exploaration ] Starting') for ni in range(1, Ni+1): print(f'[ Initial exploaration",
"self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el = self.configs['environment']['horizon'] EZ",
"num_traj = max_size//20 horizon = 1000 self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size,",
"horizon = 1000 self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) else:",
"= 40 horizon = 1000 max_size = self.configs['data']['batch_size'] self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon,",
"Spaces dimensions self.obs_dim = self.learn_env.observation_space.shape[0] self.act_dim = self.learn_env.action_space.shape[0] self.act_up_lim = self.learn_env.action_space.high self.act_low_lim =",
"o, d, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] # a",
"self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next, el) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o_next, d_next,",
"0, 0, 0 o, d = o_next, d_next return o, d, Z, el,",
"gym.make(name) self._seed_env(self.learn_env) assert isinstance (self.learn_env.action_space, Box), \"Works only with continuous action space\" if",
"seed = self.seed device = self._device_ if self.configs['algorithm']['on-policy']: # num_traj = 40 horizon",
"import numpy as np import torch as T import rl.environments from rl.data.buffer import",
"= self.configs['environment']['horizon'] EZ = [] # Evaluation episodic return ES = [] #",
"el += 1 t += 1 self.buffer.store_transition(o, a, r, d, v, log_pi, el)",
"log_pi, el) o = o_next if d or (el == max_el): if el",
"Z, el = self.learn_env.reset(), 0, 0 return o, Z, el, t def internact(self,",
"el, t def internact(self, n, o, Z, el, t): Nx = self.configs['algorithm']['learning']['expl_epochs'] max_el",
"= gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10)) # env.seed(seed) # env.action_space.seed(seed) # env.observation_space.seed(seed)",
"+= r el +=1 t +=1 if d or (el == max_el): o,",
"action | No reparameterization # Deterministic action | No reparameterization else: a =",
"self.configs['algorithm']['on-policy']: max_size = self.configs['data']['batch_size'] num_traj = max_size//20 horizon = 1000 self.buffer = TrajBuffer(self.obs_dim,",
"o, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] # a =",
"class MFRL: \"\"\" Model-Free Reinforcement Learning \"\"\" def __init__(self, exp_prefix, configs, seed, device):",
"= self.seed device = self._device_ if self.configs['algorithm']['on-policy']: # num_traj = 40 horizon =",
"[ Agent Evaluation ] Episode: {ee} ', end='\\r') o, d, Z, S, el",
"while not(d or (el == max_el)): # Take deterministic actions at evaluation time",
"capture_video, run_name): # def thunk(): # print('in thunk') # env = gym.make(env_id) #",
"self.learn_env.action_space.low def _seed_env(self, env): env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def _set_buffer(self): max_size = self.configs['data']['buffer_size'] device",
"= self.configs['algorithm']['evaluation']['eval_episodes'] max_el = self.configs['environment']['horizon'] EZ = [] # Evaluation episodic return ES",
"range(1, Ni+1): print(f'[ Initial exploaration ] Epoch {ni}') nt = 0 while nt",
"self.learn_env.reset(), 0, 0 with T.no_grad(): v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next, el) # print(f'termination:",
"environment self.eval_env = gym.make(name) self._seed_env(self.eval_env) else: self.eval_env = None # Spaces dimensions self.obs_dim",
"0 while nt < NT: # Random actions a = self.learn_env.action_space.sample() o_next, r,",
"return o, Z, el, t def internact(self, n, o, Z, el, t): Nx",
"max_el = self.configs['environment']['horizon'] # a = self.actor_critic.get_action_np(o) with T.no_grad(): a, log_pi, v =",
"# Take deterministic actions at evaluation time a = self.actor_critic.get_action_np(o, deterministic=True) # Deterministic",
"print('[ Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el = self.configs['environment']['horizon'] EZ = [] #",
"True if el == max_el else d # Ignore artificial termination self.buffer.store_transition(o, a,",
"+= r el += 1 t += 1 self.buffer.store(o, a, r, o_next, v,",
"= self.learn_env.action_space.sample() o_next, r, d, _ = self.learn_env.step(a) d = False if el",
"d_next return o, d, Z, el, t def internact_opB(self, n, o, Z, el,",
"el == max_el: with T.no_grad(): v = self.actor_critic.get_v(T.Tensor(o)).cpu() else: # print('v=0') v =",
"dimensions self.obs_dim = self.learn_env.observation_space.shape[0] self.act_dim = self.learn_env.action_space.shape[0] self.act_up_lim = self.learn_env.action_space.high self.act_low_lim = self.learn_env.action_space.low",
"torch as T import rl.environments from rl.data.buffer import TrajBuffer, ReplayBuffer # from rl.data.buffer",
"el +=1 t +=1 if d or (el == max_el): o, Z, el",
"Agent Evaluation ] Episode: {ee} ', end='\\r') o, d, Z, S, el =",
"evaluate: # Ininialize Evaluation environment self.eval_env = gym.make(name) self._seed_env(self.eval_env) else: self.eval_env = None",
"Z, el, t = self.learn_env.reset(), 0, 0, 0 if Ni < 1: return",
"if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el) # if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': # for",
"d_next, _ = self.learn_env.step(a) Z += r el += 1 t += 1",
"== max_el)): # Take deterministic actions at evaluation time a = self.actor_critic.get_action_np(o, deterministic=True)",
"idx == 0: # env = gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") # env = gym.wrappers.ClipAction(env) #",
"0, 0 o, d = o_next, d_next return o, d, Z, el, t",
"device) def initialize_learning(self, NT, Ni): max_el = self.configs['environment']['horizon'] o, Z, el, t =",
"env = gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") # env = gym.wrappers.ClipAction(env) # env = gym.wrappers.NormalizeObservation(env) #",
"No reparameterization else: a = self.learn_env.action_space.sample() o_next, r, d, _ = self.learn_env.step(a) d",
"Z, el, t def internact(self, n, o, Z, el, t): Nx = self.configs['algorithm']['learning']['expl_epochs']",
"Ininialize Evaluation environment self.eval_env = gym.make(name) self._seed_env(self.eval_env) else: self.eval_env = None # Spaces",
"TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) def initialize_learning(self, NT, Ni): max_el =",
"d or (el == max_el): if el == max_el: with T.no_grad(): v =",
"r if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': S += info['score'] el += 1 EZ.append(Z) if",
"self.configs['data']['buffer_size'] device = self._device_ if self.configs['algorithm']['on-policy']: max_size = self.configs['data']['batch_size'] num_traj = max_size//20 horizon",
"> Nx: a = self.actor_critic.get_action_np(o) # Stochastic action | No reparameterization # Deterministic",
"def internact_op(self, n, o, d, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el =",
"# ES[i] /= EL[i] return EZ, ES, EL def evaluate(self): evaluate = self.configs['algorithm']['evaluation']",
"== max_el): if el == max_el: with T.no_grad(): v = self.actor_critic.get_v(T.Tensor(o)).cpu() else: #",
"gym.make(name) self._seed_env(self.eval_env) else: self.eval_env = None # Spaces dimensions self.obs_dim = self.learn_env.observation_space.shape[0] self.act_dim",
"Z, S, el = self.eval_env.reset(), False, 0, 0, 0 while not(d or (el",
"Z, el = self.learn_env.reset(), 0, 0 with T.no_grad(): v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next,",
"rl.data.buffer import TrajBuffer, ReplayBuffer # from rl.data.buffer import TrajBuffer, ReplayBufferNP # def make_env(env_id,",
"Inintialize Learning environment self.learn_env = gym.make(name) self._seed_env(self.learn_env) assert isinstance (self.learn_env.action_space, Box), \"Works only",
"1 self.buffer.store(o, a, r, o_next, v, log_pi, el) o = o_next if d",
"def initialize_learning(self, NT, Ni): max_el = self.configs['environment']['horizon'] o, Z, el, t = self.learn_env.reset(),",
"EL.append(el) # if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': # for i in range(len(ES)): # ES[i]",
"import TrajBuffer, ReplayBufferNP # def make_env(env_id, seed, idx, capture_video, run_name): # def thunk():",
"range(1, EE+1): print(f' [ Agent Evaluation ] Episode: {ee} ', end='\\r') o, d,",
"horizon, num_traj, max_size, self.seed, device) else: self.buffer = ReplayBuffer(self.obs_dim, self.act_dim, max_size, self.seed, device)",
"Box), \"Works only with continuous action space\" if evaluate: # Ininialize Evaluation environment",
"= gym.make(name) self._seed_env(self.eval_env) else: self.eval_env = None # Spaces dimensions self.obs_dim = self.learn_env.observation_space.shape[0]",
"reparameterization # Deterministic action | No reparameterization else: a = self.learn_env.action_space.sample() o_next, r,",
"max_size = self.configs['data']['buffer_size'] device = self._device_ if self.configs['algorithm']['on-policy']: max_size = self.configs['data']['batch_size'] num_traj =",
"# env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10)) # env = gym.wrappers.NormalizeReward(env)",
"def internact(self, n, o, Z, el, t): Nx = self.configs['algorithm']['learning']['expl_epochs'] max_el = self.configs['environment']['horizon']",
"el = self.eval_env.reset(), False, 0, 0, 0 while not(d or (el == max_el)):",
"env): env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def _set_buffer(self): max_size = self.configs['data']['buffer_size'] device = self._device_ if",
"range(len(ES)): # ES[i] /= EL[i] return EZ, ES, EL def evaluate(self): evaluate =",
"if capture_video: # if idx == 0: # env = gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") #",
"horizon = 1000 max_size = self.configs['data']['batch_size'] self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size,",
"# Spaces dimensions self.obs_dim = self.learn_env.observation_space.shape[0] self.act_dim = self.learn_env.action_space.shape[0] self.act_up_lim = self.learn_env.action_space.high self.act_low_lim",
"0, 0 while not(d or (el == max_el)): # Take deterministic actions at",
"exploaration ] Starting') for ni in range(1, Ni+1): print(f'[ Initial exploaration ] Epoch",
"a New Buffer..') seed = self.seed device = self._device_ if self.configs['algorithm']['on-policy']: # num_traj",
"= self.learn_env.action_space.low def _seed_env(self, env): env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def _set_buffer(self): max_size = self.configs['data']['buffer_size']",
"a, _, _ = self.actor_critic.get_pi(T.Tensor(o)) a = self.actor_critic.get_action_np(o, deterministic=True) # a = self.actor_critic.get_action_np(o,",
"= self.learn_env.action_space.shape[0] self.act_up_lim = self.learn_env.action_space.high self.act_low_lim = self.learn_env.action_space.low def _seed_env(self, env): env.seed(self.seed) env.action_space.seed(self.seed)",
"= [] # Evaluation episodic return ES = [] # Evaluation episodic score",
"el = self.learn_env.reset(), 0, 0 nt += 1 return o, Z, el, t",
"self.eval_env.step(a) Z += r if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': S += info['score'] el +=",
"t = self.learn_env.reset(), 0, 0, 0 if Ni < 1: return o, Z,",
"# env.seed(seed) # env.action_space.seed(seed) # env.observation_space.seed(seed) # return env # # return thunk",
"NT: # Random actions a = self.learn_env.action_space.sample() o_next, r, d, info = self.learn_env.step(a)",
"max_el: with T.no_grad(): v = self.actor_critic.get_v(T.Tensor(o)).cpu() else: # print('v=0') v = T.Tensor([0.0]) self.buffer.finish_path(el,",
"return o, Z, el, t print(f'[ Initial exploaration ] Starting') for ni in",
"in range(1, Ni+1): print(f'[ Initial exploaration ] Epoch {ni}') nt = 0 while",
"{ee} ', end='\\r') o, d, Z, S, el = self.eval_env.reset(), False, 0, 0,",
"print('init MBRL!') self.exp_prefix = exp_prefix self.configs = configs self.seed = seed self._device_ =",
"(self.learn_env.action_space, Box), \"Works only with continuous action space\" if evaluate: # Ininialize Evaluation",
"self.learn_env.reset(), 0, 0 return o, Z, el, t def internact(self, n, o, Z,",
"if Ni < 1: return o, Z, el, t print(f'[ Initial exploaration ]",
"0 with T.no_grad(): v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next, el) # print(f'termination: t={t} |",
"self.configs['data']['batch_size'] self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) def initialize_learning(self, NT,",
"= max_size//20 horizon = 1000 self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed,",
"Episode: {ee} ', end='\\r') o, d, Z, S, el = self.eval_env.reset(), False, 0,",
"# env = gym.make(env_id) # env = gym.wrappers.RecordEpisodeStatistics(env) # if capture_video: # if",
"el, t print(f'[ Initial exploaration ] Starting') for ni in range(1, Ni+1): print(f'[",
"t def internact(self, n, o, Z, el, t): Nx = self.configs['algorithm']['learning']['expl_epochs'] max_el =",
"gym.wrappers.ClipAction(env) # env = gym.wrappers.NormalizeObservation(env) # env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10,",
"10)) # env = gym.wrappers.NormalizeReward(env) # env = gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10,",
"self.configs['environment']['horizon'] if n > Nx: a = self.actor_critic.get_action_np(o) # Stochastic action | No",
"self.eval_env.reset(), False, 0, 0, 0 while not(d or (el == max_el)): # with",
"_ = self.learn_env.step(a) Z += r el += 1 t += 1 self.buffer.store(o,",
"1 self.buffer.store_transition(o, a, r, d, v, log_pi, el) if d_next or (el ==",
"= self.configs['data']['batch_size'] self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) def initialize_learning(self,",
"log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d_next, _ =",
"seed, device): # super(MFRL, self).__init__(configs, seed) # print('init MBRL!') self.exp_prefix = exp_prefix self.configs",
"= self.learn_env.action_space.high self.act_low_lim = self.learn_env.action_space.low def _seed_env(self, env): env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def _set_buffer(self):",
"= self._device_ if self.configs['algorithm']['on-policy']: max_size = self.configs['data']['batch_size'] num_traj = max_size//20 horizon = 1000",
"el) if d_next or (el == max_el): # o_next, Z, el = self.learn_env.reset(),",
"ReplayBuffer(self.obs_dim, self.act_dim, max_size, self.seed, device) def initialize_buffer(self, num_traj=400): # print('Initialize a New Buffer..')",
"40 horizon = 1000 max_size = self.configs['data']['batch_size'] self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj,",
"= gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") # env = gym.wrappers.ClipAction(env) # env = gym.wrappers.NormalizeObservation(env) # env",
"Deterministic action | No reparameterization else: a = self.learn_env.action_space.sample() o_next, r, d, _",
"# if capture_video: # if idx == 0: # env = gym.wrappers.RecordVideo(env, f\"videos/{run_name}\")",
"New Buffer..') seed = self.seed device = self._device_ if self.configs['algorithm']['on-policy']: # num_traj =",
"def make_env(env_id, seed, idx, capture_video, run_name): # def thunk(): # print('in thunk') #",
"with continuous action space\" if evaluate: # Ininialize Evaluation environment self.eval_env = gym.make(name)",
"isinstance (self.learn_env.action_space, Box), \"Works only with continuous action space\" if evaluate: # Ininialize",
"el = self.learn_env.reset(), 0, 0 return o, Z, el, t def internact(self, n,",
"= self.learn_env.reset(), 0, 0 with T.no_grad(): v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next, el) #",
"_ = self.learn_env.step(a) d = False if el == max_el else d #",
"'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el) # if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': # for i in range(len(ES)):",
"o, Z, el, t = self.learn_env.reset(), 0, 0, 0 if Ni < 1:",
"MFRL: \"\"\" Model-Free Reinforcement Learning \"\"\" def __init__(self, exp_prefix, configs, seed, device): #",
"= self.learn_env.action_space.sample() o_next, r, d, info = self.learn_env.step(a) d = True if el",
"o, Z, el, t def internact_op(self, n, o, d, Z, el, t): Nt",
"Z, el, t): Nx = self.configs['algorithm']['learning']['expl_epochs'] max_el = self.configs['environment']['horizon'] if n > Nx:",
"= self.actor_critic.get_pi(T.Tensor(o)) a = self.actor_critic.get_action_np(o, deterministic=True) # a = self.actor_critic.get_action_np(o, deterministic=True) o, r,",
"as np import torch as T import rl.environments from rl.data.buffer import TrajBuffer, ReplayBuffer",
"max_el = self.configs['environment']['horizon'] if n > Nx: a = self.actor_critic.get_action_np(o) # Stochastic action",
"self.eval_env.reset(), False, 0, 0, 0 while not(d or (el == max_el)): # Take",
"if d or (el == max_el): if el == max_el: with T.no_grad(): v",
"# print('log_pi: ', log_pi) o_next, r, d_next, _ = self.learn_env.step(a) Z += r",
"+= 1 self.buffer.store_transition(o, a, r, d, v, log_pi, el) if d_next or (el",
"= self.eval_env.step(a) Z += r if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': S += info['score'] el",
"el) o = o_next if d or (el == max_el): if el ==",
"end='\\r') o, d, Z, S, el = self.eval_env.reset(), False, 0, 0, 0 while",
"def _set_env(self): name = self.configs['environment']['name'] evaluate = self.configs['algorithm']['evaluation'] # Inintialize Learning environment self.learn_env",
"0, 0, 0 if Ni < 1: return o, Z, el, t print(f'[",
"el = self.learn_env.reset(), 0, 0 return o, Z, el, t def evaluate_op(self): evaluate",
"0 while not(d or (el == max_el)): # Take deterministic actions at evaluation",
"self.seed, device) def initialize_learning(self, NT, Ni): max_el = self.configs['environment']['horizon'] o, Z, el, t",
"el) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o_next, d_next, Z, el =",
"self.eval_env = None # Spaces dimensions self.obs_dim = self.learn_env.observation_space.shape[0] self.act_dim = self.learn_env.action_space.shape[0] self.act_up_lim",
"from gym.spaces import Box import numpy as np import torch as T import",
"self.configs['data']['batch_size'] num_traj = max_size//20 horizon = 1000 self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj,",
"o, d, Z, el, t def internact_opB(self, n, o, Z, el, t): Nt",
"+= r if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': S += info['score'] el += 1 EZ.append(Z)",
"initialize_learning(self, NT, Ni): max_el = self.configs['environment']['horizon'] o, Z, el, t = self.learn_env.reset(), 0,",
"continuous action space\" if evaluate: # Ininialize Evaluation environment self.eval_env = gym.make(name) self._seed_env(self.eval_env)",
"at evaluation time a = self.actor_critic.get_action_np(o, deterministic=True) # Deterministic action | No reparameterization",
"self.learn_env.step(a) Z += r el += 1 t += 1 self.buffer.store_transition(o, a, r,",
"self.learn_env.action_space.sample() o_next, r, d, _ = self.learn_env.step(a) d = False if el ==",
"Z += r el += 1 t += 1 self.buffer.store_transition(o, a, r, d,",
"# Evaluation episodic length for ee in range(1, EE+1): print(f' [ Agent Evaluation",
"r, d, _ = self.learn_env.step(a) Z += r el += 1 t +=",
"(el == max_el)): # with T.no_grad(): a, _, _ = self.actor_critic.get_pi(T.Tensor(o)) a =",
"self.act_dim, max_size, self.seed, device) def initialize_buffer(self, num_traj=400): # print('Initialize a New Buffer..') seed",
"r el += 1 t += 1 self.buffer.store_transition(o, a, r, d, v, log_pi,",
"r el += 1 t += 1 self.buffer.store(o, a, r, o_next, v, log_pi,",
"np.clip(reward, -10, 10)) # env.seed(seed) # env.action_space.seed(seed) # env.observation_space.seed(seed) # return env #",
"= 1000 self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) else: self.buffer",
"or (el == max_el): o, Z, el = self.learn_env.reset(), 0, 0 return o,",
"None # Spaces dimensions self.obs_dim = self.learn_env.observation_space.shape[0] self.act_dim = self.learn_env.action_space.shape[0] self.act_up_lim = self.learn_env.action_space.high",
"el == max_el else d # Ignore artificial termination self.buffer.store_transition(o, a, r, o_next,",
"length for ee in range(1, EE+1): print(f' [ Agent Evaluation ] Episode: {ee}",
"space\" if evaluate: # Ininialize Evaluation environment self.eval_env = gym.make(name) self._seed_env(self.eval_env) else: self.eval_env",
"self._device_ = device def _build(self): self._set_env() self._set_buffer() def _set_env(self): name = self.configs['environment']['name'] evaluate",
"if d or (el == max_el): o, Z, el = self.learn_env.reset(), 0, 0",
"episodic length for ee in range(1, EE+1): print(f' [ Agent Evaluation ] Episode:",
"max_el)): # with T.no_grad(): a, _, _ = self.actor_critic.get_pi(T.Tensor(o)) a = self.actor_critic.get_action_np(o, deterministic=True)",
"self.actor_critic.get_action_np(o) # Stochastic action | No reparameterization # Deterministic action | No reparameterization",
"exp_prefix, configs, seed, device): # super(MFRL, self).__init__(configs, seed) # print('init MBRL!') self.exp_prefix =",
"Learning environment self.learn_env = gym.make(name) self._seed_env(self.learn_env) assert isinstance (self.learn_env.action_space, Box), \"Works only with",
"= self.configs['algorithm']['evaluation'] # Inintialize Learning environment self.learn_env = gym.make(name) self._seed_env(self.learn_env) assert isinstance (self.learn_env.action_space,",
"# print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o_next, d_next, Z, el = self.learn_env.reset(),",
"(el == max_el)): # Take deterministic actions at evaluation time a = self.actor_critic.get_action_np(o,",
"or (el == max_el): # o_next, Z, el = self.learn_env.reset(), 0, 0 with",
"= None # Spaces dimensions self.obs_dim = self.learn_env.observation_space.shape[0] self.act_dim = self.learn_env.action_space.shape[0] self.act_up_lim =",
"self._seed_env(self.learn_env) assert isinstance (self.learn_env.action_space, Box), \"Works only with continuous action space\" if evaluate:",
"0, 0 nt += 1 return o, Z, el, t def internact_op(self, n,",
"with T.no_grad(): a, _, _ = self.actor_critic.get_pi(T.Tensor(o)) a = self.actor_critic.get_action_np(o, deterministic=True) # a",
"self.learn_env.step(a) Z += r el += 1 t += 1 self.buffer.store(o, a, r,",
"# Ininialize Evaluation environment self.eval_env = gym.make(name) self._seed_env(self.eval_env) else: self.eval_env = None #",
"ES.append(S/el) EL.append(el) # if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': # for i in range(len(ES)): #",
"print(f'[ Initial exploaration ] Epoch {ni}') nt = 0 while nt < NT:",
"'mujoco-pddm-shadowhand': S += info['score'] el += 1 EZ.append(Z) if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': ES.append(S/el)",
"a = self.actor_critic.get_action_np(o) with T.no_grad(): a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ',",
"self.actor_critic.get_v(T.Tensor(o)).cpu() else: # print('v=0') v = T.Tensor([0.0]) self.buffer.finish_path(el, v) # print(f'termination: t={t} |",
"t def internact_opB(self, n, o, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el =",
"_set_env(self): name = self.configs['environment']['name'] evaluate = self.configs['algorithm']['evaluation'] # Inintialize Learning environment self.learn_env =",
"idx, capture_video, run_name): # def thunk(): # print('in thunk') # env = gym.make(env_id)",
"ReplayBuffer # from rl.data.buffer import TrajBuffer, ReplayBufferNP # def make_env(env_id, seed, idx, capture_video,",
"self.seed, device) else: self.buffer = ReplayBuffer(self.obs_dim, self.act_dim, max_size, self.seed, device) def initialize_buffer(self, num_traj=400):",
"el, t def internact_opB(self, n, o, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el",
"v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d, _ = self.learn_env.step(a)",
"t += 1 self.buffer.store(o, a, r, o_next, v, log_pi, el) o = o_next",
"gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10)) # env.seed(seed) # env.action_space.seed(seed) # env.observation_space.seed(seed) #",
"as T import rl.environments from rl.data.buffer import TrajBuffer, ReplayBuffer # from rl.data.buffer import",
"total_size={self.buffer.total_size()}') o, Z, el = self.learn_env.reset(), 0, 0 return o, Z, el, t",
"o, Z, el = self.learn_env.reset(), 0, 0 nt += 1 return o, Z,",
"# a = self.actor_critic.get_action_np(o) with T.no_grad(): a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi:",
"print('Initialize a New Buffer..') seed = self.seed device = self._device_ if self.configs['algorithm']['on-policy']: #",
"lambda reward: np.clip(reward, -10, 10)) # env.seed(seed) # env.action_space.seed(seed) # env.observation_space.seed(seed) # return",
"TrajBuffer, ReplayBuffer # from rl.data.buffer import TrajBuffer, ReplayBufferNP # def make_env(env_id, seed, idx,",
"# env = gym.wrappers.ClipAction(env) # env = gym.wrappers.NormalizeObservation(env) # env = gym.wrappers.TransformObservation(env, lambda",
"Z, el = self.learn_env.reset(), 0, 0 nt += 1 return o, Z, el,",
"d = False if el == max_el else d # Ignore artificial termination",
"t def internact_op(self, n, o, d, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el",
"# super(MFRL, self).__init__(configs, seed) # print('init MBRL!') self.exp_prefix = exp_prefix self.configs = configs",
"T.no_grad(): v = self.actor_critic.get_v(T.Tensor(o)).cpu() else: # print('v=0') v = T.Tensor([0.0]) self.buffer.finish_path(el, v) #",
"import torch as T import rl.environments from rl.data.buffer import TrajBuffer, ReplayBuffer # from",
"a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d, _",
"__init__(self, exp_prefix, configs, seed, device): # super(MFRL, self).__init__(configs, seed) # print('init MBRL!') self.exp_prefix",
"# a = self.actor_critic.get_action_np(o, deterministic=True) o, r, d, info = self.eval_env.step(a) Z +=",
"self.configs['environment']['name'] evaluate = self.configs['algorithm']['evaluation'] # Inintialize Learning environment self.learn_env = gym.make(name) self._seed_env(self.learn_env) assert",
"max_size = self.configs['data']['batch_size'] num_traj = max_size//20 horizon = 1000 self.buffer = TrajBuffer(self.obs_dim, self.act_dim,",
"(el == max_el): o, Z, el = self.learn_env.reset(), 0, 0 nt += 1",
"self.buffer.store(o, a, r, o_next, v, log_pi, el) o = o_next if d or",
"Ni): max_el = self.configs['environment']['horizon'] o, Z, el, t = self.learn_env.reset(), 0, 0, 0",
"# with T.no_grad(): a, _, _ = self.actor_critic.get_pi(T.Tensor(o)) a = self.actor_critic.get_action_np(o, deterministic=True) #",
"run_name): # def thunk(): # print('in thunk') # env = gym.make(env_id) # env",
"a, r, o_next, d) o = o_next Z += r el +=1 t",
"nt < NT: # Random actions a = self.learn_env.action_space.sample() o_next, r, d, info",
"] Episode: {ee} ', end='\\r') o, d, Z, S, el = self.eval_env.reset(), False,",
"_seed_env(self, env): env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def _set_buffer(self): max_size = self.configs['data']['buffer_size'] device = self._device_",
"Random actions a = self.learn_env.action_space.sample() o_next, r, d, info = self.learn_env.step(a) d =",
"# print('in thunk') # env = gym.make(env_id) # env = gym.wrappers.RecordEpisodeStatistics(env) # if",
"EZ, ES, EL def evaluate(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]')",
"max_size//20 horizon = 1000 self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device)",
"self.configs['algorithm']['evaluation']['eval_episodes'] max_el = self.configs['environment']['horizon'] EZ = [] # Evaluation episodic return ES =",
"return env # # return thunk class MFRL: \"\"\" Model-Free Reinforcement Learning \"\"\"",
"return o, d, Z, el, t def internact_opB(self, n, o, Z, el, t):",
"env.seed(seed) # env.action_space.seed(seed) # env.observation_space.seed(seed) # return env # # return thunk class",
"exploaration ] Epoch {ni}') nt = 0 while nt < NT: # Random",
"d_next or (el == max_el): # o_next, Z, el = self.learn_env.reset(), 0, 0",
"self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el) # if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': # for i",
"el = self.learn_env.reset(), 0, 0 with T.no_grad(): v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next, el)",
"env = gym.wrappers.NormalizeReward(env) # env = gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10)) #",
"T import rl.environments from rl.data.buffer import TrajBuffer, ReplayBuffer # from rl.data.buffer import TrajBuffer,",
"= self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el = self.configs['environment']['horizon']",
"else: self.eval_env = None # Spaces dimensions self.obs_dim = self.learn_env.observation_space.shape[0] self.act_dim = self.learn_env.action_space.shape[0]",
"action | No reparameterization else: a = self.learn_env.action_space.sample() o_next, r, d, _ =",
"= True if el == max_el else d # Ignore artificial termination self.buffer.store_transition(o,",
"_build(self): self._set_env() self._set_buffer() def _set_env(self): name = self.configs['environment']['name'] evaluate = self.configs['algorithm']['evaluation'] # Inintialize",
"el, t = self.learn_env.reset(), 0, 0, 0 if Ni < 1: return o,",
"# env = gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10)) # env.seed(seed) # env.action_space.seed(seed)",
"False if el == max_el else d # Ignore artificial termination self.buffer.store_transition(o, a,",
"o, d, Z, S, el = self.eval_env.reset(), False, 0, 0, 0 while not(d",
"print('log_pi: ', log_pi) o_next, r, d, _ = self.learn_env.step(a) Z += r el",
"Model-Free Reinforcement Learning \"\"\" def __init__(self, exp_prefix, configs, seed, device): # super(MFRL, self).__init__(configs,",
"0, 0, 0 while not(d or (el == max_el)): # Take deterministic actions",
"< 1: return o, Z, el, t print(f'[ Initial exploaration ] Starting') for",
"Nx: a = self.actor_critic.get_action_np(o) # Stochastic action | No reparameterization # Deterministic action",
"= gym.make(env_id) # env = gym.wrappers.RecordEpisodeStatistics(env) # if capture_video: # if idx ==",
"[] # Evaluation episodic return ES = [] # Evaluation episodic score EL",
"a = self.actor_critic.get_action_np(o, deterministic=True) # Deterministic action | No reparameterization o, r, d,",
"== 'mujoco-pddm-shadowhand': # for i in range(len(ES)): # ES[i] /= EL[i] return EZ,",
"self.configs['algorithm']['on-policy']: # num_traj = 40 horizon = 1000 max_size = self.configs['data']['batch_size'] self.buffer =",
"t={t} | el={el} | total_size={self.buffer.total_size()}') o, Z, el = self.learn_env.reset(), 0, 0 return",
"episodic return ES = [] # Evaluation episodic score EL = [] #",
"Z += r el +=1 t +=1 if d or (el == max_el):",
"log_pi) o_next, r, d, _ = self.learn_env.step(a) Z += r el += 1",
"configs, seed, device): # super(MFRL, self).__init__(configs, seed) # print('init MBRL!') self.exp_prefix = exp_prefix",
"def _build(self): self._set_env() self._set_buffer() def _set_env(self): name = self.configs['environment']['name'] evaluate = self.configs['algorithm']['evaluation'] #",
"print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o, Z, el = self.learn_env.reset(), 0, 0",
"device = self._device_ if self.configs['algorithm']['on-policy']: max_size = self.configs['data']['batch_size'] num_traj = max_size//20 horizon =",
"d, v, log_pi, el) if d_next or (el == max_el): # o_next, Z,",
"self.actor_critic.get_action_np(o, deterministic=True) # Deterministic action | No reparameterization o, r, d, info =",
"info['score'] el += 1 EZ.append(Z) if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el) # if",
"print('log_pi: ', log_pi) o_next, r, d_next, _ = self.learn_env.step(a) Z += r el",
"obs: np.clip(obs, -10, 10)) # env = gym.wrappers.NormalizeReward(env) # env = gym.wrappers.TransformReward(env, lambda",
"EZ.append(Z) if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el) # if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': #",
"np.clip(obs, -10, 10)) # env = gym.wrappers.NormalizeReward(env) # env = gym.wrappers.TransformReward(env, lambda reward:",
"max_el): if el == max_el: with T.no_grad(): v = self.actor_critic.get_v(T.Tensor(o)).cpu() else: # print('v=0')",
"self.configs['environment']['horizon'] # a = self.actor_critic.get_action_np(o) with T.no_grad(): a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) #",
"a = self.learn_env.action_space.sample() o_next, r, d, _ = self.learn_env.step(a) d = False if",
"d, Z, S, el = self.eval_env.reset(), False, 0, 0, 0 while not(d or",
"# print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o, Z, el = self.learn_env.reset(), 0,",
"self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) else: self.buffer = ReplayBuffer(self.obs_dim,",
"if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': S += info['score'] el += 1 EZ.append(Z) if self.configs['environment']['type']",
"False, 0, 0, 0 while not(d or (el == max_el)): # Take deterministic",
"# def make_env(env_id, seed, idx, capture_video, run_name): # def thunk(): # print('in thunk')",
"capture_video: # if idx == 0: # env = gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") # env",
"max_el else d # Ignore artificial termination self.buffer.store_transition(o, a, r, o_next, d) o",
"# if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': # for i in range(len(ES)): # ES[i] /=",
"o, d = o_next, d_next return o, d, Z, el, t def internact_opB(self,",
"evaluate: print('[ Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el = self.configs['environment']['horizon'] EZ = []",
"self.exp_prefix = exp_prefix self.configs = configs self.seed = seed self._device_ = device def",
"Ignore artificial termination self.buffer.store_transition(o, a, r, o_next, d) o = o_next Z +=",
"o_next, Z, el = self.learn_env.reset(), 0, 0 with T.no_grad(): v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next,",
"for ee in range(1, EE+1): print(f' [ Agent Evaluation ] Episode: {ee} ',",
"env = gym.make(env_id) # env = gym.wrappers.RecordEpisodeStatistics(env) # if capture_video: # if idx",
"device): # super(MFRL, self).__init__(configs, seed) # print('init MBRL!') self.exp_prefix = exp_prefix self.configs =",
"if n > Nx: a = self.actor_critic.get_action_np(o) # Stochastic action | No reparameterization",
"t): Nx = self.configs['algorithm']['learning']['expl_epochs'] max_el = self.configs['environment']['horizon'] if n > Nx: a =",
"1: return o, Z, el, t print(f'[ Initial exploaration ] Starting') for ni",
"1 t += 1 self.buffer.store_transition(o, a, r, d, v, log_pi, el) if d_next",
"import TrajBuffer, ReplayBuffer # from rl.data.buffer import TrajBuffer, ReplayBufferNP # def make_env(env_id, seed,",
"episodic score EL = [] # Evaluation episodic length for ee in range(1,",
"self.act_dim, horizon, num_traj, max_size, self.seed, device) def initialize_learning(self, NT, Ni): max_el = self.configs['environment']['horizon']",
"Z += r if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': S += info['score'] el += 1",
"numpy as np import torch as T import rl.environments from rl.data.buffer import TrajBuffer,",
"self._device_ if self.configs['algorithm']['on-policy']: max_size = self.configs['data']['batch_size'] num_traj = max_size//20 horizon = 1000 self.buffer",
"def evaluate(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes']",
"thunk(): # print('in thunk') # env = gym.make(env_id) # env = gym.wrappers.RecordEpisodeStatistics(env) #",
"el, t def internact_op(self, n, o, d, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps']",
"in range(1, EE+1): print(f' [ Agent Evaluation ] Episode: {ee} ', end='\\r') o,",
"self.learn_env.reset(), 0, 0 nt += 1 return o, Z, el, t def internact_op(self,",
"el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] # a = self.actor_critic.get_action_np(o) with",
"+= 1 self.buffer.store(o, a, r, o_next, v, log_pi, el) o = o_next if",
"if el == max_el else d # Ignore artificial termination self.buffer.store_transition(o, a, r,",
"Z, el = self.learn_env.reset(), 0, 0 return o, Z, el, t def evaluate_op(self):",
"gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") # env = gym.wrappers.ClipAction(env) # env = gym.wrappers.NormalizeObservation(env) # env =",
"gym.wrappers.RecordEpisodeStatistics(env) # if capture_video: # if idx == 0: # env = gym.wrappers.RecordVideo(env,",
"= self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d, _ = self.learn_env.step(a) Z",
"else: self.buffer = ReplayBuffer(self.obs_dim, self.act_dim, max_size, self.seed, device) def initialize_buffer(self, num_traj=400): # print('Initialize",
"max_size, self.seed, device) def initialize_buffer(self, num_traj=400): # print('Initialize a New Buffer..') seed =",
"Epoch {ni}') nt = 0 while nt < NT: # Random actions a",
"Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el = self.configs['environment']['horizon'] EZ = [] # Evaluation",
"T.no_grad(): a, _, _ = self.actor_critic.get_pi(T.Tensor(o)) a = self.actor_critic.get_action_np(o, deterministic=True) # a =",
"env # # return thunk class MFRL: \"\"\" Model-Free Reinforcement Learning \"\"\" def",
"def _set_buffer(self): max_size = self.configs['data']['buffer_size'] device = self._device_ if self.configs['algorithm']['on-policy']: max_size = self.configs['data']['batch_size']",
"= self.learn_env.reset(), 0, 0 return o, Z, el, t def internact(self, n, o,",
"# print('log_pi: ', log_pi) o_next, r, d, _ = self.learn_env.step(a) Z += r",
"ES = [] # Evaluation episodic score EL = [] # Evaluation episodic",
"self.seed = seed self._device_ = device def _build(self): self._set_env() self._set_buffer() def _set_env(self): name",
"not(d or (el == max_el)): # Take deterministic actions at evaluation time a",
"# Deterministic action | No reparameterization else: a = self.learn_env.action_space.sample() o_next, r, d,",
"gym.spaces import Box import numpy as np import torch as T import rl.environments",
"self.buffer = ReplayBuffer(self.obs_dim, self.act_dim, max_size, self.seed, device) def initialize_buffer(self, num_traj=400): # print('Initialize a",
"o_next, r, d_next, _ = self.learn_env.step(a) Z += r el += 1 t",
"self.learn_env.reset(), 0, 0, 0 if Ni < 1: return o, Z, el, t",
"return thunk class MFRL: \"\"\" Model-Free Reinforcement Learning \"\"\" def __init__(self, exp_prefix, configs,",
"n, o, Z, el, t): Nx = self.configs['algorithm']['learning']['expl_epochs'] max_el = self.configs['environment']['horizon'] if n",
"f\"videos/{run_name}\") # env = gym.wrappers.ClipAction(env) # env = gym.wrappers.NormalizeObservation(env) # env = gym.wrappers.TransformObservation(env,",
"= self.configs['data']['buffer_size'] device = self._device_ if self.configs['algorithm']['on-policy']: max_size = self.configs['data']['batch_size'] num_traj = max_size//20",
"1 t += 1 self.buffer.store(o, a, r, o_next, v, log_pi, el) o =",
"v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d_next, _ = self.learn_env.step(a)",
"= o_next Z += r el +=1 t +=1 if d or (el",
"def _seed_env(self, env): env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def _set_buffer(self): max_size = self.configs['data']['buffer_size'] device =",
"/= EL[i] return EZ, ES, EL def evaluate(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate:",
"self.eval_env = gym.make(name) self._seed_env(self.eval_env) else: self.eval_env = None # Spaces dimensions self.obs_dim =",
"evaluate(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el",
"actions at evaluation time a = self.actor_critic.get_action_np(o, deterministic=True) # Deterministic action | No",
"lambda obs: np.clip(obs, -10, 10)) # env = gym.wrappers.NormalizeReward(env) # env = gym.wrappers.TransformReward(env,",
"env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10)) # env = gym.wrappers.NormalizeReward(env) #",
"_set_buffer(self): max_size = self.configs['data']['buffer_size'] device = self._device_ if self.configs['algorithm']['on-policy']: max_size = self.configs['data']['batch_size'] num_traj",
"log_pi, el) if d_next or (el == max_el): # o_next, Z, el =",
"T.no_grad(): a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d_next,",
"= self.learn_env.step(a) d = True if el == max_el else d # Ignore",
"', log_pi) o_next, r, d_next, _ = self.learn_env.step(a) Z += r el +=",
"| total_size={self.buffer.total_size()}') o, Z, el = self.learn_env.reset(), 0, 0 return o, Z, el,",
"| el={el} | total_size={self.buffer.total_size()}') o, Z, el = self.learn_env.reset(), 0, 0 return o,",
"= self.learn_env.observation_space.shape[0] self.act_dim = self.learn_env.action_space.shape[0] self.act_up_lim = self.learn_env.action_space.high self.act_low_lim = self.learn_env.action_space.low def _seed_env(self,",
"o, Z, el, t print(f'[ Initial exploaration ] Starting') for ni in range(1,",
"= self.learn_env.reset(), 0, 0, 0 o, d = o_next, d_next return o, d,",
"o, Z, el, t def internact(self, n, o, Z, el, t): Nx =",
"deterministic=True) # Deterministic action | No reparameterization o, r, d, info = self.eval_env.step(a)",
"n > Nx: a = self.actor_critic.get_action_np(o) # Stochastic action | No reparameterization #",
"Buffer..') seed = self.seed device = self._device_ if self.configs['algorithm']['on-policy']: # num_traj = 40",
"# Evaluation episodic score EL = [] # Evaluation episodic length for ee",
"d_next, Z, el = self.learn_env.reset(), 0, 0, 0 o, d = o_next, d_next",
"Z, el, t print(f'[ Initial exploaration ] Starting') for ni in range(1, Ni+1):",
"0 nt += 1 return o, Z, el, t def internact_op(self, n, o,",
"Initial exploaration ] Starting') for ni in range(1, Ni+1): print(f'[ Initial exploaration ]",
"= self.configs['environment']['horizon'] if n > Nx: a = self.actor_critic.get_action_np(o) # Stochastic action |",
"# env = gym.wrappers.NormalizeReward(env) # env = gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10))",
"d, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] # a =",
"def thunk(): # print('in thunk') # env = gym.make(env_id) # env = gym.wrappers.RecordEpisodeStatistics(env)",
"o, r, d, info = self.eval_env.step(a) Z += r if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand':",
"# for i in range(len(ES)): # ES[i] /= EL[i] return EZ, ES, EL",
"= self.actor_critic.get_action_np(o, deterministic=True) o, r, d, info = self.eval_env.step(a) Z += r if",
"a = self.actor_critic.get_action_np(o, deterministic=True) o, r, d, info = self.eval_env.step(a) Z += r",
"return o, Z, el, t def internact_op(self, n, o, d, Z, el, t):",
"T.no_grad(): a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d,",
"= gym.wrappers.ClipAction(env) # env = gym.wrappers.NormalizeObservation(env) # env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs,",
"Deterministic action | No reparameterization o, r, d, info = self.eval_env.step(a) Z +=",
"reparameterization o, r, d, info = self.eval_env.step(a) Z += r if self.configs['environment']['type'] ==",
"# Inintialize Learning environment self.learn_env = gym.make(name) self._seed_env(self.learn_env) assert isinstance (self.learn_env.action_space, Box), \"Works",
"name = self.configs['environment']['name'] evaluate = self.configs['algorithm']['evaluation'] # Inintialize Learning environment self.learn_env = gym.make(name)",
"= gym.wrappers.RecordEpisodeStatistics(env) # if capture_video: # if idx == 0: # env =",
"# env.action_space.seed(seed) # env.observation_space.seed(seed) # return env # # return thunk class MFRL:",
"Ni+1): print(f'[ Initial exploaration ] Epoch {ni}') nt = 0 while nt <",
"0 while not(d or (el == max_el)): # with T.no_grad(): a, _, _",
"Evaluation episodic length for ee in range(1, EE+1): print(f' [ Agent Evaluation ]",
"o_next, r, d, _ = self.learn_env.step(a) d = False if el == max_el",
"action | No reparameterization o, r, d, info = self.eval_env.step(a) Z += r",
"el = self.learn_env.reset(), 0, 0, 0 o, d = o_next, d_next return o,",
"env.action_space.seed(seed) # env.observation_space.seed(seed) # return env # # return thunk class MFRL: \"\"\"",
"EL[i] return EZ, ES, EL def evaluate(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[",
"r, o_next, v, log_pi, el) o = o_next if d or (el ==",
"EL = [] # Evaluation episodic length for ee in range(1, EE+1): print(f'",
"self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d, _ = self.learn_env.step(a) Z +=",
"self.seed device = self._device_ if self.configs['algorithm']['on-policy']: # num_traj = 40 horizon = 1000",
"| No reparameterization else: a = self.learn_env.action_space.sample() o_next, r, d, _ = self.learn_env.step(a)",
"\"Works only with continuous action space\" if evaluate: # Ininialize Evaluation environment self.eval_env",
"EE+1): print(f' [ Agent Evaluation ] Episode: {ee} ', end='\\r') o, d, Z,",
"Take deterministic actions at evaluation time a = self.actor_critic.get_action_np(o, deterministic=True) # Deterministic action",
"= gym.wrappers.NormalizeObservation(env) # env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10)) # env",
"gym.wrappers.NormalizeReward(env) # env = gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10)) # env.seed(seed) #",
"< NT: # Random actions a = self.learn_env.action_space.sample() o_next, r, d, info =",
"0 o, d = o_next, d_next return o, d, Z, el, t def",
"nt = 0 while nt < NT: # Random actions a = self.learn_env.action_space.sample()",
"o, Z, el, t): Nx = self.configs['algorithm']['learning']['expl_epochs'] max_el = self.configs['environment']['horizon'] if n >",
"+= 1 t += 1 self.buffer.store(o, a, r, o_next, v, log_pi, el) o",
"Z, el, t def internact_op(self, n, o, d, Z, el, t): Nt =",
"device) def initialize_buffer(self, num_traj=400): # print('Initialize a New Buffer..') seed = self.seed device",
"# return thunk class MFRL: \"\"\" Model-Free Reinforcement Learning \"\"\" def __init__(self, exp_prefix,",
"Evaluation environment self.eval_env = gym.make(name) self._seed_env(self.eval_env) else: self.eval_env = None # Spaces dimensions",
"self.buffer.store_transition(o, a, r, d, v, log_pi, el) if d_next or (el == max_el):",
"self.actor_critic.get_pi(T.Tensor(o)) a = self.actor_critic.get_action_np(o, deterministic=True) # a = self.actor_critic.get_action_np(o, deterministic=True) o, r, d,",
"a = self.actor_critic.get_action_np(o) # Stochastic action | No reparameterization # Deterministic action |",
"self.learn_env.reset(), 0, 0 return o, Z, el, t def evaluate_op(self): evaluate = self.configs['algorithm']['evaluation']",
"_ = self.actor_critic.get_pi(T.Tensor(o)) a = self.actor_critic.get_action_np(o, deterministic=True) # a = self.actor_critic.get_action_np(o, deterministic=True) o,",
"max_size, self.seed, device) def initialize_learning(self, NT, Ni): max_el = self.configs['environment']['horizon'] o, Z, el,",
"+= r el += 1 t += 1 self.buffer.store_transition(o, a, r, d, v,",
"0, 0 return o, Z, el, t def internact(self, n, o, Z, el,",
"| total_size={self.buffer.total_size()}') o_next, d_next, Z, el = self.learn_env.reset(), 0, 0, 0 o, d",
"+= 1 t += 1 self.buffer.store_transition(o, a, r, d, v, log_pi, el) if",
"d = True if el == max_el else d # Ignore artificial termination",
"Evaluation ] Episode: {ee} ', end='\\r') o, d, Z, S, el = self.eval_env.reset(),",
"else: # print('v=0') v = T.Tensor([0.0]) self.buffer.finish_path(el, v) # print(f'termination: t={t} | el={el}",
"# from rl.data.buffer import TrajBuffer, ReplayBufferNP # def make_env(env_id, seed, idx, capture_video, run_name):",
"horizon, num_traj, max_size, self.seed, device) def initialize_learning(self, NT, Ni): max_el = self.configs['environment']['horizon'] o,",
"self.configs['algorithm']['learning']['expl_epochs'] max_el = self.configs['environment']['horizon'] if n > Nx: a = self.actor_critic.get_action_np(o) # Stochastic",
"= self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d_next, _ = self.learn_env.step(a) Z",
"el, t): Nx = self.configs['algorithm']['learning']['expl_epochs'] max_el = self.configs['environment']['horizon'] if n > Nx: a",
"Reinforcement Learning \"\"\" def __init__(self, exp_prefix, configs, seed, device): # super(MFRL, self).__init__(configs, seed)",
"def internact_opB(self, n, o, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon']",
"el={el} | total_size={self.buffer.total_size()}') o_next, d_next, Z, el = self.learn_env.reset(), 0, 0, 0 o,",
"] Starting') for ni in range(1, Ni+1): print(f'[ Initial exploaration ] Epoch {ni}')",
"actions a = self.learn_env.action_space.sample() o_next, r, d, info = self.learn_env.step(a) d = True",
"log_pi) o_next, r, d_next, _ = self.learn_env.step(a) Z += r el += 1",
"False, 0, 0, 0 while not(d or (el == max_el)): # with T.no_grad():",
"== 'mujoco-pddm-shadowhand': S += info['score'] el += 1 EZ.append(Z) if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand':",
"thunk class MFRL: \"\"\" Model-Free Reinforcement Learning \"\"\" def __init__(self, exp_prefix, configs, seed,",
"# env = gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") # env = gym.wrappers.ClipAction(env) # env = gym.wrappers.NormalizeObservation(env)",
"else: a = self.learn_env.action_space.sample() o_next, r, d, _ = self.learn_env.step(a) d = False",
"Evaluation episodic score EL = [] # Evaluation episodic length for ee in",
"v, log_pi, el) o = o_next if d or (el == max_el): if",
"0 if Ni < 1: return o, Z, el, t print(f'[ Initial exploaration",
"self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) def initialize_learning(self, NT, Ni):",
"assert isinstance (self.learn_env.action_space, Box), \"Works only with continuous action space\" if evaluate: #",
"v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next, el) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}')",
"self.buffer.finish_path(el, v) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o, Z, el =",
"internact(self, n, o, Z, el, t): Nx = self.configs['algorithm']['learning']['expl_epochs'] max_el = self.configs['environment']['horizon'] if",
"# o_next, Z, el = self.learn_env.reset(), 0, 0 with T.no_grad(): v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu()",
"self._device_ if self.configs['algorithm']['on-policy']: # num_traj = 40 horizon = 1000 max_size = self.configs['data']['batch_size']",
"= T.Tensor([0.0]) self.buffer.finish_path(el, v) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o, Z,",
"num_traj = 40 horizon = 1000 max_size = self.configs['data']['batch_size'] self.buffer = TrajBuffer(self.obs_dim, self.act_dim,",
"v) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o, Z, el = self.learn_env.reset(),",
"self._set_buffer() def _set_env(self): name = self.configs['environment']['name'] evaluate = self.configs['algorithm']['evaluation'] # Inintialize Learning environment",
"a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d_next, _",
"env = gym.wrappers.RecordEpisodeStatistics(env) # if capture_video: # if idx == 0: # env",
"= self.configs['environment']['horizon'] o, Z, el, t = self.learn_env.reset(), 0, 0, 0 if Ni",
"0, 0 if Ni < 1: return o, Z, el, t print(f'[ Initial",
"action space\" if evaluate: # Ininialize Evaluation environment self.eval_env = gym.make(name) self._seed_env(self.eval_env) else:",
"# if idx == 0: # env = gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") # env =",
"o_next, v, log_pi, el) o = o_next if d or (el == max_el):",
"0, 0 return o, Z, el, t def evaluate_op(self): evaluate = self.configs['algorithm']['evaluation'] if",
"time a = self.actor_critic.get_action_np(o, deterministic=True) # Deterministic action | No reparameterization o, r,",
"d, _ = self.learn_env.step(a) Z += r el += 1 t += 1",
"o = o_next if d or (el == max_el): if el == max_el:",
"= [] # Evaluation episodic length for ee in range(1, EE+1): print(f' [",
"exp_prefix self.configs = configs self.seed = seed self._device_ = device def _build(self): self._set_env()",
"max_size = self.configs['data']['batch_size'] self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) def",
"= self.configs['environment']['horizon'] # a = self.actor_critic.get_action_np(o) with T.no_grad(): a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o))",
"ES, EL def evaluate(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE",
"self.act_dim = self.learn_env.action_space.shape[0] self.act_up_lim = self.learn_env.action_space.high self.act_low_lim = self.learn_env.action_space.low def _seed_env(self, env): env.seed(self.seed)",
"initialize_buffer(self, num_traj=400): # print('Initialize a New Buffer..') seed = self.seed device = self._device_",
"Ni < 1: return o, Z, el, t print(f'[ Initial exploaration ] Starting')",
"d, info = self.learn_env.step(a) d = True if el == max_el else d",
"== 0: # env = gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") # env = gym.wrappers.ClipAction(env) # env",
"ni in range(1, Ni+1): print(f'[ Initial exploaration ] Epoch {ni}') nt = 0",
"= o_next, d_next return o, d, Z, el, t def internact_opB(self, n, o,",
"configs self.seed = seed self._device_ = device def _build(self): self._set_env() self._set_buffer() def _set_env(self):",
"# Random actions a = self.learn_env.action_space.sample() o_next, r, d, info = self.learn_env.step(a) d",
"S += info['score'] el += 1 EZ.append(Z) if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el)",
"d = o_next, d_next return o, d, Z, el, t def internact_opB(self, n,",
"== max_el): o, Z, el = self.learn_env.reset(), 0, 0 return o, Z, el,",
"a = self.learn_env.action_space.sample() o_next, r, d, info = self.learn_env.step(a) d = True if",
"for i in range(len(ES)): # ES[i] /= EL[i] return EZ, ES, EL def",
"self.learn_env.action_space.sample() o_next, r, d, info = self.learn_env.step(a) d = True if el ==",
"Z, el, t def evaluate_op(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]')",
"T.Tensor([0.0]) self.buffer.finish_path(el, v) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o, Z, el",
"thunk') # env = gym.make(env_id) # env = gym.wrappers.RecordEpisodeStatistics(env) # if capture_video: #",
"= self.actor_critic.get_action_np(o, deterministic=True) # a = self.actor_critic.get_action_np(o, deterministic=True) o, r, d, info =",
"print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o_next, d_next, Z, el = self.learn_env.reset(), 0,",
"d, _ = self.learn_env.step(a) d = False if el == max_el else d",
"o_next, d_next, Z, el = self.learn_env.reset(), 0, 0, 0 o, d = o_next,",
"= self.actor_critic.get_action_np(o, deterministic=True) # Deterministic action | No reparameterization o, r, d, info",
"i in range(len(ES)): # ES[i] /= EL[i] return EZ, ES, EL def evaluate(self):",
"def initialize_buffer(self, num_traj=400): # print('Initialize a New Buffer..') seed = self.seed device =",
"== max_el else d # Ignore artificial termination self.buffer.store_transition(o, a, r, o_next, d)",
"artificial termination self.buffer.store_transition(o, a, r, o_next, d) o = o_next Z += r",
"info = self.learn_env.step(a) d = True if el == max_el else d #",
"t print(f'[ Initial exploaration ] Starting') for ni in range(1, Ni+1): print(f'[ Initial",
"with T.no_grad(): a, log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r,",
"env.observation_space.seed(self.seed) def _set_buffer(self): max_size = self.configs['data']['buffer_size'] device = self._device_ if self.configs['algorithm']['on-policy']: max_size =",
"# Ignore artificial termination self.buffer.store_transition(o, a, r, o_next, d) o = o_next Z",
"= self.learn_env.reset(), 0, 0 nt += 1 return o, Z, el, t def",
"total_size={self.buffer.total_size()}') o_next, d_next, Z, el = self.learn_env.reset(), 0, 0, 0 o, d =",
"0, 0, 0 while not(d or (el == max_el)): # with T.no_grad(): a,",
"r, d, v, log_pi, el) if d_next or (el == max_el): # o_next,",
"t={t} | el={el} | total_size={self.buffer.total_size()}') o_next, d_next, Z, el = self.learn_env.reset(), 0, 0,",
"# env = gym.wrappers.NormalizeObservation(env) # env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10))",
"env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def _set_buffer(self): max_size = self.configs['data']['buffer_size'] device = self._device_ if self.configs['algorithm']['on-policy']:",
"| No reparameterization o, r, d, info = self.eval_env.step(a) Z += r if",
"Z, el, t def internact_opB(self, n, o, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps']",
"(el == max_el): o, Z, el = self.learn_env.reset(), 0, 0 return o, Z,",
"1000 self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device) else: self.buffer =",
"{ni}') nt = 0 while nt < NT: # Random actions a =",
"T.no_grad(): v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next, el) # print(f'termination: t={t} | el={el} |",
"= self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next, el) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o_next,",
"t def evaluate_op(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE =",
"r, d, info = self.eval_env.step(a) Z += r if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': S",
"self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d_next, _ = self.learn_env.step(a) Z +=",
"v_next, el) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o_next, d_next, Z, el",
"max_el = self.configs['environment']['horizon'] o, Z, el, t = self.learn_env.reset(), 0, 0, 0 if",
"0 return o, Z, el, t def internact(self, n, o, Z, el, t):",
"= ReplayBuffer(self.obs_dim, self.act_dim, max_size, self.seed, device) def initialize_buffer(self, num_traj=400): # print('Initialize a New",
"internact_opB(self, n, o, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] #",
"with T.no_grad(): v = self.actor_critic.get_v(T.Tensor(o)).cpu() else: # print('v=0') v = T.Tensor([0.0]) self.buffer.finish_path(el, v)",
"d or (el == max_el): o, Z, el = self.learn_env.reset(), 0, 0 nt",
"', end='\\r') o, d, Z, S, el = self.eval_env.reset(), False, 0, 0, 0",
"num_traj, max_size, self.seed, device) else: self.buffer = ReplayBuffer(self.obs_dim, self.act_dim, max_size, self.seed, device) def",
"| el={el} | total_size={self.buffer.total_size()}') o_next, d_next, Z, el = self.learn_env.reset(), 0, 0, 0",
"-10, 10)) # env.seed(seed) # env.action_space.seed(seed) # env.observation_space.seed(seed) # return env # #",
"Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] # a = self.actor_critic.get_action_np(o) with T.no_grad(): a,",
"from rl.data.buffer import TrajBuffer, ReplayBufferNP # def make_env(env_id, seed, idx, capture_video, run_name): #",
"No reparameterization # Deterministic action | No reparameterization else: a = self.learn_env.action_space.sample() o_next,",
"NT, Ni): max_el = self.configs['environment']['horizon'] o, Z, el, t = self.learn_env.reset(), 0, 0,",
"self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': # for i in range(len(ES)): # ES[i] /= EL[i] return",
"\"\"\" def __init__(self, exp_prefix, configs, seed, device): # super(MFRL, self).__init__(configs, seed) # print('init",
"max_el): # o_next, Z, el = self.learn_env.reset(), 0, 0 with T.no_grad(): v_next =",
"n, o, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] # a",
"self.learn_env.action_space.high self.act_low_lim = self.learn_env.action_space.low def _seed_env(self, env): env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def _set_buffer(self): max_size",
"not(d or (el == max_el)): # with T.no_grad(): a, _, _ = self.actor_critic.get_pi(T.Tensor(o))",
"o_next, d) o = o_next Z += r el +=1 t +=1 if",
"self.learn_env.reset(), 0, 0, 0 o, d = o_next, d_next return o, d, Z,",
"a = self.actor_critic.get_action_np(o, deterministic=True) # a = self.actor_critic.get_action_np(o, deterministic=True) o, r, d, info",
"self.act_low_lim = self.learn_env.action_space.low def _seed_env(self, env): env.seed(self.seed) env.action_space.seed(self.seed) env.observation_space.seed(self.seed) def _set_buffer(self): max_size =",
"with T.no_grad(): v_next = self.actor_critic.get_v(T.Tensor(o_next)).cpu() self.buffer.traj_tail(d_next, v_next, el) # print(f'termination: t={t} | el={el}",
"self.buffer.traj_tail(d_next, v_next, el) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o_next, d_next, Z,",
"TrajBuffer, ReplayBufferNP # def make_env(env_id, seed, idx, capture_video, run_name): # def thunk(): #",
"or (el == max_el)): # with T.no_grad(): a, _, _ = self.actor_critic.get_pi(T.Tensor(o)) a",
"# print('init MBRL!') self.exp_prefix = exp_prefix self.configs = configs self.seed = seed self._device_",
"_ = self.learn_env.step(a) Z += r el += 1 t += 1 self.buffer.store_transition(o,",
"o, Z, el = self.learn_env.reset(), 0, 0 return o, Z, el, t def",
"+= 1 EZ.append(Z) if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el) # if self.configs['environment']['type'] ==",
"a, r, o_next, v, log_pi, el) o = o_next if d or (el",
"r, d_next, _ = self.learn_env.step(a) Z += r el += 1 t +=",
"10)) # env.seed(seed) # env.action_space.seed(seed) # env.observation_space.seed(seed) # return env # # return",
"or (el == max_el)): # Take deterministic actions at evaluation time a =",
"0 return o, Z, el, t def evaluate_op(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate:",
"reward: np.clip(reward, -10, 10)) # env.seed(seed) # env.action_space.seed(seed) # env.observation_space.seed(seed) # return env",
"super(MFRL, self).__init__(configs, seed) # print('init MBRL!') self.exp_prefix = exp_prefix self.configs = configs self.seed",
"t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] # a = self.actor_critic.get_action_np(o) with T.no_grad():",
"r, o_next, d) o = o_next Z += r el +=1 t +=1",
"= configs self.seed = seed self._device_ = device def _build(self): self._set_env() self._set_buffer() def",
"el, t def evaluate_op(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE",
"self.learn_env.observation_space.shape[0] self.act_dim = self.learn_env.action_space.shape[0] self.act_up_lim = self.learn_env.action_space.high self.act_low_lim = self.learn_env.action_space.low def _seed_env(self, env):",
"r, d, _ = self.learn_env.step(a) d = False if el == max_el else",
"if self.configs['algorithm']['on-policy']: max_size = self.configs['data']['batch_size'] num_traj = max_size//20 horizon = 1000 self.buffer =",
"max_el): o, Z, el = self.learn_env.reset(), 0, 0 nt += 1 return o,",
"== max_el: with T.no_grad(): v = self.actor_critic.get_v(T.Tensor(o)).cpu() else: # print('v=0') v = T.Tensor([0.0])",
"self.act_dim, horizon, num_traj, max_size, self.seed, device) else: self.buffer = ReplayBuffer(self.obs_dim, self.act_dim, max_size, self.seed,",
"evaluate_op(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el",
"Initial exploaration ] Epoch {ni}') nt = 0 while nt < NT: #",
"1 EZ.append(Z) if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el) # if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand':",
"def evaluate_op(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE = self.configs['algorithm']['evaluation']['eval_episodes']",
"= self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] # a = self.actor_critic.get_action_np(o) with T.no_grad(): a, log_pi,",
"seed self._device_ = device def _build(self): self._set_env() self._set_buffer() def _set_env(self): name = self.configs['environment']['name']",
"termination self.buffer.store_transition(o, a, r, o_next, d) o = o_next Z += r el",
"print('v=0') v = T.Tensor([0.0]) self.buffer.finish_path(el, v) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}')",
"t +=1 if d or (el == max_el): o, Z, el = self.learn_env.reset(),",
"ReplayBufferNP # def make_env(env_id, seed, idx, capture_video, run_name): # def thunk(): # print('in",
"v = T.Tensor([0.0]) self.buffer.finish_path(el, v) # print(f'termination: t={t} | el={el} | total_size={self.buffer.total_size()}') o,",
"return EZ, ES, EL def evaluate(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation",
"self.buffer.store_transition(o, a, r, o_next, d) o = o_next Z += r el +=1",
"+= 1 return o, Z, el, t def internact_op(self, n, o, d, Z,",
"if self.configs['algorithm']['on-policy']: # num_traj = 40 horizon = 1000 max_size = self.configs['data']['batch_size'] self.buffer",
"info = self.eval_env.step(a) Z += r if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': S += info['score']",
"# env = gym.wrappers.RecordEpisodeStatistics(env) # if capture_video: # if idx == 0: #",
"deterministic=True) o, r, d, info = self.eval_env.step(a) Z += r if self.configs['environment']['type'] ==",
"Learning \"\"\" def __init__(self, exp_prefix, configs, seed, device): # super(MFRL, self).__init__(configs, seed) #",
"self.configs['environment']['horizon'] EZ = [] # Evaluation episodic return ES = [] # Evaluation",
"== max_el): o, Z, el = self.learn_env.reset(), 0, 0 nt += 1 return",
"if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': # for i in range(len(ES)): # ES[i] /= EL[i]",
"Stochastic action | No reparameterization # Deterministic action | No reparameterization else: a",
"[] # Evaluation episodic length for ee in range(1, EE+1): print(f' [ Agent",
"reparameterization else: a = self.learn_env.action_space.sample() o_next, r, d, _ = self.learn_env.step(a) d =",
"self).__init__(configs, seed) # print('init MBRL!') self.exp_prefix = exp_prefix self.configs = configs self.seed =",
"import rl.environments from rl.data.buffer import TrajBuffer, ReplayBuffer # from rl.data.buffer import TrajBuffer, ReplayBufferNP",
"+=1 if d or (el == max_el): o, Z, el = self.learn_env.reset(), 0,",
"Box import numpy as np import torch as T import rl.environments from rl.data.buffer",
"= self.learn_env.reset(), 0, 0 return o, Z, el, t def evaluate_op(self): evaluate =",
"v = self.actor_critic.get_v(T.Tensor(o)).cpu() else: # print('v=0') v = T.Tensor([0.0]) self.buffer.finish_path(el, v) # print(f'termination:",
"evaluation time a = self.actor_critic.get_action_np(o, deterministic=True) # Deterministic action | No reparameterization o,",
"EZ = [] # Evaluation episodic return ES = [] # Evaluation episodic",
"o_next, d_next return o, d, Z, el, t def internact_opB(self, n, o, Z,",
"= self.actor_critic.get_action_np(o) # Stochastic action | No reparameterization # Deterministic action | No",
"= 1000 max_size = self.configs['data']['batch_size'] self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed,",
"log_pi, v = self.actor_critic.get_a_and_v_np(T.Tensor(o)) # print('log_pi: ', log_pi) o_next, r, d, _ =",
"== 'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el) # if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': # for i in",
"+= info['score'] el += 1 EZ.append(Z) if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': ES.append(S/el) EL.append(el) #",
"ee in range(1, EE+1): print(f' [ Agent Evaluation ] Episode: {ee} ', end='\\r')",
"deterministic actions at evaluation time a = self.actor_critic.get_action_np(o, deterministic=True) # Deterministic action |",
"[] # Evaluation episodic score EL = [] # Evaluation episodic length for",
"== max_el): # o_next, Z, el = self.learn_env.reset(), 0, 0 with T.no_grad(): v_next",
"+=1 t +=1 if d or (el == max_el): o, Z, el =",
"o_next, r, d, _ = self.learn_env.step(a) Z += r el += 1 t",
"device def _build(self): self._set_env() self._set_buffer() def _set_env(self): name = self.configs['environment']['name'] evaluate = self.configs['algorithm']['evaluation']",
"self.configs['algorithm']['evaluation'] # Inintialize Learning environment self.learn_env = gym.make(name) self._seed_env(self.learn_env) assert isinstance (self.learn_env.action_space, Box),",
"n, o, d, Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] #",
"env = gym.wrappers.ClipAction(env) # env = gym.wrappers.NormalizeObservation(env) # env = gym.wrappers.TransformObservation(env, lambda obs:",
"in range(len(ES)): # ES[i] /= EL[i] return EZ, ES, EL def evaluate(self): evaluate",
"= gym.wrappers.NormalizeReward(env) # env = gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10)) # env.seed(seed)",
"1 return o, Z, el, t def internact_op(self, n, o, d, Z, el,",
"# Stochastic action | No reparameterization # Deterministic action | No reparameterization else:",
"env = gym.wrappers.NormalizeObservation(env) # env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10)) #",
"max_el)): # Take deterministic actions at evaluation time a = self.actor_critic.get_action_np(o, deterministic=True) #",
"a, r, d, v, log_pi, el) if d_next or (el == max_el): #",
"def __init__(self, exp_prefix, configs, seed, device): # super(MFRL, self).__init__(configs, seed) # print('init MBRL!')",
"# num_traj = 40 horizon = 1000 max_size = self.configs['data']['batch_size'] self.buffer = TrajBuffer(self.obs_dim,",
"= self.learn_env.reset(), 0, 0, 0 if Ni < 1: return o, Z, el,",
"Z, el, t): Nt = self.configs['algorithm']['learning']['epoch_steps'] max_el = self.configs['environment']['horizon'] # a = self.actor_critic.get_action_np(o)",
"= 0 while nt < NT: # Random actions a = self.learn_env.action_space.sample() o_next,",
"# print('v=0') v = T.Tensor([0.0]) self.buffer.finish_path(el, v) # print(f'termination: t={t} | el={el} |",
"= self.learn_env.step(a) Z += r el += 1 t += 1 self.buffer.store(o, a,",
"el={el} | total_size={self.buffer.total_size()}') o, Z, el = self.learn_env.reset(), 0, 0 return o, Z,",
"0: # env = gym.wrappers.RecordVideo(env, f\"videos/{run_name}\") # env = gym.wrappers.ClipAction(env) # env =",
"= o_next if d or (el == max_el): if el == max_el: with",
"import Box import numpy as np import torch as T import rl.environments from",
"Z, el = self.learn_env.reset(), 0, 0, 0 o, d = o_next, d_next return",
"or (el == max_el): o, Z, el = self.learn_env.reset(), 0, 0 nt +=",
"or (el == max_el): if el == max_el: with T.no_grad(): v = self.actor_critic.get_v(T.Tensor(o)).cpu()",
"return o, Z, el, t def evaluate_op(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[",
"= exp_prefix self.configs = configs self.seed = seed self._device_ = device def _build(self):",
"print(f' [ Agent Evaluation ] Episode: {ee} ', end='\\r') o, d, Z, S,",
"= [] # Evaluation episodic score EL = [] # Evaluation episodic length",
"', log_pi) o_next, r, d, _ = self.learn_env.step(a) Z += r el +=",
"# Deterministic action | No reparameterization o, r, d, info = self.eval_env.step(a) Z",
"= self.learn_env.step(a) d = False if el == max_el else d # Ignore",
"EL def evaluate(self): evaluate = self.configs['algorithm']['evaluation'] if evaluate: print('[ Evaluation ]') EE =",
"device = self._device_ if self.configs['algorithm']['on-policy']: # num_traj = 40 horizon = 1000 max_size",
"self.obs_dim = self.learn_env.observation_space.shape[0] self.act_dim = self.learn_env.action_space.shape[0] self.act_up_lim = self.learn_env.action_space.high self.act_low_lim = self.learn_env.action_space.low def",
"== max_el)): # with T.no_grad(): a, _, _ = self.actor_critic.get_pi(T.Tensor(o)) a = self.actor_critic.get_action_np(o,",
"ES[i] /= EL[i] return EZ, ES, EL def evaluate(self): evaluate = self.configs['algorithm']['evaluation'] if",
"device) else: self.buffer = ReplayBuffer(self.obs_dim, self.act_dim, max_size, self.seed, device) def initialize_buffer(self, num_traj=400): #",
"deterministic=True) # a = self.actor_critic.get_action_np(o, deterministic=True) o, r, d, info = self.eval_env.step(a) Z",
"= self.configs['data']['batch_size'] num_traj = max_size//20 horizon = 1000 self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon,",
"if d_next or (el == max_el): # o_next, Z, el = self.learn_env.reset(), 0,",
"No reparameterization o, r, d, info = self.eval_env.step(a) Z += r if self.configs['environment']['type']",
"| No reparameterization # Deterministic action | No reparameterization else: a = self.learn_env.action_space.sample()",
"_, _ = self.actor_critic.get_pi(T.Tensor(o)) a = self.actor_critic.get_action_np(o, deterministic=True) # a = self.actor_critic.get_action_np(o, deterministic=True)",
"= self.learn_env.step(a) Z += r el += 1 t += 1 self.buffer.store_transition(o, a,",
"MBRL!') self.exp_prefix = exp_prefix self.configs = configs self.seed = seed self._device_ = device",
"self.actor_critic.get_action_np(o, deterministic=True) # a = self.actor_critic.get_action_np(o, deterministic=True) o, r, d, info = self.eval_env.step(a)",
"d) o = o_next Z += r el +=1 t +=1 if d",
"= self.configs['environment']['name'] evaluate = self.configs['algorithm']['evaluation'] # Inintialize Learning environment self.learn_env = gym.make(name) self._seed_env(self.learn_env)",
"= gym.make(name) self._seed_env(self.learn_env) assert isinstance (self.learn_env.action_space, Box), \"Works only with continuous action space\"",
"self.seed, device) def initialize_buffer(self, num_traj=400): # print('Initialize a New Buffer..') seed = self.seed",
"self.learn_env.step(a) d = True if el == max_el else d # Ignore artificial",
"S, el = self.eval_env.reset(), False, 0, 0, 0 while not(d or (el ==",
"] Epoch {ni}') nt = 0 while nt < NT: # Random actions",
"d # Ignore artificial termination self.buffer.store_transition(o, a, r, o_next, d) o = o_next",
"(el == max_el): if el == max_el: with T.no_grad(): v = self.actor_critic.get_v(T.Tensor(o)).cpu() else:",
"for ni in range(1, Ni+1): print(f'[ Initial exploaration ] Epoch {ni}') nt =",
"1000 max_size = self.configs['data']['batch_size'] self.buffer = TrajBuffer(self.obs_dim, self.act_dim, horizon, num_traj, max_size, self.seed, device)",
"(el == max_el): # o_next, Z, el = self.learn_env.reset(), 0, 0 with T.no_grad():",
"= gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10)) # env = gym.wrappers.NormalizeReward(env) # env",
"seed, idx, capture_video, run_name): # def thunk(): # print('in thunk') # env =",
"nt += 1 return o, Z, el, t def internact_op(self, n, o, d,",
"d, info = self.eval_env.step(a) Z += r if self.configs['environment']['type'] == 'mujoco-pddm-shadowhand': S +=",
"]') EE = self.configs['algorithm']['evaluation']['eval_episodes'] max_el = self.configs['environment']['horizon'] EZ = [] # Evaluation episodic",
"from rl.data.buffer import TrajBuffer, ReplayBuffer # from rl.data.buffer import TrajBuffer, ReplayBufferNP # def",
"self.learn_env.step(a) d = False if el == max_el else d # Ignore artificial"
] |
[
"configparser.RawConfigParser() config.read('.twconfig') print('success!') except: print('failed to read config file!') exit() try: sys.stdout.write('connecting to",
"' % statusId ) status = api.GetStatus(statusId) print('success!') except: print('failed to get status!')",
"them signing up at https://apps.twitter.com #Install required modules with #'pip install -r requirements.txt'",
"status id to fetch statusId = '973464578708316161' try: sys.stdout.write('reading config file... ') config",
"your own api keys and secrets #Get them signing up at https://apps.twitter.com #Install",
"print('failed to read config file!') exit() try: sys.stdout.write('connecting to api... ') api =",
"to get status!') exit() try: print('writing to file out.txt... ') with open(statusId +",
"to read config file!') exit() try: sys.stdout.write('connecting to api... ') api = twitter.Api(consumer_key=config.get('keys',",
"o.__dict__ #usage: print(json.dumps(string, default=jdefault)) def main(): #Twitter status id to fetch statusId =",
"api = twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys', 'access_secret')) print('success!') except Exception",
"as e: print('failed to connect to twitter api!') print(e) exit() try: sys.stdout.write('fetching status",
"to fetch statusId = '973464578708316161' try: sys.stdout.write('reading config file... ') config = configparser.RawConfigParser()",
"to twitter api!') print(e) exit() try: sys.stdout.write('fetching status %s... ' % statusId )",
"import sys import json import twitter def jdefault(o): return o.__dict__ #usage: print(json.dumps(string, default=jdefault))",
"print(json.dumps(string, default=jdefault)) def main(): #Twitter status id to fetch statusId = '973464578708316161' try:",
"import os import sys import json import twitter def jdefault(o): return o.__dict__ #usage:",
"exit() try: sys.stdout.write('fetching status %s... ' % statusId ) status = api.GetStatus(statusId) print('success!')",
"os import sys import json import twitter def jdefault(o): return o.__dict__ #usage: print(json.dumps(string,",
"try: print('writing to file out.txt... ') with open(statusId + '.txt', 'w') as outfile:",
"= configparser.RawConfigParser() config.read('.twconfig') print('success!') except: print('failed to read config file!') exit() try: sys.stdout.write('connecting",
"except Exception as e: print('failed to connect to twitter api!') print(e) exit() try:",
"outfile: statusparsed = json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault) + '\\n') sys.stdout.write('Created at: ' + statusparsed['created_at'])",
"+ '\\n') sys.stdout.write('Created at: ' + statusparsed['created_at']) outfile.closed except: print('failed writing to file!')",
"same directory #with your own api keys and secrets #Get them signing up",
"install -r requirements.txt' import configparser import os import sys import json import twitter",
"status = api.GetStatus(statusId) print('success!') except: print('failed to get status!') exit() try: print('writing to",
"file!') exit() try: sys.stdout.write('connecting to api... ') api = twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'),",
"'access_secret')) print('success!') except Exception as e: print('failed to connect to twitter api!') print(e)",
"this same directory #with your own api keys and secrets #Get them signing",
"open(statusId + '.txt', 'w') as outfile: statusparsed = json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault) + '\\n')",
"= '973464578708316161' try: sys.stdout.write('reading config file... ') config = configparser.RawConfigParser() config.read('.twconfig') print('success!') except:",
"print('success!') except: print('failed to read config file!') exit() try: sys.stdout.write('connecting to api... ')",
"consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys', 'access_secret')) print('success!') except Exception as e: print('failed to",
"https://apps.twitter.com #Install required modules with #'pip install -r requirements.txt' import configparser import os",
"access_token_secret=config.get('keys', 'access_secret')) print('success!') except Exception as e: print('failed to connect to twitter api!')",
"at: ' + statusparsed['created_at']) outfile.closed except: print('failed writing to file!') exit() if __name__",
"keys and secrets #Get them signing up at https://apps.twitter.com #Install required modules with",
"to connect to twitter api!') print(e) exit() try: sys.stdout.write('fetching status %s... ' %",
") status = api.GetStatus(statusId) print('success!') except: print('failed to get status!') exit() try: print('writing",
"statusparsed['created_at']) outfile.closed except: print('failed writing to file!') exit() if __name__ == \"__main__\": main()",
"#'pip install -r requirements.txt' import configparser import os import sys import json import",
"statusId = '973464578708316161' try: sys.stdout.write('reading config file... ') config = configparser.RawConfigParser() config.read('.twconfig') print('success!')",
"requirements.txt' import configparser import os import sys import json import twitter def jdefault(o):",
"sys.stdout.write('Created at: ' + statusparsed['created_at']) outfile.closed except: print('failed writing to file!') exit() if",
"config file!') exit() try: sys.stdout.write('connecting to api... ') api = twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys',",
"'.txt', 'w') as outfile: statusparsed = json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault) + '\\n') sys.stdout.write('Created at:",
"def main(): #Twitter status id to fetch statusId = '973464578708316161' try: sys.stdout.write('reading config",
"print('writing to file out.txt... ') with open(statusId + '.txt', 'w') as outfile: statusparsed",
"except: print('failed to get status!') exit() try: print('writing to file out.txt... ') with",
"#Update your .twconfig file on this same directory #with your own api keys",
"your .twconfig file on this same directory #with your own api keys and",
"file out.txt... ') with open(statusId + '.txt', 'w') as outfile: statusparsed = json.loads(str(status).encode())",
"signing up at https://apps.twitter.com #Install required modules with #'pip install -r requirements.txt' import",
"status!') exit() try: print('writing to file out.txt... ') with open(statusId + '.txt', 'w')",
"') config = configparser.RawConfigParser() config.read('.twconfig') print('success!') except: print('failed to read config file!') exit()",
"fetch statusId = '973464578708316161' try: sys.stdout.write('reading config file... ') config = configparser.RawConfigParser() config.read('.twconfig')",
"api keys and secrets #Get them signing up at https://apps.twitter.com #Install required modules",
"at https://apps.twitter.com #Install required modules with #'pip install -r requirements.txt' import configparser import",
".twconfig file on this same directory #with your own api keys and secrets",
"api.GetStatus(statusId) print('success!') except: print('failed to get status!') exit() try: print('writing to file out.txt...",
"-r requirements.txt' import configparser import os import sys import json import twitter def",
"') api = twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys', 'access_secret')) print('success!') except",
"api!') print(e) exit() try: sys.stdout.write('fetching status %s... ' % statusId ) status =",
"api... ') api = twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys', 'access_secret')) print('success!')",
"sys.stdout.write('connecting to api... ') api = twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys',",
"file on this same directory #with your own api keys and secrets #Get",
"with #'pip install -r requirements.txt' import configparser import os import sys import json",
"= twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys', 'access_secret')) print('success!') except Exception as",
"= api.GetStatus(statusId) print('success!') except: print('failed to get status!') exit() try: print('writing to file",
"'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys', 'access_secret')) print('success!') except Exception as e: print('failed",
"#usage: print(json.dumps(string, default=jdefault)) def main(): #Twitter status id to fetch statusId = '973464578708316161'",
"try: sys.stdout.write('connecting to api... ') api = twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys', 'access_key'),",
"outfile.write(json.dumps(status, default=jdefault) + '\\n') sys.stdout.write('Created at: ' + statusparsed['created_at']) outfile.closed except: print('failed writing",
"python #Update your .twconfig file on this same directory #with your own api",
"own api keys and secrets #Get them signing up at https://apps.twitter.com #Install required",
"required modules with #'pip install -r requirements.txt' import configparser import os import sys",
"def jdefault(o): return o.__dict__ #usage: print(json.dumps(string, default=jdefault)) def main(): #Twitter status id to",
"try: sys.stdout.write('reading config file... ') config = configparser.RawConfigParser() config.read('.twconfig') print('success!') except: print('failed to",
"configparser import os import sys import json import twitter def jdefault(o): return o.__dict__",
"print('failed to get status!') exit() try: print('writing to file out.txt... ') with open(statusId",
"get status!') exit() try: print('writing to file out.txt... ') with open(statusId + '.txt',",
"access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys', 'access_secret')) print('success!') except Exception as e: print('failed to connect to",
"status %s... ' % statusId ) status = api.GetStatus(statusId) print('success!') except: print('failed to",
"'consumer_secret'), access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys', 'access_secret')) print('success!') except Exception as e: print('failed to connect",
"print('success!') except: print('failed to get status!') exit() try: print('writing to file out.txt... ')",
"#with your own api keys and secrets #Get them signing up at https://apps.twitter.com",
"'w') as outfile: statusparsed = json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault) + '\\n') sys.stdout.write('Created at: '",
"' + statusparsed['created_at']) outfile.closed except: print('failed writing to file!') exit() if __name__ ==",
"twitter def jdefault(o): return o.__dict__ #usage: print(json.dumps(string, default=jdefault)) def main(): #Twitter status id",
"#Install required modules with #'pip install -r requirements.txt' import configparser import os import",
"'973464578708316161' try: sys.stdout.write('reading config file... ') config = configparser.RawConfigParser() config.read('.twconfig') print('success!') except: print('failed",
"twitter api!') print(e) exit() try: sys.stdout.write('fetching status %s... ' % statusId ) status",
"connect to twitter api!') print(e) exit() try: sys.stdout.write('fetching status %s... ' % statusId",
"sys.stdout.write('reading config file... ') config = configparser.RawConfigParser() config.read('.twconfig') print('success!') except: print('failed to read",
"#!/usr/bin/env python #Update your .twconfig file on this same directory #with your own",
"up at https://apps.twitter.com #Install required modules with #'pip install -r requirements.txt' import configparser",
"+ statusparsed['created_at']) outfile.closed except: print('failed writing to file!') exit() if __name__ == \"__main__\":",
"try: sys.stdout.write('fetching status %s... ' % statusId ) status = api.GetStatus(statusId) print('success!') except:",
"directory #with your own api keys and secrets #Get them signing up at",
"default=jdefault)) def main(): #Twitter status id to fetch statusId = '973464578708316161' try: sys.stdout.write('reading",
"'access_key'), access_token_secret=config.get('keys', 'access_secret')) print('success!') except Exception as e: print('failed to connect to twitter",
"with open(statusId + '.txt', 'w') as outfile: statusparsed = json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault) +",
"modules with #'pip install -r requirements.txt' import configparser import os import sys import",
"except: print('failed to read config file!') exit() try: sys.stdout.write('connecting to api... ') api",
"+ '.txt', 'w') as outfile: statusparsed = json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault) + '\\n') sys.stdout.write('Created",
"on this same directory #with your own api keys and secrets #Get them",
"exit() try: print('writing to file out.txt... ') with open(statusId + '.txt', 'w') as",
"secrets #Get them signing up at https://apps.twitter.com #Install required modules with #'pip install",
"read config file!') exit() try: sys.stdout.write('connecting to api... ') api = twitter.Api(consumer_key=config.get('keys', 'consumer_key'),",
"config = configparser.RawConfigParser() config.read('.twconfig') print('success!') except: print('failed to read config file!') exit() try:",
"= json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault) + '\\n') sys.stdout.write('Created at: ' + statusparsed['created_at']) outfile.closed except:",
"return o.__dict__ #usage: print(json.dumps(string, default=jdefault)) def main(): #Twitter status id to fetch statusId",
"statusparsed = json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault) + '\\n') sys.stdout.write('Created at: ' + statusparsed['created_at']) outfile.closed",
"print(e) exit() try: sys.stdout.write('fetching status %s... ' % statusId ) status = api.GetStatus(statusId)",
"import json import twitter def jdefault(o): return o.__dict__ #usage: print(json.dumps(string, default=jdefault)) def main():",
"id to fetch statusId = '973464578708316161' try: sys.stdout.write('reading config file... ') config =",
"Exception as e: print('failed to connect to twitter api!') print(e) exit() try: sys.stdout.write('fetching",
"'\\n') sys.stdout.write('Created at: ' + statusparsed['created_at']) outfile.closed except: print('failed writing to file!') exit()",
"to file out.txt... ') with open(statusId + '.txt', 'w') as outfile: statusparsed =",
"statusId ) status = api.GetStatus(statusId) print('success!') except: print('failed to get status!') exit() try:",
"#Twitter status id to fetch statusId = '973464578708316161' try: sys.stdout.write('reading config file... ')",
"%s... ' % statusId ) status = api.GetStatus(statusId) print('success!') except: print('failed to get",
"as outfile: statusparsed = json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault) + '\\n') sys.stdout.write('Created at: ' +",
"to api... ') api = twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys', 'access_secret'))",
"') with open(statusId + '.txt', 'w') as outfile: statusparsed = json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault)",
"e: print('failed to connect to twitter api!') print(e) exit() try: sys.stdout.write('fetching status %s...",
"import configparser import os import sys import json import twitter def jdefault(o): return",
"config file... ') config = configparser.RawConfigParser() config.read('.twconfig') print('success!') except: print('failed to read config",
"and secrets #Get them signing up at https://apps.twitter.com #Install required modules with #'pip",
"% statusId ) status = api.GetStatus(statusId) print('success!') except: print('failed to get status!') exit()",
"default=jdefault) + '\\n') sys.stdout.write('Created at: ' + statusparsed['created_at']) outfile.closed except: print('failed writing to",
"#Get them signing up at https://apps.twitter.com #Install required modules with #'pip install -r",
"exit() try: sys.stdout.write('connecting to api... ') api = twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys',",
"file... ') config = configparser.RawConfigParser() config.read('.twconfig') print('success!') except: print('failed to read config file!')",
"main(): #Twitter status id to fetch statusId = '973464578708316161' try: sys.stdout.write('reading config file...",
"sys.stdout.write('fetching status %s... ' % statusId ) status = api.GetStatus(statusId) print('success!') except: print('failed",
"jdefault(o): return o.__dict__ #usage: print(json.dumps(string, default=jdefault)) def main(): #Twitter status id to fetch",
"print('failed to connect to twitter api!') print(e) exit() try: sys.stdout.write('fetching status %s... '",
"json.loads(str(status).encode()) outfile.write(json.dumps(status, default=jdefault) + '\\n') sys.stdout.write('Created at: ' + statusparsed['created_at']) outfile.closed except: print('failed",
"out.txt... ') with open(statusId + '.txt', 'w') as outfile: statusparsed = json.loads(str(status).encode()) outfile.write(json.dumps(status,",
"import twitter def jdefault(o): return o.__dict__ #usage: print(json.dumps(string, default=jdefault)) def main(): #Twitter status",
"sys import json import twitter def jdefault(o): return o.__dict__ #usage: print(json.dumps(string, default=jdefault)) def",
"json import twitter def jdefault(o): return o.__dict__ #usage: print(json.dumps(string, default=jdefault)) def main(): #Twitter",
"print('success!') except Exception as e: print('failed to connect to twitter api!') print(e) exit()",
"config.read('.twconfig') print('success!') except: print('failed to read config file!') exit() try: sys.stdout.write('connecting to api...",
"twitter.Api(consumer_key=config.get('keys', 'consumer_key'), consumer_secret=config.get('keys', 'consumer_secret'), access_token_key=config.get('keys', 'access_key'), access_token_secret=config.get('keys', 'access_secret')) print('success!') except Exception as e:"
] |
[
"dest_offset += 2 * 2 * npart continue if npart >= 11: src1",
"f\"ldrh {r}, [{addr}, #{i * 4 + offset}]\" else: yield f\"ldr {r}, [{addr},",
"a_offset += 2 * npart yield from blockload(src1, a, npart, a_offset) if npart",
"[sp, #4]\" if col & 1: # for odd columns, go 'back up'",
"{src1}, [sp, #4]\" if col & 1: # for odd columns, go 'back",
"npart >= 11: # we cannot afford to keep these pointers around yield",
"11: src1 = regs.alloc() yield f\"ldr {src1}, [sp, #4]\" if col & 1:",
"odd columns, go 'back up' instead of down dest_offset -= 2 * npart",
"else: yield f\"ldr {r}, [{addr}, #{i * 4 + offset}]\" # allocate registers",
"for odd columns, go 'back up' instead of down dest_offset -= 2 *",
"don't load new src1 inputs if lastrow: if row == 0: # if",
"neatly into schoolbook blocks # for n <= 12, it's simply one schoolbook",
"yield f\"ldr {src1}, [sp, #4]\" if col & 1: # for odd columns,",
"SRC2, DEST, npart * parts) yield from schoolbook_postprocess(SRC1, SRC2, DEST, instructions, n, stack_src=True)",
"allocated regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST) # these can be flexible, do not need to",
"== parts-1: # if it's the last part, don't load new src2 inputs",
"idea here is that we need to divide neatly into schoolbook blocks #",
"SRC2, DEST, instructions, n, stack_src=True) def schoolbook_even_medium(SRC1, SRC2, DEST, n): # the idea",
"2 * npart # if it's the last part in this col, don't",
"first re-alloc src1 = SRC1 src2 = SRC2 parts = ceil(n / 12)",
"blockload(src1, a, npart, a_offset) if npart >= 11: # we cannot afford to",
"instead of down dest_offset -= 2 * npart else: dest_offset += 2 *",
"n <= 24, we divide into 2x2 schoolbooks (so require even n) #",
"SRC2 parts = ceil(n / 12) npart = n // parts # note",
"yield f\"str {src2}, [sp, #0]\" regs.free(src2) regs.free(*set(a)) regs.free(*set(b)) if npart >= 11: yield",
"we just finished a back-and-forth dest_offset += 2 * 2 * npart continue",
"if row == 0: # if we just finished a back-and-forth dest_offset +=",
"lastrow: if row == 0: # if we just finished a back-and-forth dest_offset",
"schoolbook # for 12 < n <= 24, we divide into 2x2 schoolbooks",
"1) and row == parts-1 or (col & 1) and row == 0",
"2 * npart else: a_offset += 2 * npart yield from blockload(src1, a,",
"loads) regs = Registers(reversed([f'r{i}' for i in range(0, 13)] + [\"r14\"])) # consider",
"yield f\"str {src1}, [sp, #4]\" regs.free(src1) if col == parts-1: # if it's",
"if col == parts-1: # if it's the last part, don't load new",
"last part in this col, don't load new src1 inputs if lastrow: if",
"have 16-bit loads) regs = Registers(reversed([f'r{i}' for i in range(0, 13)] + [\"r14\"]))",
"schoolbook_postprocess(SRC1, SRC2, DEST, instructions, n, stack_src=True) def schoolbook_even_medium(SRC1, SRC2, DEST, n): # the",
"the last part in this col, don't load new src1 inputs if lastrow:",
"= not (col & 1) and row == parts-1 or (col & 1)",
"n <= 12, it's simply one schoolbook # for 12 < n <=",
"repacking b = [regs.alloc() for _ in range(ceil(npart / 2))] yield from blockload(src2,",
"schoolbook_even_medium(SRC1, SRC2, DEST, n): # the idea here is that we need to",
"math import ceil from .common import schoolbook_inner, Registers, schoolbook_postprocess import sys def schoolbook_medium(SRC1,",
"Registers, schoolbook_postprocess import sys def schoolbook_medium(SRC1, SRC2, DEST, n): parts = ceil(n /",
"range(0, 13)] + [\"r14\"])) # consider SRC1, SRC2 and DEST allocated regs.alloc(SRC1) regs.alloc(SRC2)",
"note that these offsets shouldnt exceed 4096 (i.e. n shouldnt be huge) dest_offset",
"for n <= 12, it's simply one schoolbook # for 12 < n",
"24, we divide into 2x2 schoolbooks (so require even n) # for 24",
"we divide into 3x3 schoolbooks (so require n % 3 == 0) #",
"# etc. assert n % ceil(n / 12) == 0, \"Can only handle",
"-1, -1) if col & 1 else range(parts)): lastrow = not (col &",
"else range(parts)): lastrow = not (col & 1) and row == parts-1 or",
"= [regs.alloc() for _ in range(ceil(npart / 2))] yield from blockload(src2, b, npart,",
"for 12 < n <= 24, we divide into 2x2 schoolbooks (so require",
"r in enumerate(regs): # if it's the last coefficient for odd n, load",
"/ parts) instructions = schoolbook_even_medium(SRC1, SRC2, DEST, npart * parts) yield from schoolbook_postprocess(SRC1,",
"(col & 1) and row == 0 yield from schoolbook_inner(npart, a, b, DEST,",
"there's one extra after repacking b = [regs.alloc() for _ in range(ceil(npart /",
"# free; for some n there's one extra after repacking b = [regs.alloc()",
"if it's the last coefficient for odd n, load only one halfword if",
"[sp, #4]\" regs.free(src1) if col == parts-1: # if it's the last part,",
"a, npart, a_offset) if npart >= 11: yield f\"str {src1}, [sp, #4]\" regs.free(src1)",
"n <= 36, we divide into 3x3 schoolbooks (so require n % 3",
"12) npart = ceil(n / parts) instructions = schoolbook_even_medium(SRC1, SRC2, DEST, npart *",
"new src1 inputs if lastrow: if row == 0: # if we just",
"from blockload(src1, a, npart, a_offset) if npart >= 11: yield f\"str {src1}, [sp,",
"def schoolbook_medium(SRC1, SRC2, DEST, n): parts = ceil(n / 12) npart = ceil(n",
"f\"ldr {r}, [{addr}, #{i * 4 + offset}]\" # allocate registers for a",
"# the idea here is that we need to divide neatly into schoolbook",
"can be flexible, do not need to be r0 and r1 after first",
"do not need to be r0 and r1 after first re-alloc src1 =",
"b_offset = 0 def blockload(addr, regs, n, offset=0): for i, r in enumerate(regs):",
"go 'back up' instead of down a_offset -= 2 * npart else: a_offset",
"into schoolbook blocks # for n <= 12, it's simply one schoolbook #",
"1 else range(parts)): lastrow = not (col & 1) and row == parts-1",
"if we just finished a back-and-forth dest_offset += 2 * 2 * npart",
"parts) yield from schoolbook_postprocess(SRC1, SRC2, DEST, instructions, n, stack_src=True) def schoolbook_even_medium(SRC1, SRC2, DEST,",
"halfword if i == n // 2 and n & 1: yield f\"ldrh",
"part, don't load new src2 inputs continue if npart >= 11: src2 =",
"#0]\" b_offset += 2 * npart regs.free(*set(b)) # free; for some n there's",
"= [regs.alloc() for _ in range(ceil(npart / 2))] yield from blockload(src1, a, npart,",
"(so require even n) # for 24 < n <= 36, we divide",
"in range(0, 13)] + [\"r14\"])) # consider SRC1, SRC2 and DEST allocated regs.alloc(SRC1)",
"regs.alloc() yield f\"ldr {src2}, [sp, #0]\" b_offset += 2 * npart regs.free(*set(b)) #",
"= 0 b_offset = 0 def blockload(addr, regs, n, offset=0): for i, r",
"dest_offset=dest_offset) if col & 1: # for odd columns, go 'back up' instead",
"not need to be r0 and r1 after first re-alloc src1 = SRC1",
"== 0 yield from schoolbook_inner(npart, a, b, DEST, regs, initialized, restore_b=not lastrow, dest_offset=dest_offset)",
"n % ceil(n / 12) == 0, \"Can only handle n that divide",
"regs.alloc() yield f\"ldr {src1}, [sp, #4]\" if col & 1: # for odd",
"* parts) yield from schoolbook_postprocess(SRC1, SRC2, DEST, instructions, n, stack_src=True) def schoolbook_even_medium(SRC1, SRC2,",
"b_offset) if npart >= 11: yield f\"push {{{src2}}}\" regs.free(src2) initialized = set() for",
"npart # if it's the last part in this col, don't load new",
"here is that we need to divide neatly into schoolbook blocks # for",
"it's the last part in this col, don't load new src1 inputs if",
"% ceil(n / 12) == 0, \"Can only handle n that divide into",
"in range(parts): for row in (range(parts - 1, -1, -1) if col &",
"n shouldnt be huge) dest_offset = 0 a_offset = 0 b_offset = 0",
"for a and b a = [regs.alloc() for _ in range(ceil(npart / 2))]",
"regs, initialized, restore_b=not lastrow, dest_offset=dest_offset) if col & 1: # for odd columns,",
"2 * npart regs.free(*set(b)) # free; for some n there's one extra after",
"that divide into schoolbooks\" # reverse to prioritize low registers (as these have",
"one halfword if i == n // 2 and n & 1: yield",
"& 1) and row == 0 yield from schoolbook_inner(npart, a, b, DEST, regs,",
"= set() for col in range(parts): for row in (range(parts - 1, -1,",
"registers for a and b a = [regs.alloc() for _ in range(ceil(npart /",
"= n // parts # note that these offsets shouldnt exceed 4096 (i.e.",
"src1 = regs.alloc() yield f\"ldr {src1}, [sp, #4]\" if col & 1: #",
"1: yield f\"ldrh {r}, [{addr}, #{i * 4 + offset}]\" else: yield f\"ldr",
"+ offset}]\" else: yield f\"ldr {r}, [{addr}, #{i * 4 + offset}]\" #",
"= regs.alloc() yield f\"ldr {src2}, [sp, #0]\" b_offset += 2 * npart regs.free(*set(b))",
"+ offset}]\" # allocate registers for a and b a = [regs.alloc() for",
"11: # we cannot afford to keep these pointers around yield f\"push {{{src1}}}\"",
"from schoolbook_postprocess(SRC1, SRC2, DEST, instructions, n, stack_src=True) def schoolbook_even_medium(SRC1, SRC2, DEST, n): #",
"schoolbook_inner, Registers, schoolbook_postprocess import sys def schoolbook_medium(SRC1, SRC2, DEST, n): parts = ceil(n",
"f\"ldr {src2}, [sp, #0]\" b_offset += 2 * npart regs.free(*set(b)) # free; for",
"npart = n // parts # note that these offsets shouldnt exceed 4096",
"* 4 + offset}]\" else: yield f\"ldr {r}, [{addr}, #{i * 4 +",
"/ 2))] yield from blockload(src2, b, npart, b_offset) if npart >= 11: yield",
"else: a_offset += 2 * npart yield from blockload(src1, a, npart, a_offset) if",
"if it's the last part, don't load new src2 inputs continue if npart",
"continue if npart >= 11: src1 = regs.alloc() yield f\"ldr {src1}, [sp, #4]\"",
"into schoolbooks\" # reverse to prioritize low registers (as these have 16-bit loads)",
"0) # etc. assert n % ceil(n / 12) == 0, \"Can only",
"0 b_offset = 0 def blockload(addr, regs, n, offset=0): for i, r in",
"schoolbook_even_medium(SRC1, SRC2, DEST, npart * parts) yield from schoolbook_postprocess(SRC1, SRC2, DEST, instructions, n,",
"blocks # for n <= 12, it's simply one schoolbook # for 12",
"n, stack_src=True) def schoolbook_even_medium(SRC1, SRC2, DEST, n): # the idea here is that",
"simply one schoolbook # for 12 < n <= 24, we divide into",
"ceil(n / 12) npart = n // parts # note that these offsets",
"b = [regs.alloc() for _ in range(ceil(npart / 2))] yield from blockload(src2, b,",
"range(ceil(npart / 2))] yield from blockload(src2, b, npart, b_offset) if npart >= 11:",
"npart >= 11: src1 = regs.alloc() yield f\"ldr {src1}, [sp, #4]\" if col",
"just finished a back-and-forth dest_offset += 2 * 2 * npart continue if",
"that we need to divide neatly into schoolbook blocks # for n <=",
"f\"ldr {src1}, [sp, #4]\" if col & 1: # for odd columns, go",
"+= 2 * npart regs.free(*set(b)) # free; for some n there's one extra",
"be flexible, do not need to be r0 and r1 after first re-alloc",
"f\"push {{{src2}}}\" regs.free(src2) initialized = set() for col in range(parts): for row in",
"to be r0 and r1 after first re-alloc src1 = SRC1 src2 =",
"npart else: a_offset += 2 * npart yield from blockload(src1, a, npart, a_offset)",
"(range(parts - 1, -1, -1) if col & 1 else range(parts)): lastrow =",
"r1 after first re-alloc src1 = SRC1 src2 = SRC2 parts = ceil(n",
"12 < n <= 24, we divide into 2x2 schoolbooks (so require even",
"dest_offset = 0 a_offset = 0 b_offset = 0 def blockload(addr, regs, n,",
"= ceil(n / parts) instructions = schoolbook_even_medium(SRC1, SRC2, DEST, npart * parts) yield",
"yield f\"push {{{src1}}}\" regs.free(src1) b = [regs.alloc() for _ in range(ceil(npart / 2))]",
"def blockload(addr, regs, n, offset=0): for i, r in enumerate(regs): # if it's",
"npart >= 11: yield f\"str {src1}, [sp, #4]\" regs.free(src1) if col == parts-1:",
"require even n) # for 24 < n <= 36, we divide into",
"dest_offset += 2 * npart # if it's the last part in this",
"extra after repacking b = [regs.alloc() for _ in range(ceil(npart / 2))] yield",
"11: yield f\"str {src1}, [sp, #4]\" regs.free(src1) if col == parts-1: # if",
"12, it's simply one schoolbook # for 12 < n <= 24, we",
"range(parts)): lastrow = not (col & 1) and row == parts-1 or (col",
"after repacking b = [regs.alloc() for _ in range(ceil(npart / 2))] yield from",
"% 3 == 0) # etc. assert n % ceil(n / 12) ==",
"blockload(src2, b, npart, b_offset) if npart >= 11: yield f\"str {src2}, [sp, #0]\"",
"# for 12 < n <= 24, we divide into 2x2 schoolbooks (so",
"col == parts-1: # if it's the last part, don't load new src2",
"yield from blockload(src2, b, npart, b_offset) if npart >= 11: yield f\"str {src2},",
"a and b a = [regs.alloc() for _ in range(ceil(npart / 2))] yield",
"// parts # note that these offsets shouldnt exceed 4096 (i.e. n shouldnt",
"yield f\"ldrh {r}, [{addr}, #{i * 4 + offset}]\" else: yield f\"ldr {r},",
"/ 12) npart = n // parts # note that these offsets shouldnt",
"yield from blockload(src2, b, npart, b_offset) if npart >= 11: yield f\"push {{{src2}}}\"",
"in enumerate(regs): # if it's the last coefficient for odd n, load only",
"assert n % ceil(n / 12) == 0, \"Can only handle n that",
"npart >= 11: yield f\"str {src2}, [sp, #0]\" regs.free(src2) regs.free(*set(a)) regs.free(*set(b)) if npart",
"[{addr}, #{i * 4 + offset}]\" else: yield f\"ldr {r}, [{addr}, #{i *",
"not (col & 1) and row == parts-1 or (col & 1) and",
".common import schoolbook_inner, Registers, schoolbook_postprocess import sys def schoolbook_medium(SRC1, SRC2, DEST, n): parts",
"{{{src1}}}\" regs.free(src1) b = [regs.alloc() for _ in range(ceil(npart / 2))] yield from",
"yield f\"ldr {src2}, [sp, #0]\" b_offset += 2 * npart regs.free(*set(b)) # free;",
"# if we just finished a back-and-forth dest_offset += 2 * 2 *",
"for odd columns, go 'back up' instead of down a_offset -= 2 *",
"low registers (as these have 16-bit loads) regs = Registers(reversed([f'r{i}' for i in",
"col, don't load new src1 inputs if lastrow: if row == 0: #",
"exceed 4096 (i.e. n shouldnt be huge) dest_offset = 0 a_offset = 0",
"regs.free(*set(b)) # free; for some n there's one extra after repacking b =",
"+= 2 * npart yield from blockload(src1, a, npart, a_offset) if npart >=",
"+= 2 * 2 * npart continue if npart >= 11: src1 =",
"1) and row == 0 yield from schoolbook_inner(npart, a, b, DEST, regs, initialized,",
"ceil(n / 12) npart = ceil(n / parts) instructions = schoolbook_even_medium(SRC1, SRC2, DEST,",
"the last coefficient for odd n, load only one halfword if i ==",
"initialized = set() for col in range(parts): for row in (range(parts - 1,",
"if npart >= 11: yield f\"str {src1}, [sp, #4]\" regs.free(src1) if col ==",
"0 yield from schoolbook_inner(npart, a, b, DEST, regs, initialized, restore_b=not lastrow, dest_offset=dest_offset) if",
"yield from blockload(src1, a, npart, a_offset) if npart >= 11: yield f\"str {src1},",
"f\"str {src1}, [sp, #4]\" regs.free(src1) if col == parts-1: # if it's the",
"col & 1: # for odd columns, go 'back up' instead of down",
"handle n that divide into schoolbooks\" # reverse to prioritize low registers (as",
"DEST, n): # the idea here is that we need to divide neatly",
"yield f\"push {{{src2}}}\" regs.free(src2) initialized = set() for col in range(parts): for row",
"< n <= 36, we divide into 3x3 schoolbooks (so require n %",
"# for odd columns, go 'back up' instead of down a_offset -= 2",
"{{{src2}}}\" regs.free(src2) initialized = set() for col in range(parts): for row in (range(parts",
"2 * npart yield from blockload(src1, a, npart, a_offset) if npart >= 11:",
"16-bit loads) regs = Registers(reversed([f'r{i}' for i in range(0, 13)] + [\"r14\"])) #",
"12) == 0, \"Can only handle n that divide into schoolbooks\" # reverse",
"from blockload(src1, a, npart, a_offset) if npart >= 11: # we cannot afford",
"only one halfword if i == n // 2 and n & 1:",
"a_offset) if npart >= 11: yield f\"str {src1}, [sp, #4]\" regs.free(src1) if col",
"<= 36, we divide into 3x3 schoolbooks (so require n % 3 ==",
"i, r in enumerate(regs): # if it's the last coefficient for odd n,",
"#{i * 4 + offset}]\" # allocate registers for a and b a",
"n): # the idea here is that we need to divide neatly into",
"only handle n that divide into schoolbooks\" # reverse to prioritize low registers",
"up' instead of down dest_offset -= 2 * npart else: dest_offset += 2",
"(i.e. n shouldnt be huge) dest_offset = 0 a_offset = 0 b_offset =",
"_ in range(ceil(npart / 2))] yield from blockload(src1, a, npart, a_offset) if npart",
"if col & 1: # for odd columns, go 'back up' instead of",
"2x2 schoolbooks (so require even n) # for 24 < n <= 36,",
"schoolbook_postprocess import sys def schoolbook_medium(SRC1, SRC2, DEST, n): parts = ceil(n / 12)",
"range(parts): for row in (range(parts - 1, -1, -1) if col & 1",
"== 0: # if we just finished a back-and-forth dest_offset += 2 *",
"or (col & 1) and row == 0 yield from schoolbook_inner(npart, a, b,",
"initialized, restore_b=not lastrow, dest_offset=dest_offset) if col & 1: # for odd columns, go",
"= ceil(n / 12) npart = n // parts # note that these",
"3 == 0) # etc. assert n % ceil(n / 12) == 0,",
"[{addr}, #{i * 4 + offset}]\" # allocate registers for a and b",
"n // 2 and n & 1: yield f\"ldrh {r}, [{addr}, #{i *",
"src1 = SRC1 src2 = SRC2 parts = ceil(n / 12) npart =",
"36, we divide into 3x3 schoolbooks (so require n % 3 == 0)",
"afford to keep these pointers around yield f\"push {{{src1}}}\" regs.free(src1) b = [regs.alloc()",
"part in this col, don't load new src1 inputs if lastrow: if row",
"-= 2 * npart else: a_offset += 2 * npart yield from blockload(src1,",
"don't load new src2 inputs continue if npart >= 11: src2 = regs.alloc()",
"for _ in range(ceil(npart / 2))] yield from blockload(src2, b, npart, b_offset) if",
"into 3x3 schoolbooks (so require n % 3 == 0) # etc. assert",
"for row in (range(parts - 1, -1, -1) if col & 1 else",
"# for n <= 12, it's simply one schoolbook # for 12 <",
"load only one halfword if i == n // 2 and n &",
"back-and-forth dest_offset += 2 * 2 * npart continue if npart >= 11:",
"Registers(reversed([f'r{i}' for i in range(0, 13)] + [\"r14\"])) # consider SRC1, SRC2 and",
"divide into 3x3 schoolbooks (so require n % 3 == 0) # etc.",
"& 1 else range(parts)): lastrow = not (col & 1) and row ==",
"* npart else: dest_offset += 2 * npart # if it's the last",
"i == n // 2 and n & 1: yield f\"ldrh {r}, [{addr},",
"a back-and-forth dest_offset += 2 * 2 * npart continue if npart >=",
"this col, don't load new src1 inputs if lastrow: if row == 0:",
"we divide into 2x2 schoolbooks (so require even n) # for 24 <",
"# we cannot afford to keep these pointers around yield f\"push {{{src1}}}\" regs.free(src1)",
">= 11: yield f\"str {src1}, [sp, #4]\" regs.free(src1) if col == parts-1: #",
"dest_offset -= 2 * npart else: dest_offset += 2 * npart # if",
"-= 2 * npart else: dest_offset += 2 * npart # if it's",
"etc. assert n % ceil(n / 12) == 0, \"Can only handle n",
"offsets shouldnt exceed 4096 (i.e. n shouldnt be huge) dest_offset = 0 a_offset",
"if npart >= 11: src2 = regs.alloc() yield f\"ldr {src2}, [sp, #0]\" b_offset",
"- 1, -1, -1) if col & 1 else range(parts)): lastrow = not",
"<= 24, we divide into 2x2 schoolbooks (so require even n) # for",
"row == 0 yield from schoolbook_inner(npart, a, b, DEST, regs, initialized, restore_b=not lastrow,",
"be huge) dest_offset = 0 a_offset = 0 b_offset = 0 def blockload(addr,",
"& 1) and row == parts-1 or (col & 1) and row ==",
"schoolbooks\" # reverse to prioritize low registers (as these have 16-bit loads) regs",
"the last part, don't load new src2 inputs continue if npart >= 11:",
"down dest_offset -= 2 * npart else: dest_offset += 2 * npart #",
"# consider SRC1, SRC2 and DEST allocated regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST) # these can",
"* 4 + offset}]\" # allocate registers for a and b a =",
"2 * 2 * npart continue if npart >= 11: src1 = regs.alloc()",
"b, npart, b_offset) if npart >= 11: yield f\"str {src2}, [sp, #0]\" regs.free(src2)",
"else: dest_offset += 2 * npart # if it's the last part in",
"4 + offset}]\" # allocate registers for a and b a = [regs.alloc()",
"[\"r14\"])) # consider SRC1, SRC2 and DEST allocated regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST) # these",
"src1 inputs if lastrow: if row == 0: # if we just finished",
"4 + offset}]\" else: yield f\"ldr {r}, [{addr}, #{i * 4 + offset}]\"",
"registers (as these have 16-bit loads) regs = Registers(reversed([f'r{i}' for i in range(0,",
"columns, go 'back up' instead of down dest_offset -= 2 * npart else:",
"[regs.alloc() for _ in range(ceil(npart / 2))] yield from blockload(src1, a, npart, a_offset)",
"npart = ceil(n / parts) instructions = schoolbook_even_medium(SRC1, SRC2, DEST, npart * parts)",
"go 'back up' instead of down dest_offset -= 2 * npart else: dest_offset",
"a_offset -= 2 * npart else: a_offset += 2 * npart yield from",
"load new src1 inputs if lastrow: if row == 0: # if we",
"1: # for odd columns, go 'back up' instead of down dest_offset -=",
"[sp, #0]\" b_offset += 2 * npart regs.free(*set(b)) # free; for some n",
"col in range(parts): for row in (range(parts - 1, -1, -1) if col",
"parts = ceil(n / 12) npart = n // parts # note that",
"SRC2 and DEST allocated regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST) # these can be flexible, do",
"#{i * 4 + offset}]\" else: yield f\"ldr {r}, [{addr}, #{i * 4",
"n, load only one halfword if i == n // 2 and n",
"to divide neatly into schoolbook blocks # for n <= 12, it's simply",
"DEST, n): parts = ceil(n / 12) npart = ceil(n / parts) instructions",
"# for odd columns, go 'back up' instead of down dest_offset -= 2",
"# these can be flexible, do not need to be r0 and r1",
"row in (range(parts - 1, -1, -1) if col & 1 else range(parts)):",
"[sp, #0]\" regs.free(src2) regs.free(*set(a)) regs.free(*set(b)) if npart >= 11: yield f\"pop {{{SRC2}}}\" yield",
"if npart >= 11: yield f\"push {{{src2}}}\" regs.free(src2) initialized = set() for col",
"reverse to prioritize low registers (as these have 16-bit loads) regs = Registers(reversed([f'r{i}'",
"npart, b_offset) if npart >= 11: yield f\"push {{{src2}}}\" regs.free(src2) initialized = set()",
"instructions = schoolbook_even_medium(SRC1, SRC2, DEST, npart * parts) yield from schoolbook_postprocess(SRC1, SRC2, DEST,",
"some n there's one extra after repacking b = [regs.alloc() for _ in",
"{src1}, [sp, #4]\" regs.free(src1) if col == parts-1: # if it's the last",
"to keep these pointers around yield f\"push {{{src1}}}\" regs.free(src1) b = [regs.alloc() for",
"free; for some n there's one extra after repacking b = [regs.alloc() for",
"src2 = regs.alloc() yield f\"ldr {src2}, [sp, #0]\" b_offset += 2 * npart",
"a_offset) if npart >= 11: # we cannot afford to keep these pointers",
"lastrow = not (col & 1) and row == parts-1 or (col &",
"f\"push {{{src1}}}\" regs.free(src1) b = [regs.alloc() for _ in range(ceil(npart / 2))] yield",
"a_offset = 0 b_offset = 0 def blockload(addr, regs, n, offset=0): for i,",
"# allocate registers for a and b a = [regs.alloc() for _ in",
"/ 2))] yield from blockload(src1, a, npart, a_offset) if npart >= 11: #",
"= Registers(reversed([f'r{i}' for i in range(0, 13)] + [\"r14\"])) # consider SRC1, SRC2",
"2 * npart continue if npart >= 11: src1 = regs.alloc() yield f\"ldr",
"regs.free(src2) regs.free(*set(a)) regs.free(*set(b)) if npart >= 11: yield f\"pop {{{SRC2}}}\" yield f\"pop {{{SRC1}}}\"",
"11: yield f\"push {{{src2}}}\" regs.free(src2) initialized = set() for col in range(parts): for",
"n that divide into schoolbooks\" # reverse to prioritize low registers (as these",
"+ [\"r14\"])) # consider SRC1, SRC2 and DEST allocated regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST) #",
"divide neatly into schoolbook blocks # for n <= 12, it's simply one",
"last part, don't load new src2 inputs continue if npart >= 11: src2",
"continue if npart >= 11: src2 = regs.alloc() yield f\"ldr {src2}, [sp, #0]\"",
"# for 24 < n <= 36, we divide into 3x3 schoolbooks (so",
"1: # for odd columns, go 'back up' instead of down a_offset -=",
"& 1: # for odd columns, go 'back up' instead of down dest_offset",
"columns, go 'back up' instead of down a_offset -= 2 * npart else:",
"is that we need to divide neatly into schoolbook blocks # for n",
"src2 inputs continue if npart >= 11: src2 = regs.alloc() yield f\"ldr {src2},",
">= 11: # we cannot afford to keep these pointers around yield f\"push",
"npart regs.free(*set(b)) # free; for some n there's one extra after repacking b",
"parts # note that these offsets shouldnt exceed 4096 (i.e. n shouldnt be",
"= 0 def blockload(addr, regs, n, offset=0): for i, r in enumerate(regs): #",
"= regs.alloc() yield f\"ldr {src1}, [sp, #4]\" if col & 1: # for",
"src2 = SRC2 parts = ceil(n / 12) npart = n // parts",
"and b a = [regs.alloc() for _ in range(ceil(npart / 2))] yield from",
"if npart >= 11: src1 = regs.alloc() yield f\"ldr {src1}, [sp, #4]\" if",
"regs = Registers(reversed([f'r{i}' for i in range(0, 13)] + [\"r14\"])) # consider SRC1,",
"set() for col in range(parts): for row in (range(parts - 1, -1, -1)",
"row == parts-1 or (col & 1) and row == 0 yield from",
"npart, a_offset) if npart >= 11: # we cannot afford to keep these",
"in (range(parts - 1, -1, -1) if col & 1 else range(parts)): lastrow",
"def schoolbook_even_medium(SRC1, SRC2, DEST, n): # the idea here is that we need",
"npart yield from blockload(src1, a, npart, a_offset) if npart >= 11: yield f\"str",
"# reverse to prioritize low registers (as these have 16-bit loads) regs =",
"even n) # for 24 < n <= 36, we divide into 3x3",
">= 11: src1 = regs.alloc() yield f\"ldr {src1}, [sp, #4]\" if col &",
"b_offset) if npart >= 11: yield f\"str {src2}, [sp, #0]\" regs.free(src2) regs.free(*set(a)) regs.free(*set(b))",
"schoolbook blocks # for n <= 12, it's simply one schoolbook # for",
"it's the last part, don't load new src2 inputs continue if npart >=",
"for odd n, load only one halfword if i == n // 2",
"to prioritize low registers (as these have 16-bit loads) regs = Registers(reversed([f'r{i}' for",
"schoolbooks (so require even n) # for 24 < n <= 36, we",
"# if it's the last coefficient for odd n, load only one halfword",
"npart >= 11: yield f\"push {{{src2}}}\" regs.free(src2) initialized = set() for col in",
"npart, a_offset) if npart >= 11: yield f\"str {src1}, [sp, #4]\" regs.free(src1) if",
"enumerate(regs): # if it's the last coefficient for odd n, load only one",
"yield from schoolbook_postprocess(SRC1, SRC2, DEST, instructions, n, stack_src=True) def schoolbook_even_medium(SRC1, SRC2, DEST, n):",
"SRC1 src2 = SRC2 parts = ceil(n / 12) npart = n //",
"if col & 1 else range(parts)): lastrow = not (col & 1) and",
"a = [regs.alloc() for _ in range(ceil(npart / 2))] yield from blockload(src1, a,",
"r0 and r1 after first re-alloc src1 = SRC1 src2 = SRC2 parts",
"divide into schoolbooks\" # reverse to prioritize low registers (as these have 16-bit",
">= 11: src2 = regs.alloc() yield f\"ldr {src2}, [sp, #0]\" b_offset += 2",
"0 a_offset = 0 b_offset = 0 def blockload(addr, regs, n, offset=0): for",
"offset}]\" # allocate registers for a and b a = [regs.alloc() for _",
"we need to divide neatly into schoolbook blocks # for n <= 12,",
"<= 12, it's simply one schoolbook # for 12 < n <= 24,",
"need to be r0 and r1 after first re-alloc src1 = SRC1 src2",
"and DEST allocated regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST) # these can be flexible, do not",
"< n <= 24, we divide into 2x2 schoolbooks (so require even n)",
"#4]\" if col & 1: # for odd columns, go 'back up' instead",
"3x3 schoolbooks (so require n % 3 == 0) # etc. assert n",
"offset=0): for i, r in enumerate(regs): # if it's the last coefficient for",
"#0]\" regs.free(src2) regs.free(*set(a)) regs.free(*set(b)) if npart >= 11: yield f\"pop {{{SRC2}}}\" yield f\"pop",
"n, offset=0): for i, r in enumerate(regs): # if it's the last coefficient",
"_ in range(ceil(npart / 2))] yield from blockload(src2, b, npart, b_offset) if npart",
"b, npart, b_offset) if npart >= 11: yield f\"push {{{src2}}}\" regs.free(src2) initialized =",
"import schoolbook_inner, Registers, schoolbook_postprocess import sys def schoolbook_medium(SRC1, SRC2, DEST, n): parts =",
"blockload(addr, regs, n, offset=0): for i, r in enumerate(regs): # if it's the",
"4096 (i.e. n shouldnt be huge) dest_offset = 0 a_offset = 0 b_offset",
"* npart yield from blockload(src1, a, npart, a_offset) if npart >= 11: yield",
"it's simply one schoolbook # for 12 < n <= 24, we divide",
"parts = ceil(n / 12) npart = ceil(n / parts) instructions = schoolbook_even_medium(SRC1,",
"n % 3 == 0) # etc. assert n % ceil(n / 12)",
"schoolbook_medium(SRC1, SRC2, DEST, n): parts = ceil(n / 12) npart = ceil(n /",
"SRC2, DEST, n): # the idea here is that we need to divide",
"one extra after repacking b = [regs.alloc() for _ in range(ceil(npart / 2))]",
"need to divide neatly into schoolbook blocks # for n <= 12, it's",
"range(ceil(npart / 2))] yield from blockload(src1, a, npart, a_offset) if npart >= 11:",
"last coefficient for odd n, load only one halfword if i == n",
"lastrow, dest_offset=dest_offset) if col & 1: # for odd columns, go 'back up'",
"prioritize low registers (as these have 16-bit loads) regs = Registers(reversed([f'r{i}' for i",
"11: yield f\"str {src2}, [sp, #0]\" regs.free(src2) regs.free(*set(a)) regs.free(*set(b)) if npart >= 11:",
"b, DEST, regs, initialized, restore_b=not lastrow, dest_offset=dest_offset) if col & 1: # for",
"regs.free(src1) if col == parts-1: # if it's the last part, don't load",
"schoolbooks (so require n % 3 == 0) # etc. assert n %",
"from blockload(src2, b, npart, b_offset) if npart >= 11: yield f\"str {src2}, [sp,",
"* npart else: a_offset += 2 * npart yield from blockload(src1, a, npart,",
"new src2 inputs continue if npart >= 11: src2 = regs.alloc() yield f\"ldr",
"up' instead of down a_offset -= 2 * npart else: a_offset += 2",
"for some n there's one extra after repacking b = [regs.alloc() for _",
"= schoolbook_even_medium(SRC1, SRC2, DEST, npart * parts) yield from schoolbook_postprocess(SRC1, SRC2, DEST, instructions,",
"(so require n % 3 == 0) # etc. assert n % ceil(n",
"stack_src=True) def schoolbook_even_medium(SRC1, SRC2, DEST, n): # the idea here is that we",
"yield f\"ldr {r}, [{addr}, #{i * 4 + offset}]\" # allocate registers for",
"i in range(0, 13)] + [\"r14\"])) # consider SRC1, SRC2 and DEST allocated",
"0 def blockload(addr, regs, n, offset=0): for i, r in enumerate(regs): # if",
"re-alloc src1 = SRC1 src2 = SRC2 parts = ceil(n / 12) npart",
"odd n, load only one halfword if i == n // 2 and",
"yield from blockload(src1, a, npart, a_offset) if npart >= 11: # we cannot",
"of down dest_offset -= 2 * npart else: dest_offset += 2 * npart",
"npart * parts) yield from schoolbook_postprocess(SRC1, SRC2, DEST, instructions, n, stack_src=True) def schoolbook_even_medium(SRC1,",
"instead of down a_offset -= 2 * npart else: a_offset += 2 *",
"2))] yield from blockload(src1, a, npart, a_offset) if npart >= 11: # we",
"these can be flexible, do not need to be r0 and r1 after",
"2 * npart else: dest_offset += 2 * npart # if it's the",
"be r0 and r1 after first re-alloc src1 = SRC1 src2 = SRC2",
"shouldnt be huge) dest_offset = 0 a_offset = 0 b_offset = 0 def",
"DEST, regs, initialized, restore_b=not lastrow, dest_offset=dest_offset) if col & 1: # for odd",
"allocate registers for a and b a = [regs.alloc() for _ in range(ceil(npart",
"DEST, npart * parts) yield from schoolbook_postprocess(SRC1, SRC2, DEST, instructions, n, stack_src=True) def",
"ceil from .common import schoolbook_inner, Registers, schoolbook_postprocess import sys def schoolbook_medium(SRC1, SRC2, DEST,",
"= SRC2 parts = ceil(n / 12) npart = n // parts #",
"from blockload(src2, b, npart, b_offset) if npart >= 11: yield f\"push {{{src2}}}\" regs.free(src2)",
"== parts-1 or (col & 1) and row == 0 yield from schoolbook_inner(npart,",
"into 2x2 schoolbooks (so require even n) # for 24 < n <=",
"consider SRC1, SRC2 and DEST allocated regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST) # these can be",
"parts) instructions = schoolbook_even_medium(SRC1, SRC2, DEST, npart * parts) yield from schoolbook_postprocess(SRC1, SRC2,",
"for 24 < n <= 36, we divide into 3x3 schoolbooks (so require",
"yield from schoolbook_inner(npart, a, b, DEST, regs, initialized, restore_b=not lastrow, dest_offset=dest_offset) if col",
"# if it's the last part in this col, don't load new src1",
"regs.free(src2) initialized = set() for col in range(parts): for row in (range(parts -",
"for i, r in enumerate(regs): # if it's the last coefficient for odd",
"0: # if we just finished a back-and-forth dest_offset += 2 * 2",
"n): parts = ceil(n / 12) npart = ceil(n / parts) instructions =",
"col & 1 else range(parts)): lastrow = not (col & 1) and row",
"inputs if lastrow: if row == 0: # if we just finished a",
"// 2 and n & 1: yield f\"ldrh {r}, [{addr}, #{i * 4",
"{src2}, [sp, #0]\" b_offset += 2 * npart regs.free(*set(b)) # free; for some",
">= 11: yield f\"push {{{src2}}}\" regs.free(src2) initialized = set() for col in range(parts):",
"for col in range(parts): for row in (range(parts - 1, -1, -1) if",
"<reponame>Dia-B/polymul-z2mx-m4<filename>schoolbooks/schoolbook_even_medium.py from math import ceil from .common import schoolbook_inner, Registers, schoolbook_postprocess import sys",
"b a = [regs.alloc() for _ in range(ceil(npart / 2))] yield from blockload(src1,",
"for i in range(0, 13)] + [\"r14\"])) # consider SRC1, SRC2 and DEST",
"regs.free(src1) b = [regs.alloc() for _ in range(ceil(npart / 2))] yield from blockload(src2,",
"n) # for 24 < n <= 36, we divide into 3x3 schoolbooks",
"of down a_offset -= 2 * npart else: a_offset += 2 * npart",
"regs.alloc(DEST) # these can be flexible, do not need to be r0 and",
"from .common import schoolbook_inner, Registers, schoolbook_postprocess import sys def schoolbook_medium(SRC1, SRC2, DEST, n):",
"instructions, n, stack_src=True) def schoolbook_even_medium(SRC1, SRC2, DEST, n): # the idea here is",
"huge) dest_offset = 0 a_offset = 0 b_offset = 0 def blockload(addr, regs,",
"[regs.alloc() for _ in range(ceil(npart / 2))] yield from blockload(src2, b, npart, b_offset)",
"cannot afford to keep these pointers around yield f\"push {{{src1}}}\" regs.free(src1) b =",
"in range(ceil(npart / 2))] yield from blockload(src2, b, npart, b_offset) if npart >=",
"* npart continue if npart >= 11: src1 = regs.alloc() yield f\"ldr {src1},",
"\"Can only handle n that divide into schoolbooks\" # reverse to prioritize low",
"regs, n, offset=0): for i, r in enumerate(regs): # if it's the last",
"around yield f\"push {{{src1}}}\" regs.free(src1) b = [regs.alloc() for _ in range(ceil(npart /",
">= 11: yield f\"str {src2}, [sp, #0]\" regs.free(src2) regs.free(*set(a)) regs.free(*set(b)) if npart >=",
"restore_b=not lastrow, dest_offset=dest_offset) if col & 1: # for odd columns, go 'back",
"== 0, \"Can only handle n that divide into schoolbooks\" # reverse to",
"2))] yield from blockload(src2, b, npart, b_offset) if npart >= 11: yield f\"push",
"offset}]\" else: yield f\"ldr {r}, [{addr}, #{i * 4 + offset}]\" # allocate",
"= ceil(n / 12) npart = ceil(n / parts) instructions = schoolbook_even_medium(SRC1, SRC2,",
"2 and n & 1: yield f\"ldrh {r}, [{addr}, #{i * 4 +",
"& 1: yield f\"ldrh {r}, [{addr}, #{i * 4 + offset}]\" else: yield",
"{r}, [{addr}, #{i * 4 + offset}]\" else: yield f\"ldr {r}, [{addr}, #{i",
"these have 16-bit loads) regs = Registers(reversed([f'r{i}' for i in range(0, 13)] +",
"import ceil from .common import schoolbook_inner, Registers, schoolbook_postprocess import sys def schoolbook_medium(SRC1, SRC2,",
"parts-1 or (col & 1) and row == 0 yield from schoolbook_inner(npart, a,",
"a, b, DEST, regs, initialized, restore_b=not lastrow, dest_offset=dest_offset) if col & 1: #",
"n & 1: yield f\"ldrh {r}, [{addr}, #{i * 4 + offset}]\" else:",
"#4]\" regs.free(src1) if col == parts-1: # if it's the last part, don't",
"npart else: dest_offset += 2 * npart # if it's the last part",
"schoolbook_inner(npart, a, b, DEST, regs, initialized, restore_b=not lastrow, dest_offset=dest_offset) if col & 1:",
"row == 0: # if we just finished a back-and-forth dest_offset += 2",
"sys def schoolbook_medium(SRC1, SRC2, DEST, n): parts = ceil(n / 12) npart =",
"divide into 2x2 schoolbooks (so require even n) # for 24 < n",
"24 < n <= 36, we divide into 3x3 schoolbooks (so require n",
"'back up' instead of down dest_offset -= 2 * npart else: dest_offset +=",
"if npart >= 11: yield f\"str {src2}, [sp, #0]\" regs.free(src2) regs.free(*set(a)) regs.free(*set(b)) if",
"keep these pointers around yield f\"push {{{src1}}}\" regs.free(src1) b = [regs.alloc() for _",
"load new src2 inputs continue if npart >= 11: src2 = regs.alloc() yield",
"(col & 1) and row == parts-1 or (col & 1) and row",
"these offsets shouldnt exceed 4096 (i.e. n shouldnt be huge) dest_offset = 0",
"in this col, don't load new src1 inputs if lastrow: if row ==",
"1, -1, -1) if col & 1 else range(parts)): lastrow = not (col",
"odd columns, go 'back up' instead of down a_offset -= 2 * npart",
"these pointers around yield f\"push {{{src1}}}\" regs.free(src1) b = [regs.alloc() for _ in",
"if lastrow: if row == 0: # if we just finished a back-and-forth",
"(as these have 16-bit loads) regs = Registers(reversed([f'r{i}' for i in range(0, 13)]",
"the idea here is that we need to divide neatly into schoolbook blocks",
"and row == 0 yield from schoolbook_inner(npart, a, b, DEST, regs, initialized, restore_b=not",
"coefficient for odd n, load only one halfword if i == n //",
"one schoolbook # for 12 < n <= 24, we divide into 2x2",
"blockload(src2, b, npart, b_offset) if npart >= 11: yield f\"push {{{src2}}}\" regs.free(src2) initialized",
"npart continue if npart >= 11: src1 = regs.alloc() yield f\"ldr {src1}, [sp,",
"regs.alloc(SRC2) regs.alloc(DEST) # these can be flexible, do not need to be r0",
"-1) if col & 1 else range(parts)): lastrow = not (col & 1)",
"SRC2, DEST, n): parts = ceil(n / 12) npart = ceil(n / parts)",
"regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST) # these can be flexible, do not need to be",
"= SRC1 src2 = SRC2 parts = ceil(n / 12) npart = n",
"= 0 a_offset = 0 b_offset = 0 def blockload(addr, regs, n, offset=0):",
"we cannot afford to keep these pointers around yield f\"push {{{src1}}}\" regs.free(src1) b",
"npart >= 11: src2 = regs.alloc() yield f\"ldr {src2}, [sp, #0]\" b_offset +=",
"npart, b_offset) if npart >= 11: yield f\"str {src2}, [sp, #0]\" regs.free(src2) regs.free(*set(a))",
"* npart # if it's the last part in this col, don't load",
"require n % 3 == 0) # etc. assert n % ceil(n /",
"ceil(n / 12) == 0, \"Can only handle n that divide into schoolbooks\"",
"DEST, instructions, n, stack_src=True) def schoolbook_even_medium(SRC1, SRC2, DEST, n): # the idea here",
"pointers around yield f\"push {{{src1}}}\" regs.free(src1) b = [regs.alloc() for _ in range(ceil(npart",
"it's the last coefficient for odd n, load only one halfword if i",
"12) npart = n // parts # note that these offsets shouldnt exceed",
"# note that these offsets shouldnt exceed 4096 (i.e. n shouldnt be huge)",
"import sys def schoolbook_medium(SRC1, SRC2, DEST, n): parts = ceil(n / 12) npart",
"that these offsets shouldnt exceed 4096 (i.e. n shouldnt be huge) dest_offset =",
"f\"str {src2}, [sp, #0]\" regs.free(src2) regs.free(*set(a)) regs.free(*set(b)) if npart >= 11: yield f\"pop",
"n there's one extra after repacking b = [regs.alloc() for _ in range(ceil(npart",
"a, npart, a_offset) if npart >= 11: # we cannot afford to keep",
"parts-1: # if it's the last part, don't load new src2 inputs continue",
"flexible, do not need to be r0 and r1 after first re-alloc src1",
"0, \"Can only handle n that divide into schoolbooks\" # reverse to prioritize",
"== 0) # etc. assert n % ceil(n / 12) == 0, \"Can",
"blockload(src1, a, npart, a_offset) if npart >= 11: yield f\"str {src1}, [sp, #4]\"",
"from schoolbook_inner(npart, a, b, DEST, regs, initialized, restore_b=not lastrow, dest_offset=dest_offset) if col &",
"and row == parts-1 or (col & 1) and row == 0 yield",
"== n // 2 and n & 1: yield f\"ldrh {r}, [{addr}, #{i",
"ceil(n / parts) instructions = schoolbook_even_medium(SRC1, SRC2, DEST, npart * parts) yield from",
"if npart >= 11: # we cannot afford to keep these pointers around",
"after first re-alloc src1 = SRC1 src2 = SRC2 parts = ceil(n /",
"for _ in range(ceil(npart / 2))] yield from blockload(src1, a, npart, a_offset) if",
"/ 12) npart = ceil(n / parts) instructions = schoolbook_even_medium(SRC1, SRC2, DEST, npart",
"13)] + [\"r14\"])) # consider SRC1, SRC2 and DEST allocated regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST)",
"from math import ceil from .common import schoolbook_inner, Registers, schoolbook_postprocess import sys def",
"* npart regs.free(*set(b)) # free; for some n there's one extra after repacking",
"in range(ceil(npart / 2))] yield from blockload(src1, a, npart, a_offset) if npart >=",
"n // parts # note that these offsets shouldnt exceed 4096 (i.e. n",
"if i == n // 2 and n & 1: yield f\"ldrh {r},",
"/ 12) == 0, \"Can only handle n that divide into schoolbooks\" #",
"SRC1, SRC2 and DEST allocated regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST) # these can be flexible,",
"DEST allocated regs.alloc(SRC1) regs.alloc(SRC2) regs.alloc(DEST) # these can be flexible, do not need",
"& 1: # for odd columns, go 'back up' instead of down a_offset",
"shouldnt exceed 4096 (i.e. n shouldnt be huge) dest_offset = 0 a_offset =",
"and r1 after first re-alloc src1 = SRC1 src2 = SRC2 parts =",
"if it's the last part in this col, don't load new src1 inputs",
"finished a back-and-forth dest_offset += 2 * 2 * npart continue if npart",
"b_offset += 2 * npart regs.free(*set(b)) # free; for some n there's one",
"* 2 * npart continue if npart >= 11: src1 = regs.alloc() yield",
"'back up' instead of down a_offset -= 2 * npart else: a_offset +=",
"{r}, [{addr}, #{i * 4 + offset}]\" # allocate registers for a and",
"11: src2 = regs.alloc() yield f\"ldr {src2}, [sp, #0]\" b_offset += 2 *",
"down a_offset -= 2 * npart else: a_offset += 2 * npart yield",
"inputs continue if npart >= 11: src2 = regs.alloc() yield f\"ldr {src2}, [sp,",
"{src2}, [sp, #0]\" regs.free(src2) regs.free(*set(a)) regs.free(*set(b)) if npart >= 11: yield f\"pop {{{SRC2}}}\"",
"# if it's the last part, don't load new src2 inputs continue if",
"2))] yield from blockload(src2, b, npart, b_offset) if npart >= 11: yield f\"str",
"and n & 1: yield f\"ldrh {r}, [{addr}, #{i * 4 + offset}]\"",
"+= 2 * npart # if it's the last part in this col,"
] |
[
"tf.compat.v1.get_variable(name='W1', shape=( layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2 = tf.compat.v1.get_variable(name='W2', shape=( layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3",
"tf.split( item_latent, [embed_dim, layers[0] // 2], 1) mf_vector = tf.multiply(mf_user_latent, mf_item_latent) mlp_vector =",
"shape=( embed_dim + layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'): mf_user_latent, mlp_user_latent = tf.split( user_latent,",
"8 layers = [64, 32, 16, 8] learning_rate = 0.01 with tf.compat.v1.variable_scope('nmf', dtype=tf.float32):",
"layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4 = tf.compat.v1.get_variable(name='W4', shape=( embed_dim + layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'):",
"tf.compat.v1.get_variable(name='W3', shape=( layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4 = tf.compat.v1.get_variable(name='W4', shape=( embed_dim + layers[3], 1),",
"// 2], 1) mf_item_latent, mlp_item_latent = tf.split( item_latent, [embed_dim, layers[0] // 2], 1)",
"W3 = tf.compat.v1.get_variable(name='W3', shape=( layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4 = tf.compat.v1.get_variable(name='W4', shape=( embed_dim +",
"relu1 = tf.nn.relu(fc1) fc2 = tf.matmul(relu1, W2) relu2 = tf.nn.relu(fc2) fc3 = tf.matmul(relu2,",
"0.01 with tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with tf.device('/cpu:0'): User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users, embed_dim +",
"layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'): mf_user_latent, mlp_user_latent = tf.split( user_latent, [embed_dim, layers[0] //",
"= tf.multiply(mf_user_latent, mf_item_latent) mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent), 1) fc1 = tf.matmul(mlp_vector, W1) relu1",
"mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent), 1) fc1 = tf.matmul(mlp_vector, W1) relu1 = tf.nn.relu(fc1) fc2",
"initializer=tf.random_normal_initializer(stddev=0.1)) W4 = tf.compat.v1.get_variable(name='W4', shape=( embed_dim + layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'): mf_user_latent,",
"import tensorflow as tf def neural_mf(user_input, item_input, y_, num_users, num_items, embed_partitioner=None): embed_dim =",
"= tf.compat.v1.get_variable(name='W3', shape=( layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4 = tf.compat.v1.get_variable(name='W4', shape=( embed_dim + layers[3],",
"Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent",
"def neural_mf(user_input, item_input, y_, num_users, num_items, embed_partitioner=None): embed_dim = 8 layers = [64,",
"= tf.nn.embedding_lookup(User_Embedding, user_input) item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input) W1 = tf.compat.v1.get_variable(name='W1', shape=( layers[0], layers[1]),",
"tf.nn.relu(fc2) fc3 = tf.matmul(relu2, W3) relu3 = tf.nn.relu(fc3) concat_vector = tf.concat((mf_vector, relu3), 1)",
"item_input, y_, num_users, num_items, embed_partitioner=None): embed_dim = 8 layers = [64, 32, 16,",
"+ layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items, embed_dim +",
"partitioner=embed_partitioner) user_latent = tf.nn.embedding_lookup(User_Embedding, user_input) item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input) W1 = tf.compat.v1.get_variable(name='W1', shape=(",
"= tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding =",
"tf.reshape(tf.matmul(concat_vector, W4), (-1,)) loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss = tf.reduce_mean(loss) y = tf.sigmoid(y)",
"tensorflow as tf def neural_mf(user_input, item_input, y_, num_users, num_items, embed_partitioner=None): embed_dim = 8",
"// 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent = tf.nn.embedding_lookup(User_Embedding, user_input) item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input) W1",
"y = tf.reshape(tf.matmul(concat_vector, W4), (-1,)) loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss = tf.reduce_mean(loss) y",
"= tf.reshape(tf.matmul(concat_vector, W4), (-1,)) loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss = tf.reduce_mean(loss) y =",
"[embed_dim, layers[0] // 2], 1) mf_vector = tf.multiply(mf_user_latent, mf_item_latent) mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent),",
"= tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss = tf.reduce_mean(loss) y = tf.sigmoid(y) optimizer = tf.compat.v1.train.GradientDescentOptimizer( learning_rate)",
"layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2 = tf.compat.v1.get_variable(name='W2', shape=( layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3 = tf.compat.v1.get_variable(name='W3',",
"item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input) W1 = tf.compat.v1.get_variable(name='W1', shape=( layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2 =",
"mf_user_latent, mlp_user_latent = tf.split( user_latent, [embed_dim, layers[0] // 2], 1) mf_item_latent, mlp_item_latent =",
"mlp_user_latent = tf.split( user_latent, [embed_dim, layers[0] // 2], 1) mf_item_latent, mlp_item_latent = tf.split(",
"= tf.split( user_latent, [embed_dim, layers[0] // 2], 1) mf_item_latent, mlp_item_latent = tf.split( item_latent,",
"layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4 = tf.compat.v1.get_variable(name='W4', shape=( embed_dim + layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1)) with",
"mf_vector = tf.multiply(mf_user_latent, mf_item_latent) mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent), 1) fc1 = tf.matmul(mlp_vector, W1)",
"layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items, embed_dim + layers[0]",
"tf.device('/cpu:0'): User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner)",
"tf.device('/gpu:0'): mf_user_latent, mlp_user_latent = tf.split( user_latent, [embed_dim, layers[0] // 2], 1) mf_item_latent, mlp_item_latent",
"shape=( layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2 = tf.compat.v1.get_variable(name='W2', shape=( layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3 =",
"tf.compat.v1.get_variable(name='W2', shape=( layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3 = tf.compat.v1.get_variable(name='W3', shape=( layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4",
"tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\",",
"item_latent, [embed_dim, layers[0] // 2], 1) mf_vector = tf.multiply(mf_user_latent, mf_item_latent) mlp_vector = tf.concat((mlp_user_latent,",
"tf.matmul(relu2, W3) relu3 = tf.nn.relu(fc3) concat_vector = tf.concat((mf_vector, relu3), 1) y = tf.reshape(tf.matmul(concat_vector,",
"1) fc1 = tf.matmul(mlp_vector, W1) relu1 = tf.nn.relu(fc1) fc2 = tf.matmul(relu1, W2) relu2",
"with tf.device('/gpu:0'): mf_user_latent, mlp_user_latent = tf.split( user_latent, [embed_dim, layers[0] // 2], 1) mf_item_latent,",
"tf.concat((mlp_user_latent, mlp_item_latent), 1) fc1 = tf.matmul(mlp_vector, W1) relu1 = tf.nn.relu(fc1) fc2 = tf.matmul(relu1,",
"tf def neural_mf(user_input, item_input, y_, num_users, num_items, embed_partitioner=None): embed_dim = 8 layers =",
"mlp_item_latent), 1) fc1 = tf.matmul(mlp_vector, W1) relu1 = tf.nn.relu(fc1) fc2 = tf.matmul(relu1, W2)",
"= tf.compat.v1.get_variable(name='W4', shape=( embed_dim + layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'): mf_user_latent, mlp_user_latent =",
"user_input) item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input) W1 = tf.compat.v1.get_variable(name='W1', shape=( layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2",
"tf.nn.relu(fc1) fc2 = tf.matmul(relu1, W2) relu2 = tf.nn.relu(fc2) fc3 = tf.matmul(relu2, W3) relu3",
"W1) relu1 = tf.nn.relu(fc1) fc2 = tf.matmul(relu1, W2) relu2 = tf.nn.relu(fc2) fc3 =",
"W2) relu2 = tf.nn.relu(fc2) fc3 = tf.matmul(relu2, W3) relu3 = tf.nn.relu(fc3) concat_vector =",
"tf.nn.embedding_lookup(User_Embedding, user_input) item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input) W1 = tf.compat.v1.get_variable(name='W1', shape=( layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1))",
"item_input) W1 = tf.compat.v1.get_variable(name='W1', shape=( layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2 = tf.compat.v1.get_variable(name='W2', shape=( layers[1],",
"user_latent = tf.nn.embedding_lookup(User_Embedding, user_input) item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input) W1 = tf.compat.v1.get_variable(name='W1', shape=( layers[0],",
"tf.nn.relu(fc3) concat_vector = tf.concat((mf_vector, relu3), 1) y = tf.reshape(tf.matmul(concat_vector, W4), (-1,)) loss =",
"initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01),",
"num_items, embed_partitioner=None): embed_dim = 8 layers = [64, 32, 16, 8] learning_rate =",
"tf.multiply(mf_user_latent, mf_item_latent) mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent), 1) fc1 = tf.matmul(mlp_vector, W1) relu1 =",
"16, 8] learning_rate = 0.01 with tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with tf.device('/cpu:0'): User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\",",
"= tf.concat((mf_vector, relu3), 1) y = tf.reshape(tf.matmul(concat_vector, W4), (-1,)) loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_)",
"labels=y_) loss = tf.reduce_mean(loss) y = tf.sigmoid(y) optimizer = tf.compat.v1.train.GradientDescentOptimizer( learning_rate) return loss,",
"= tf.matmul(relu1, W2) relu2 = tf.nn.relu(fc2) fc3 = tf.matmul(relu2, W3) relu3 = tf.nn.relu(fc3)",
"shape=( layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3 = tf.compat.v1.get_variable(name='W3', shape=( layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4 =",
"tf.concat((mf_vector, relu3), 1) y = tf.reshape(tf.matmul(concat_vector, W4), (-1,)) loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss",
"= tf.nn.relu(fc2) fc3 = tf.matmul(relu2, W3) relu3 = tf.nn.relu(fc3) concat_vector = tf.concat((mf_vector, relu3),",
"= tf.matmul(relu2, W3) relu3 = tf.nn.relu(fc3) concat_vector = tf.concat((mf_vector, relu3), 1) y =",
"1) y = tf.reshape(tf.matmul(concat_vector, W4), (-1,)) loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss = tf.reduce_mean(loss)",
"W2 = tf.compat.v1.get_variable(name='W2', shape=( layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3 = tf.compat.v1.get_variable(name='W3', shape=( layers[2], layers[3]),",
"with tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with tf.device('/cpu:0'): User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users, embed_dim + layers[0]",
"embed_partitioner=None): embed_dim = 8 layers = [64, 32, 16, 8] learning_rate = 0.01",
"W3) relu3 = tf.nn.relu(fc3) concat_vector = tf.concat((mf_vector, relu3), 1) y = tf.reshape(tf.matmul(concat_vector, W4),",
"num_users, num_items, embed_partitioner=None): embed_dim = 8 layers = [64, 32, 16, 8] learning_rate",
"tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss = tf.reduce_mean(loss) y = tf.sigmoid(y) optimizer = tf.compat.v1.train.GradientDescentOptimizer( learning_rate) return",
"layers[0] // 2], 1) mf_item_latent, mlp_item_latent = tf.split( item_latent, [embed_dim, layers[0] // 2],",
"2], 1) mf_vector = tf.multiply(mf_user_latent, mf_item_latent) mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent), 1) fc1 =",
"layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent = tf.nn.embedding_lookup(User_Embedding, user_input) item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input)",
"= tf.nn.relu(fc1) fc2 = tf.matmul(relu1, W2) relu2 = tf.nn.relu(fc2) fc3 = tf.matmul(relu2, W3)",
"relu2 = tf.nn.relu(fc2) fc3 = tf.matmul(relu2, W3) relu3 = tf.nn.relu(fc3) concat_vector = tf.concat((mf_vector,",
"concat_vector = tf.concat((mf_vector, relu3), 1) y = tf.reshape(tf.matmul(concat_vector, W4), (-1,)) loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y,",
"loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss = tf.reduce_mean(loss) y = tf.sigmoid(y) optimizer = tf.compat.v1.train.GradientDescentOptimizer(",
"tf.nn.embedding_lookup(Item_Embedding, item_input) W1 = tf.compat.v1.get_variable(name='W1', shape=( layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2 = tf.compat.v1.get_variable(name='W2', shape=(",
"neural_mf(user_input, item_input, y_, num_users, num_items, embed_partitioner=None): embed_dim = 8 layers = [64, 32,",
"32, 16, 8] learning_rate = 0.01 with tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with tf.device('/cpu:0'): User_Embedding =",
"1) mf_vector = tf.multiply(mf_user_latent, mf_item_latent) mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent), 1) fc1 = tf.matmul(mlp_vector,",
"fc1 = tf.matmul(mlp_vector, W1) relu1 = tf.nn.relu(fc1) fc2 = tf.matmul(relu1, W2) relu2 =",
"initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent = tf.nn.embedding_lookup(User_Embedding, user_input) item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input) W1 = tf.compat.v1.get_variable(name='W1',",
"1) mf_item_latent, mlp_item_latent = tf.split( item_latent, [embed_dim, layers[0] // 2], 1) mf_vector =",
"tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with tf.device('/cpu:0'): User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users, embed_dim + layers[0] //",
"= tf.compat.v1.get_variable(name='W1', shape=( layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2 = tf.compat.v1.get_variable(name='W2', shape=( layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1))",
"= tf.split( item_latent, [embed_dim, layers[0] // 2], 1) mf_vector = tf.multiply(mf_user_latent, mf_item_latent) mlp_vector",
"as tf def neural_mf(user_input, item_input, y_, num_users, num_items, embed_partitioner=None): embed_dim = 8 layers",
"embed_dim + layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'): mf_user_latent, mlp_user_latent = tf.split( user_latent, [embed_dim,",
"+ layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'): mf_user_latent, mlp_user_latent = tf.split( user_latent, [embed_dim, layers[0]",
"W1 = tf.compat.v1.get_variable(name='W1', shape=( layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2 = tf.compat.v1.get_variable(name='W2', shape=( layers[1], layers[2]),",
"2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent = tf.nn.embedding_lookup(User_Embedding, user_input) item_latent = tf.nn.embedding_lookup(Item_Embedding, item_input) W1 =",
"with tf.device('/cpu:0'): User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01),",
"tf.compat.v1.get_variable(name='W4', shape=( embed_dim + layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'): mf_user_latent, mlp_user_latent = tf.split(",
"W4 = tf.compat.v1.get_variable(name='W4', shape=( embed_dim + layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'): mf_user_latent, mlp_user_latent",
"initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'): mf_user_latent, mlp_user_latent = tf.split( user_latent, [embed_dim, layers[0] // 2], 1)",
"= tf.nn.embedding_lookup(Item_Embedding, item_input) W1 = tf.compat.v1.get_variable(name='W1', shape=( layers[0], layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2 = tf.compat.v1.get_variable(name='W2',",
"mf_item_latent) mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent), 1) fc1 = tf.matmul(mlp_vector, W1) relu1 = tf.nn.relu(fc1)",
"= tf.compat.v1.get_variable(name='W2', shape=( layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3 = tf.compat.v1.get_variable(name='W3', shape=( layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1))",
"num_items, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent = tf.nn.embedding_lookup(User_Embedding, user_input) item_latent",
"User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding",
"shape=( num_users, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\", shape=(",
"= 0.01 with tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with tf.device('/cpu:0'): User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users, embed_dim",
"layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3 = tf.compat.v1.get_variable(name='W3', shape=( layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4 = tf.compat.v1.get_variable(name='W4', shape=(",
"loss = tf.reduce_mean(loss) y = tf.sigmoid(y) optimizer = tf.compat.v1.train.GradientDescentOptimizer( learning_rate) return loss, y,",
"[64, 32, 16, 8] learning_rate = 0.01 with tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with tf.device('/cpu:0'): User_Embedding",
"= tf.concat((mlp_user_latent, mlp_item_latent), 1) fc1 = tf.matmul(mlp_vector, W1) relu1 = tf.nn.relu(fc1) fc2 =",
"shape=( num_items, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent = tf.nn.embedding_lookup(User_Embedding, user_input)",
"initializer=tf.random_normal_initializer(stddev=0.1)) W2 = tf.compat.v1.get_variable(name='W2', shape=( layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3 = tf.compat.v1.get_variable(name='W3', shape=( layers[2],",
"tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent = tf.nn.embedding_lookup(User_Embedding,",
"// 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items, embed_dim + layers[0] //",
"shape=( layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4 = tf.compat.v1.get_variable(name='W4', shape=( embed_dim + layers[3], 1), initializer=tf.random_normal_initializer(stddev=0.1))",
"learning_rate = 0.01 with tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with tf.device('/cpu:0'): User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users,",
"W4), (-1,)) loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss = tf.reduce_mean(loss) y = tf.sigmoid(y) optimizer",
"// 2], 1) mf_vector = tf.multiply(mf_user_latent, mf_item_latent) mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent), 1) fc1",
"= 8 layers = [64, 32, 16, 8] learning_rate = 0.01 with tf.compat.v1.variable_scope('nmf',",
"layers[1]), initializer=tf.random_normal_initializer(stddev=0.1)) W2 = tf.compat.v1.get_variable(name='W2', shape=( layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3 = tf.compat.v1.get_variable(name='W3', shape=(",
"= tf.matmul(mlp_vector, W1) relu1 = tf.nn.relu(fc1) fc2 = tf.matmul(relu1, W2) relu2 = tf.nn.relu(fc2)",
"relu3), 1) y = tf.reshape(tf.matmul(concat_vector, W4), (-1,)) loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss =",
"[embed_dim, layers[0] // 2], 1) mf_item_latent, mlp_item_latent = tf.split( item_latent, [embed_dim, layers[0] //",
"embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent = tf.nn.embedding_lookup(User_Embedding, user_input) item_latent =",
"= tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent =",
"= tf.reduce_mean(loss) y = tf.sigmoid(y) optimizer = tf.compat.v1.train.GradientDescentOptimizer( learning_rate) return loss, y, optimizer",
"+ layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) user_latent = tf.nn.embedding_lookup(User_Embedding, user_input) item_latent = tf.nn.embedding_lookup(Item_Embedding,",
"embed_dim = 8 layers = [64, 32, 16, 8] learning_rate = 0.01 with",
"(-1,)) loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=y, labels=y_) loss = tf.reduce_mean(loss) y = tf.sigmoid(y) optimizer =",
"1), initializer=tf.random_normal_initializer(stddev=0.1)) with tf.device('/gpu:0'): mf_user_latent, mlp_user_latent = tf.split( user_latent, [embed_dim, layers[0] // 2],",
"partitioner=embed_partitioner) Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner)",
"dtype=tf.float32): with tf.device('/cpu:0'): User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\", shape=( num_users, embed_dim + layers[0] // 2),",
"mf_item_latent, mlp_item_latent = tf.split( item_latent, [embed_dim, layers[0] // 2], 1) mf_vector = tf.multiply(mf_user_latent,",
"initializer=tf.random_normal_initializer(stddev=0.1)) W3 = tf.compat.v1.get_variable(name='W3', shape=( layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4 = tf.compat.v1.get_variable(name='W4', shape=( embed_dim",
"tf.matmul(mlp_vector, W1) relu1 = tf.nn.relu(fc1) fc2 = tf.matmul(relu1, W2) relu2 = tf.nn.relu(fc2) fc3",
"layers[0] // 2], 1) mf_vector = tf.multiply(mf_user_latent, mf_item_latent) mlp_vector = tf.concat((mlp_user_latent, mlp_item_latent), 1)",
"layers[1], layers[2]), initializer=tf.random_normal_initializer(stddev=0.1)) W3 = tf.compat.v1.get_variable(name='W3', shape=( layers[2], layers[3]), initializer=tf.random_normal_initializer(stddev=0.1)) W4 = tf.compat.v1.get_variable(name='W4',",
"fc2 = tf.matmul(relu1, W2) relu2 = tf.nn.relu(fc2) fc3 = tf.matmul(relu2, W3) relu3 =",
"relu3 = tf.nn.relu(fc3) concat_vector = tf.concat((mf_vector, relu3), 1) y = tf.reshape(tf.matmul(concat_vector, W4), (-1,))",
"layers = [64, 32, 16, 8] learning_rate = 0.01 with tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with",
"tf.split( user_latent, [embed_dim, layers[0] // 2], 1) mf_item_latent, mlp_item_latent = tf.split( item_latent, [embed_dim,",
"num_users, embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items,",
"mlp_item_latent = tf.split( item_latent, [embed_dim, layers[0] // 2], 1) mf_vector = tf.multiply(mf_user_latent, mf_item_latent)",
"= tf.nn.relu(fc3) concat_vector = tf.concat((mf_vector, relu3), 1) y = tf.reshape(tf.matmul(concat_vector, W4), (-1,)) loss",
"tf.matmul(relu1, W2) relu2 = tf.nn.relu(fc2) fc3 = tf.matmul(relu2, W3) relu3 = tf.nn.relu(fc3) concat_vector",
"y_, num_users, num_items, embed_partitioner=None): embed_dim = 8 layers = [64, 32, 16, 8]",
"= [64, 32, 16, 8] learning_rate = 0.01 with tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with tf.device('/cpu:0'):",
"user_latent, [embed_dim, layers[0] // 2], 1) mf_item_latent, mlp_item_latent = tf.split( item_latent, [embed_dim, layers[0]",
"fc3 = tf.matmul(relu2, W3) relu3 = tf.nn.relu(fc3) concat_vector = tf.concat((mf_vector, relu3), 1) y",
"8] learning_rate = 0.01 with tf.compat.v1.variable_scope('nmf', dtype=tf.float32): with tf.device('/cpu:0'): User_Embedding = tf.compat.v1.get_variable(name=\"user_embed\", shape=(",
"2], 1) mf_item_latent, mlp_item_latent = tf.split( item_latent, [embed_dim, layers[0] // 2], 1) mf_vector",
"embed_dim + layers[0] // 2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items, embed_dim",
"2), initializer=tf.random_normal_initializer(stddev=0.01), partitioner=embed_partitioner) Item_Embedding = tf.compat.v1.get_variable(name=\"item_embed\", shape=( num_items, embed_dim + layers[0] // 2),"
] |
[
"test_co_occurrence_reproducibility(adata: AnnData, n_jobs: int, n_splits: int): \"\"\"Check co_occurrence reproducibility results.\"\"\" arr_1, interval_1 =",
"are the same for seq. and parallel computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False],",
"reproducibility results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) # seed will work only",
"!= df_1.shape # assert idx are sorted and contain same elements assert not",
"same results with pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\) are different.*'): # because the seeds will",
"to be the same assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1, 2]) def test_moran_reproducibility(dummy_adata: AnnData, n_jobs:",
"assert arr.shape[1] == arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\", \"xs\"), [(10, 10), (None, None),",
"arr.shape[2] == 49 assert arr.shape[1] == arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\", \"xs\"), [(10,",
"arr.shape[1] == arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\", \"xs\"), [(10, 10), (None, None), (10,",
"def test_co_occurrence_reproducibility(adata: AnnData, n_jobs: int, n_splits: int): \"\"\"Check co_occurrence reproducibility results.\"\"\" arr_1, interval_1",
"adata.uns[\"leiden_co_occurrence\"].keys() # assert shapes arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim == 3 assert arr.shape[2]",
"= df.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\" in",
"parallel gives same results with pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\) are different.*'): # because the",
"df_2) def test_co_occurrence(adata: AnnData): \"\"\" check ripley score and shape \"\"\" co_occurrence(adata, cluster_key=\"leiden\")",
"arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\", \"xs\"), [(10, 10), (None, None), (10, 20)]) @pytest.mark.parametrize((\"n_jobs\",",
"df.shape # assert idx are sorted and contain same elements assert not np.array_equal(idx_df,",
"@pytest.mark.parametrize((\"ys\", \"xs\"), [(10, 10), (None, None), (10, 20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1, 2), (2,",
"squidpy.gr import moran, ripley_k, co_occurrence MORAN_K = \"moranI\" def test_ripley_k(adata: AnnData): \"\"\"Check ripley",
"clusters intersection cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata = set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata) is False def",
"= dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape",
"!= df.shape # assert idx are sorted and contain same elements assert not",
"False def test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check whether moran results are the same for seq.",
"will work only when multiprocessing/loky df_1 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) df_2",
"assert idx are sorted and contain same elements assert not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df),",
"sorted(idx_adata)) # check parallel gives same results assert_frame_equal(df_1, df_2) def test_co_occurrence(adata: AnnData): \"\"\"",
"in adata.uns assert \"ripley_k_leiden\" in adata.uns.keys() # assert clusters intersection cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique())",
"highly variable assert dummy_adata.uns[MORAN_K].shape != df.shape # assert idx are sorted and contain",
"test highly variable assert dummy_adata.uns[MORAN_K].shape != df_1.shape # assert idx are sorted and",
"\"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape",
"adata.uns assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable",
"= co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) arr_2, interval_2 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs,",
"check parallel gives same results assert_frame_equal(df_1, df_2) def test_co_occurrence(adata: AnnData): \"\"\" check ripley",
"\"leiden_co_occurrence\" in adata.uns.keys() assert \"occ\" in adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\" in adata.uns[\"leiden_co_occurrence\"].keys() # assert",
"in dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly",
"ripley in adata.uns assert \"ripley_k_leiden\" in adata.uns.keys() # assert clusters intersection cat_ripley =",
"in adata.uns assert \"leiden_co_occurrence\" in adata.uns.keys() assert \"occ\" in adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\" in",
"@pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1, 2), (2, 2)]) def test_co_occurrence_reproducibility(adata: AnnData, n_jobs: int, n_splits: int):",
"adata.uns assert \"leiden_co_occurrence\" in adata.uns.keys() assert \"occ\" in adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\" in adata.uns[\"leiden_co_occurrence\"].keys()",
"n_jobs: int, n_splits: int): \"\"\"Check co_occurrence reproducibility results.\"\"\" arr_1, interval_1 = co_occurrence(adata, cluster_key=\"leiden\",",
"idx_df = df_1.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() # assert",
"check parallel gives same results with pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\) are different.*'): # because",
"idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results with pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\)",
"contain same elements assert not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives",
"int): \"\"\"Check co_occurrence reproducibility results.\"\"\" arr_1, interval_1 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits)",
"idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert",
"will be different, we don't expect the pval_sim values to be the same",
"adata.uns assert \"ripley_k_leiden\" in adata.uns.keys() # assert clusters intersection cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata",
"only when multiprocessing/loky df_1 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) df_2 = moran(dummy_adata,",
"match=r'.*\\(column name=\"pval_sim\"\\) are different.*'): # because the seeds will be different, we don't",
"None), (10, 20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1, 2), (2, 2)]) def test_co_occurrence_reproducibility(adata: AnnData, n_jobs:",
"assert occurrence in adata.uns assert \"leiden_co_occurrence\" in adata.uns.keys() assert \"occ\" in adata.uns[\"leiden_co_occurrence\"].keys() assert",
"assert dummy_adata.uns[MORAN_K].shape != df_1.shape # assert idx are sorted and contain same elements",
"= set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata) is False def test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check whether moran results",
"set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata) is False def test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check whether moran results are",
"df = moran(dummy_adata, copy=True, n_jobs=1, seed=42, n_perms=50) df_parallel = moran(dummy_adata, copy=True, n_jobs=2, seed=42,",
"# check parallel gives same results with pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\) are different.*'): #",
"= moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) idx_df = df_1.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values",
"assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape != df.shape #",
"results with pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\) are different.*'): # because the seeds will be",
"sorted(idx_adata)) # check parallel gives same results with pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\) are different.*'):",
"AnnData, n_jobs: int): \"\"\"Check moran reproducibility results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape)",
"n_jobs=n_jobs, n_splits=n_splits) arr_2, interval_2 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) np.testing.assert_array_equal(sorted(interval_1), sorted(interval_2)) np.testing.assert_allclose(arr_1,",
"idx_df = df.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\"",
"(2, 2)]) def test_co_occurrence_reproducibility(adata: AnnData, n_jobs: int, n_splits: int): \"\"\"Check co_occurrence reproducibility results.\"\"\"",
"= moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) df_2 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50)",
"name=\"pval_sim\"\\) are different.*'): # because the seeds will be different, we don't expect",
"dummy_adata.uns[MORAN_K].shape != df_1.shape # assert idx are sorted and contain same elements assert",
"the same assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1, 2]) def test_moran_reproducibility(dummy_adata: AnnData, n_jobs: int): \"\"\"Check",
"arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim == 3 assert arr.shape[2] == 49 assert arr.shape[1]",
"= dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() # assert fdr correction in adata.uns",
"# assert occurrence in adata.uns assert \"leiden_co_occurrence\" in adata.uns.keys() assert \"occ\" in adata.uns[\"leiden_co_occurrence\"].keys()",
"interval_1 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) arr_2, interval_2 = co_occurrence(adata, cluster_key=\"leiden\", copy=True,",
"assert MORAN_K in dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) #",
"\"\"\" co_occurrence(adata, cluster_key=\"leiden\") # assert occurrence in adata.uns assert \"leiden_co_occurrence\" in adata.uns.keys() assert",
"multiprocessing/loky df_1 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) df_2 = moran(dummy_adata, copy=True, n_jobs=n_jobs,",
"\"ripley_k_leiden\" in adata.uns.keys() # assert clusters intersection cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata = set(adata.obs[\"leiden\"].cat.categories)",
"dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,)",
"False], size=dummy_adata.var_names.shape) df = moran(dummy_adata, copy=True, n_jobs=1, seed=42, n_perms=50) df_parallel = moran(dummy_adata, copy=True,",
"the pval_sim values to be the same assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1, 2]) def",
"ripley score and shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\") # assert ripley in adata.uns assert \"ripley_k_leiden\"",
"when multiprocessing/loky df_1 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) df_2 = moran(dummy_adata, copy=True,",
"n_jobs=2, seed=42, n_perms=50) idx_df = df.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in",
"assert_frame_equal(df_1, df_2) def test_co_occurrence(adata: AnnData): \"\"\" check ripley score and shape \"\"\" co_occurrence(adata,",
"parallel computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) df = moran(dummy_adata, copy=True, n_jobs=1,",
"np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results assert_frame_equal(df_1, df_2) def",
"co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) arr_2, interval_2 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits)",
"in adata.uns.keys() # assert clusters intersection cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata = set(adata.obs[\"leiden\"].cat.categories) assert",
"AnnData): \"\"\"Check ripley score and shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\") # assert ripley in adata.uns",
"\"n_splits\"), [(1, 2), (2, 2)]) def test_co_occurrence_reproducibility(adata: AnnData, n_jobs: int, n_splits: int): \"\"\"Check",
"n_splits=n_splits) arr_2, interval_2 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) np.testing.assert_array_equal(sorted(interval_1), sorted(interval_2)) np.testing.assert_allclose(arr_1, arr_2)",
"parallel gives same results assert_frame_equal(df_1, df_2) def test_co_occurrence(adata: AnnData): \"\"\" check ripley score",
"is False def test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check whether moran results are the same for",
"copy=True, n_jobs=n_jobs, n_splits=n_splits) arr_2, interval_2 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) np.testing.assert_array_equal(sorted(interval_1), sorted(interval_2))",
"\"occ\" in adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\" in adata.uns[\"leiden_co_occurrence\"].keys() # assert shapes arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"]",
"adata.uns.keys() # assert clusters intersection cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata = set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata)",
"df_2 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) idx_df = df_1.index.values idx_adata = dummy_adata[:,",
"in dummy_adata.uns.keys() # assert fdr correction in adata.uns assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert",
"fdr correction in adata.uns assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) #",
"cluster_key=\"leiden\") # assert occurrence in adata.uns assert \"leiden_co_occurrence\" in adata.uns.keys() assert \"occ\" in",
"adata.uns.keys() assert \"occ\" in adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\" in adata.uns[\"leiden_co_occurrence\"].keys() # assert shapes arr",
"ripley score and shape \"\"\" co_occurrence(adata, cluster_key=\"leiden\") # assert occurrence in adata.uns assert",
"def test_co_occurrence(adata: AnnData): \"\"\" check ripley score and shape \"\"\" co_occurrence(adata, cluster_key=\"leiden\") #",
"n_perms=50) idx_df = df.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() assert",
"= set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata = set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata) is False def test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check",
"and parallel computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) df = moran(dummy_adata, copy=True,",
"results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) # seed will work only when",
"dummy_adata.uns.keys() # assert fdr correction in adata.uns assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape",
"results are the same for seq. and parallel computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True,",
"n_perms=50) df_2 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) idx_df = df_1.index.values idx_adata =",
"dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable",
"in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape !=",
"n_jobs: int): \"\"\"Check moran reproducibility results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) #",
"MORAN_K in dummy_adata.uns.keys() # assert fdr correction in adata.uns assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K]",
"check ripley score and shape \"\"\" co_occurrence(adata, cluster_key=\"leiden\") # assert occurrence in adata.uns",
"df_1.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() # assert fdr correction",
"AnnData): \"\"\" check ripley score and shape \"\"\" co_occurrence(adata, cluster_key=\"leiden\") # assert occurrence",
"correction in adata.uns assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test",
"set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata = set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata) is False def test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check whether",
"3 assert arr.shape[2] == 49 assert arr.shape[1] == arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\",",
"10), (None, None), (10, 20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1, 2), (2, 2)]) def test_co_occurrence_reproducibility(adata:",
"df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1, 2]) def test_moran_reproducibility(dummy_adata: AnnData, n_jobs: int): \"\"\"Check moran reproducibility results.\"\"\"",
"import moran, ripley_k, co_occurrence MORAN_K = \"moranI\" def test_ripley_k(adata: AnnData): \"\"\"Check ripley score",
"np.random.choice([True, False], size=dummy_adata.var_names.shape) df = moran(dummy_adata, copy=True, n_jobs=1, seed=42, n_perms=50) df_parallel = moran(dummy_adata,",
"results assert_frame_equal(df_1, df_2) def test_co_occurrence(adata: AnnData): \"\"\" check ripley score and shape \"\"\"",
"# check parallel gives same results assert_frame_equal(df_1, df_2) def test_co_occurrence(adata: AnnData): \"\"\" check",
"not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results with pytest.raises(AssertionError,",
"= moran(dummy_adata, copy=True, n_jobs=1, seed=42, n_perms=50) df_parallel = moran(dummy_adata, copy=True, n_jobs=2, seed=42, n_perms=50)",
"np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results with pytest.raises(AssertionError, match=r'.*\\(column",
"dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape != df_1.shape",
"assert dummy_adata.uns[MORAN_K].shape != df.shape # assert idx are sorted and contain same elements",
"= np.random.choice([True, False], size=dummy_adata.var_names.shape) # seed will work only when multiprocessing/loky df_1 =",
"test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check whether moran results are the same for seq. and parallel",
"idx are sorted and contain same elements assert not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata))",
"different, we don't expect the pval_sim values to be the same assert_frame_equal(df, df_parallel)",
"adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\", \"xs\"), [(10, 10), (None, None), (10, 20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1,",
"pytest from anndata import AnnData from pandas.testing import assert_frame_equal import numpy as np",
"(4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape != df_1.shape # assert idx are",
"pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\) are different.*'): # because the seeds will be different, we",
"# assert idx are sorted and contain same elements assert not np.array_equal(idx_df, idx_adata)",
"whether moran results are the same for seq. and parallel computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"]",
"\"\"\"Check ripley score and shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\") # assert ripley in adata.uns assert",
"adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim == 3 assert arr.shape[2] == 49 assert arr.shape[1] == arr.shape[0]",
"test highly variable assert dummy_adata.uns[MORAN_K].shape != df.shape # assert idx are sorted and",
"(None, None), (10, 20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1, 2), (2, 2)]) def test_co_occurrence_reproducibility(adata: AnnData,",
"n_perms=50) idx_df = df_1.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() #",
"@pytest.mark.parametrize(\"n_jobs\", [1, 2]) def test_moran_reproducibility(dummy_adata: AnnData, n_jobs: int): \"\"\"Check moran reproducibility results.\"\"\" moran(dummy_adata)",
"assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape != df_1.shape #",
"size=dummy_adata.var_names.shape) # seed will work only when multiprocessing/loky df_1 = moran(dummy_adata, copy=True, n_jobs=n_jobs,",
"arr.ndim == 3 assert arr.shape[2] == 49 assert arr.shape[1] == arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0]",
"np from squidpy.gr import moran, ripley_k, co_occurrence MORAN_K = \"moranI\" def test_ripley_k(adata: AnnData):",
"size=dummy_adata.var_names.shape) df = moran(dummy_adata, copy=True, n_jobs=1, seed=42, n_perms=50) df_parallel = moran(dummy_adata, copy=True, n_jobs=2,",
"# assert fdr correction in adata.uns assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape ==",
"moran reproducibility results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) # seed will work",
"ripley_k(adata, cluster_key=\"leiden\") # assert ripley in adata.uns assert \"ripley_k_leiden\" in adata.uns.keys() # assert",
"from squidpy.gr import moran, ripley_k, co_occurrence MORAN_K = \"moranI\" def test_ripley_k(adata: AnnData): \"\"\"Check",
"df_parallel = moran(dummy_adata, copy=True, n_jobs=2, seed=42, n_perms=50) idx_df = df.index.values idx_adata = dummy_adata[:,",
"False], size=dummy_adata.var_names.shape) # seed will work only when multiprocessing/loky df_1 = moran(dummy_adata, copy=True,",
"arr_1, interval_1 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) arr_2, interval_2 = co_occurrence(adata, cluster_key=\"leiden\",",
"elements assert not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results",
"same for seq. and parallel computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) df",
"# assert clusters intersection cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata = set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata) is",
"dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) # seed will work only when multiprocessing/loky df_1",
"# because the seeds will be different, we don't expect the pval_sim values",
"moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) # seed will work only when multiprocessing/loky",
"moran, ripley_k, co_occurrence MORAN_K = \"moranI\" def test_ripley_k(adata: AnnData): \"\"\"Check ripley score and",
"same results assert_frame_equal(df_1, df_2) def test_co_occurrence(adata: AnnData): \"\"\" check ripley score and shape",
"intersection cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata = set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata) is False def test_moran_seq_par(dummy_adata:",
"seed=42, n_perms=50) idx_df = df.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys()",
"are different.*'): # because the seeds will be different, we don't expect the",
"df.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K]",
"cat_adata = set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata) is False def test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check whether moran",
"co_occurrence reproducibility results.\"\"\" arr_1, interval_1 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) arr_2, interval_2",
"assert fdr correction in adata.uns assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,)",
"(10, 20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1, 2), (2, 2)]) def test_co_occurrence_reproducibility(adata: AnnData, n_jobs: int,",
"# test highly variable assert dummy_adata.uns[MORAN_K].shape != df.shape # assert idx are sorted",
"assert arr.shape[2] == 49 assert arr.shape[1] == arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\", \"xs\"),",
"expect the pval_sim values to be the same assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1, 2])",
"because the seeds will be different, we don't expect the pval_sim values to",
"shapes arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim == 3 assert arr.shape[2] == 49 assert",
"# assert shapes arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim == 3 assert arr.shape[2] ==",
"variable assert dummy_adata.uns[MORAN_K].shape != df.shape # assert idx are sorted and contain same",
"\"\"\" check ripley score and shape \"\"\" co_occurrence(adata, cluster_key=\"leiden\") # assert occurrence in",
"test_ripley_k(adata: AnnData): \"\"\"Check ripley score and shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\") # assert ripley in",
"== (4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape != df_1.shape # assert idx",
"seed=42, n_perms=50) df_parallel = moran(dummy_adata, copy=True, n_jobs=2, seed=42, n_perms=50) idx_df = df.index.values idx_adata",
"we don't expect the pval_sim values to be the same assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\",",
"(4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape != df.shape # assert idx are",
"n_jobs=n_jobs, seed=42, n_perms=50) df_2 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) idx_df = df_1.index.values",
"assert arr.ndim == 3 assert arr.shape[2] == 49 assert arr.shape[1] == arr.shape[0] ==",
"moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) idx_df = df_1.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert",
"assert shapes arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim == 3 assert arr.shape[2] == 49",
"in adata.uns[\"leiden_co_occurrence\"].keys() # assert shapes arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim == 3 assert",
"values to be the same assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1, 2]) def test_moran_reproducibility(dummy_adata: AnnData,",
"int, n_splits: int): \"\"\"Check co_occurrence reproducibility results.\"\"\" arr_1, interval_1 = co_occurrence(adata, cluster_key=\"leiden\", copy=True,",
"import pytest from anndata import AnnData from pandas.testing import assert_frame_equal import numpy as",
"\"\"\"Check moran reproducibility results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) # seed will",
"[(1, 2), (2, 2)]) def test_co_occurrence_reproducibility(adata: AnnData, n_jobs: int, n_splits: int): \"\"\"Check co_occurrence",
"in adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\" in adata.uns[\"leiden_co_occurrence\"].keys() # assert shapes arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert",
"== 3 assert arr.shape[2] == 49 assert arr.shape[1] == arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0] #",
"assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1, 2]) def test_moran_reproducibility(dummy_adata: AnnData, n_jobs: int): \"\"\"Check moran reproducibility",
"copy=True, n_jobs=n_jobs, seed=42, n_perms=50) idx_df = df_1.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K",
"= np.random.choice([True, False], size=dummy_adata.var_names.shape) df = moran(dummy_adata, copy=True, n_jobs=1, seed=42, n_perms=50) df_parallel =",
"numpy as np from squidpy.gr import moran, ripley_k, co_occurrence MORAN_K = \"moranI\" def",
"copy=True, n_jobs=1, seed=42, n_perms=50) df_parallel = moran(dummy_adata, copy=True, n_jobs=2, seed=42, n_perms=50) idx_df =",
"\"moranI\" def test_ripley_k(adata: AnnData): \"\"\"Check ripley score and shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\") # assert",
"= df_1.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() # assert fdr",
"2)]) def test_co_occurrence_reproducibility(adata: AnnData, n_jobs: int, n_splits: int): \"\"\"Check co_occurrence reproducibility results.\"\"\" arr_1,",
"dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) df = moran(dummy_adata, copy=True, n_jobs=1, seed=42, n_perms=50) df_parallel",
"np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results assert_frame_equal(df_1, df_2) def test_co_occurrence(adata: AnnData):",
"reproducibility results.\"\"\" arr_1, interval_1 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) arr_2, interval_2 =",
"import assert_frame_equal import numpy as np from squidpy.gr import moran, ripley_k, co_occurrence MORAN_K",
"np.random.choice([True, False], size=dummy_adata.var_names.shape) # seed will work only when multiprocessing/loky df_1 = moran(dummy_adata,",
"49 assert arr.shape[1] == arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\", \"xs\"), [(10, 10), (None,",
"AnnData, n_jobs: int, n_splits: int): \"\"\"Check co_occurrence reproducibility results.\"\"\" arr_1, interval_1 = co_occurrence(adata,",
"seed=42, n_perms=50) df_2 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) idx_df = df_1.index.values idx_adata",
"be different, we don't expect the pval_sim values to be the same assert_frame_equal(df,",
"assert not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results assert_frame_equal(df_1,",
"adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\" in adata.uns[\"leiden_co_occurrence\"].keys() # assert shapes arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim",
"np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results with pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\) are",
"as np from squidpy.gr import moran, ripley_k, co_occurrence MORAN_K = \"moranI\" def test_ripley_k(adata:",
"anndata import AnnData from pandas.testing import assert_frame_equal import numpy as np from squidpy.gr",
"from pandas.testing import assert_frame_equal import numpy as np from squidpy.gr import moran, ripley_k,",
"20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1, 2), (2, 2)]) def test_co_occurrence_reproducibility(adata: AnnData, n_jobs: int, n_splits:",
"dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape != df.shape",
"different.*'): # because the seeds will be different, we don't expect the pval_sim",
"dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() # assert fdr correction in adata.uns assert \"pval_sim_fdr_bh\"",
"n_jobs=n_jobs, seed=42, n_perms=50) idx_df = df_1.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in",
"[1, 2]) def test_moran_reproducibility(dummy_adata: AnnData, n_jobs: int): \"\"\"Check moran reproducibility results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"]",
"\"\"\"Check co_occurrence reproducibility results.\"\"\" arr_1, interval_1 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) arr_2,",
"the seeds will be different, we don't expect the pval_sim values to be",
"gives same results with pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\) are different.*'): # because the seeds",
"import AnnData from pandas.testing import assert_frame_equal import numpy as np from squidpy.gr import",
"dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape ==",
"== arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\", \"xs\"), [(10, 10), (None, None), (10, 20)])",
"test_moran_reproducibility(dummy_adata: AnnData, n_jobs: int): \"\"\"Check moran reproducibility results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False],",
"idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results assert_frame_equal(df_1, df_2) def test_co_occurrence(adata:",
"ripley_k, co_occurrence MORAN_K = \"moranI\" def test_ripley_k(adata: AnnData): \"\"\"Check ripley score and shape.\"\"\"",
"pval_sim values to be the same assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1, 2]) def test_moran_reproducibility(dummy_adata:",
"= \"moranI\" def test_ripley_k(adata: AnnData): \"\"\"Check ripley score and shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\") #",
"in adata.uns.keys() assert \"occ\" in adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\" in adata.uns[\"leiden_co_occurrence\"].keys() # assert shapes",
"with pytest.raises(AssertionError, match=r'.*\\(column name=\"pval_sim\"\\) are different.*'): # because the seeds will be different,",
"moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) df_2 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) idx_df",
"cluster_key=\"leiden\") # assert ripley in adata.uns assert \"ripley_k_leiden\" in adata.uns.keys() # assert clusters",
"assert ripley in adata.uns assert \"ripley_k_leiden\" in adata.uns.keys() # assert clusters intersection cat_ripley",
"and shape \"\"\" co_occurrence(adata, cluster_key=\"leiden\") # assert occurrence in adata.uns assert \"leiden_co_occurrence\" in",
"MORAN_K = \"moranI\" def test_ripley_k(adata: AnnData): \"\"\"Check ripley score and shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\")",
"assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable assert",
"AnnData from pandas.testing import assert_frame_equal import numpy as np from squidpy.gr import moran,",
"and contain same elements assert not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel",
"# test highly variable assert dummy_adata.uns[MORAN_K].shape != df_1.shape # assert idx are sorted",
"== adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\", \"xs\"), [(10, 10), (None, None), (10, 20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"),",
"moran(dummy_adata, copy=True, n_jobs=1, seed=42, n_perms=50) df_parallel = moran(dummy_adata, copy=True, n_jobs=2, seed=42, n_perms=50) idx_df",
"MORAN_K in dummy_adata.uns.keys() assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test",
"seed will work only when multiprocessing/loky df_1 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50)",
"moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) df = moran(dummy_adata, copy=True, n_jobs=1, seed=42, n_perms=50)",
"assert clusters intersection cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata = set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata) is False",
"variable assert dummy_adata.uns[MORAN_K].shape != df_1.shape # assert idx are sorted and contain same",
"# assert ripley in adata.uns assert \"ripley_k_leiden\" in adata.uns.keys() # assert clusters intersection",
"not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results assert_frame_equal(df_1, df_2)",
"n_perms=50) df_parallel = moran(dummy_adata, copy=True, n_jobs=2, seed=42, n_perms=50) idx_df = df.index.values idx_adata =",
"test_co_occurrence(adata: AnnData): \"\"\" check ripley score and shape \"\"\" co_occurrence(adata, cluster_key=\"leiden\") # assert",
"score and shape \"\"\" co_occurrence(adata, cluster_key=\"leiden\") # assert occurrence in adata.uns assert \"leiden_co_occurrence\"",
"import numpy as np from squidpy.gr import moran, ripley_k, co_occurrence MORAN_K = \"moranI\"",
"pandas.testing import assert_frame_equal import numpy as np from squidpy.gr import moran, ripley_k, co_occurrence",
"seq. and parallel computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) df = moran(dummy_adata,",
"= adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim == 3 assert arr.shape[2] == 49 assert arr.shape[1] ==",
"AnnData): \"\"\"Check whether moran results are the same for seq. and parallel computation.\"\"\"",
"assert \"leiden_co_occurrence\" in adata.uns.keys() assert \"occ\" in adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\" in adata.uns[\"leiden_co_occurrence\"].keys() #",
"\"xs\"), [(10, 10), (None, None), (10, 20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1, 2), (2, 2)])",
"dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape != df_1.shape # assert",
"\"\"\"Check whether moran results are the same for seq. and parallel computation.\"\"\" moran(dummy_adata)",
"df_1.shape # assert idx are sorted and contain same elements assert not np.array_equal(idx_df,",
"assert not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same results with",
"= moran(dummy_adata, copy=True, n_jobs=2, seed=42, n_perms=50) idx_df = df.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values",
"seeds will be different, we don't expect the pval_sim values to be the",
"def test_moran_reproducibility(dummy_adata: AnnData, n_jobs: int): \"\"\"Check moran reproducibility results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True,",
"int): \"\"\"Check moran reproducibility results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) # seed",
"assert \"ripley_k_leiden\" in adata.uns.keys() # assert clusters intersection cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata =",
"n_splits: int): \"\"\"Check co_occurrence reproducibility results.\"\"\" arr_1, interval_1 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs,",
"dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() # assert fdr correction in adata.uns assert",
"and shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\") # assert ripley in adata.uns assert \"ripley_k_leiden\" in adata.uns.keys()",
"shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\") # assert ripley in adata.uns assert \"ripley_k_leiden\" in adata.uns.keys() #",
"dummy_adata.uns[MORAN_K].shape != df.shape # assert idx are sorted and contain same elements assert",
"assert cat_ripley.isdisjoint(cat_adata) is False def test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check whether moran results are the",
"assert \"occ\" in adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\" in adata.uns[\"leiden_co_occurrence\"].keys() # assert shapes arr =",
"copy=True, n_jobs=n_jobs, seed=42, n_perms=50) df_2 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) idx_df =",
"# seed will work only when multiprocessing/loky df_1 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42,",
"def test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check whether moran results are the same for seq. and",
"== (4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape != df.shape # assert idx",
"n_jobs=1, seed=42, n_perms=50) df_parallel = moran(dummy_adata, copy=True, n_jobs=2, seed=42, n_perms=50) idx_df = df.index.values",
"score and shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\") # assert ripley in adata.uns assert \"ripley_k_leiden\" in",
"cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) arr_2, interval_2 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) np.testing.assert_array_equal(sorted(interval_1),",
"cat_ripley = set(adata.uns[\"ripley_k_leiden\"][\"leiden\"].unique()) cat_adata = set(adata.obs[\"leiden\"].cat.categories) assert cat_ripley.isdisjoint(cat_adata) is False def test_moran_seq_par(dummy_adata: AnnData):",
"highly variable assert dummy_adata.uns[MORAN_K].shape != df_1.shape # assert idx are sorted and contain",
"co_occurrence(adata, cluster_key=\"leiden\") # assert occurrence in adata.uns assert \"leiden_co_occurrence\" in adata.uns.keys() assert \"occ\"",
"moran(dummy_adata, copy=True, n_jobs=2, seed=42, n_perms=50) idx_df = df.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert",
"cat_ripley.isdisjoint(cat_adata) is False def test_moran_seq_par(dummy_adata: AnnData): \"\"\"Check whether moran results are the same",
"from anndata import AnnData from pandas.testing import assert_frame_equal import numpy as np from",
"# @pytest.mark.parametrize((\"ys\", \"xs\"), [(10, 10), (None, None), (10, 20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1, 2),",
"the same for seq. and parallel computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape)",
"assert \"interval\" in adata.uns[\"leiden_co_occurrence\"].keys() # assert shapes arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim ==",
"occurrence in adata.uns assert \"leiden_co_occurrence\" in adata.uns.keys() assert \"occ\" in adata.uns[\"leiden_co_occurrence\"].keys() assert \"interval\"",
"seed=42, n_perms=50) idx_df = df_1.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys()",
"don't expect the pval_sim values to be the same assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1,",
"be the same assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1, 2]) def test_moran_reproducibility(dummy_adata: AnnData, n_jobs: int):",
"def test_ripley_k(adata: AnnData): \"\"\"Check ripley score and shape.\"\"\" ripley_k(adata, cluster_key=\"leiden\") # assert ripley",
"dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly variable assert dummy_adata.uns[MORAN_K].shape != df.shape # assert",
"for seq. and parallel computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) df =",
"2), (2, 2)]) def test_co_occurrence_reproducibility(adata: AnnData, n_jobs: int, n_splits: int): \"\"\"Check co_occurrence reproducibility",
"\"interval\" in adata.uns[\"leiden_co_occurrence\"].keys() # assert shapes arr = adata.uns[\"leiden_co_occurrence\"][\"occ\"] assert arr.ndim == 3",
"2]) def test_moran_reproducibility(dummy_adata: AnnData, n_jobs: int): \"\"\"Check moran reproducibility results.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] =",
"idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K in dummy_adata.uns.keys() # assert fdr correction in",
"co_occurrence MORAN_K = \"moranI\" def test_ripley_k(adata: AnnData): \"\"\"Check ripley score and shape.\"\"\" ripley_k(adata,",
"same assert_frame_equal(df, df_parallel) @pytest.mark.parametrize(\"n_jobs\", [1, 2]) def test_moran_reproducibility(dummy_adata: AnnData, n_jobs: int): \"\"\"Check moran",
"work only when multiprocessing/loky df_1 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) df_2 =",
"shape \"\"\" co_occurrence(adata, cluster_key=\"leiden\") # assert occurrence in adata.uns assert \"leiden_co_occurrence\" in adata.uns.keys()",
"moran results are the same for seq. and parallel computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] =",
"same elements assert not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check parallel gives same",
"computation.\"\"\" moran(dummy_adata) dummy_adata.var[\"highly_variable\"] = np.random.choice([True, False], size=dummy_adata.var_names.shape) df = moran(dummy_adata, copy=True, n_jobs=1, seed=42,",
"copy=True, n_jobs=2, seed=42, n_perms=50) idx_df = df.index.values idx_adata = dummy_adata[:, dummy_adata.var.highly_variable.values].var_names.values assert MORAN_K",
"assert MORAN_K in dummy_adata.uns.keys() # assert fdr correction in adata.uns assert \"pval_sim_fdr_bh\" in",
"[(10, 10), (None, None), (10, 20)]) @pytest.mark.parametrize((\"n_jobs\", \"n_splits\"), [(1, 2), (2, 2)]) def",
"df_1 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42, n_perms=50) df_2 = moran(dummy_adata, copy=True, n_jobs=n_jobs, seed=42,",
"assert_frame_equal import numpy as np from squidpy.gr import moran, ripley_k, co_occurrence MORAN_K =",
"are sorted and contain same elements assert not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) #",
"sorted and contain same elements assert not np.array_equal(idx_df, idx_adata) np.testing.assert_array_equal(sorted(idx_df), sorted(idx_adata)) # check",
"gives same results assert_frame_equal(df_1, df_2) def test_co_occurrence(adata: AnnData): \"\"\" check ripley score and",
"results.\"\"\" arr_1, interval_1 = co_occurrence(adata, cluster_key=\"leiden\", copy=True, n_jobs=n_jobs, n_splits=n_splits) arr_2, interval_2 = co_occurrence(adata,",
"in adata.uns assert \"pval_sim_fdr_bh\" in dummy_adata.uns[MORAN_K] assert dummy_adata.uns[MORAN_K].columns.shape == (4,) # test highly",
"== 49 assert arr.shape[1] == arr.shape[0] == adata.obs[\"leiden\"].unique().shape[0] # @pytest.mark.parametrize((\"ys\", \"xs\"), [(10, 10),"
] |
[
"{'minValue': 10, 'maxValue': 20, 'step': 1} char = get_char(PROPERTIES.copy(), min_value=0, max_value=1) char.override_properties(properties=new_properties) assert",
"new_valid_values def test_get_hap_value(): max_value = 5 raw_value = 6 char = get_char(PROPERTIES.copy(), max_value=max_value)",
"min_value is not None: props[\"minValue\"] = min_value if max_value is not None: props[\"maxValue\"]",
"= 6 char = get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value, should_notify=False) assert char.value == raw_value assert",
"char.value = notify_value char.notify() assert broker_mock.publish.called broker_mock.publish.assert_called_with(expected, char) def test_notify_except_no_broker(): char = get_char(PROPERTIES.copy())",
"Characteristic PROPERTIES = { \"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ] } def get_char(props, valid=None, min_value=None,",
"notify_value, } char.value = notify_value char.notify() assert broker_mock.publish.called broker_mock.publish.assert_called_with(expected, char) def test_notify_except_no_broker(): char",
"get_char(PROPERTIES.copy(), valid=valid_values) with pytest.raises(ValueError): char.set_value(4) def test_set_value_callback_toggle(): char = get_char(PROPERTIES.copy()) char.setter_callback = mock.Mock()",
"not None: props[\"maxValue\"] = max_value c = Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(), properties=props) return c",
"char.properties['ValidValues'] == new_valid_values def test_get_hap_value(): max_value = 5 raw_value = 6 char =",
"def test_notify(): char = get_char(PROPERTIES.copy()) broker_mock = mock.Mock() char.broker = broker_mock notify_value =",
"def test_get_hap_value(): max_value = 5 raw_value = 6 char = get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value,",
"new_properties['minValue'] assert char.properties['maxValue'] == new_properties['maxValue'] assert char.properties['step'] == new_properties['step'] def test_override_properties_valid_values(): new_valid_values =",
"min_value=0, max_value=1) char.override_properties(properties=new_properties) assert char.properties['minValue'] == new_properties['minValue'] assert char.properties['maxValue'] == new_properties['maxValue'] assert char.properties['step']",
"= {\"foo\": 2, \"bar\": 3} char = get_char(PROPERTIES.copy(), valid=valid_values) assert char.value in valid_values.values()",
"test_set_value_valid_values(): valid_values = {\"foo\": 2, \"bar\": 3, } char = get_char(PROPERTIES.copy(), valid=valid_values) with",
"\"\"\" import uuid from unittest import mock import pytest import pyhap.characteristic as characteristic",
"2, \"bar\": 3} char = get_char(PROPERTIES.copy(), valid=valid_values) assert char.value in valid_values.values() def test_set_value():",
"char.properties['maxValue'] == new_properties['maxValue'] assert char.properties['step'] == new_properties['step'] def test_override_properties_valid_values(): new_valid_values = {'foo2': 2,",
"test_notify(): char = get_char(PROPERTIES.copy()) broker_mock = mock.Mock() char.broker = broker_mock notify_value = 3",
"c def test_default_value(): char = get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value) def test_default_valid_value(): valid_values",
"def test_default_value(): char = get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value) def test_default_valid_value(): valid_values =",
"(characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value) def test_default_valid_value(): valid_values = {\"foo\": 2, \"bar\": 3} char =",
"3} char = get_char(PROPERTIES.copy(), valid={'foo': 1, 'bar': 2}) char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues'] == new_valid_values",
"max_value is not None: props[\"maxValue\"] = max_value c = Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(), properties=props)",
"new_properties['maxValue'] assert char.properties['step'] == new_properties['step'] def test_override_properties_valid_values(): new_valid_values = {'foo2': 2, 'bar2': 3}",
"char.set_value(3, should_callback=False) assert not char.setter_callback.called char.set_value(3, should_callback=True) assert char.setter_callback.called def test_override_properties_properties(): new_properties =",
"import mock import pytest import pyhap.characteristic as characteristic from pyhap.characteristic import Characteristic PROPERTIES",
"char = get_char(PROPERTIES.copy(), valid=valid_values) assert char.value in valid_values.values() def test_set_value(): char = get_char(PROPERTIES.copy())",
"from pyhap.characteristic import Characteristic PROPERTIES = { \"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ] } def",
"characteristic from pyhap.characteristic import Characteristic PROPERTIES = { \"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ] }",
"notify_value = 3 expected = { \"type_id\": char.type_id, \"value\": notify_value, } char.value =",
"properties=props) return c def test_default_value(): char = get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value) def",
"char.value == new_value def test_set_value_valid_values(): valid_values = {\"foo\": 2, \"bar\": 3, } char",
"None: props[\"ValidValues\"] = valid if min_value is not None: props[\"minValue\"] = min_value if",
"'bar2': 3} char = get_char(PROPERTIES.copy(), valid={'foo': 1, 'bar': 2}) char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues'] ==",
"props[\"ValidValues\"] = valid if min_value is not None: props[\"minValue\"] = min_value if max_value",
"char.set_value(raw_value, should_notify=False) assert char.value == raw_value assert char.get_hap_value() == max_value def test_notify(): char",
"char.properties['step'] == new_properties['step'] def test_override_properties_valid_values(): new_valid_values = {'foo2': 2, 'bar2': 3} char =",
"char.set_value(new_value) assert char.value == new_value def test_set_value_valid_values(): valid_values = {\"foo\": 2, \"bar\": 3,",
"6 char = get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value, should_notify=False) assert char.value == raw_value assert char.get_hap_value()",
"char.broker = broker_mock notify_value = 3 expected = { \"type_id\": char.type_id, \"value\": notify_value,",
"type_id=uuid.uuid1(), properties=props) return c def test_default_value(): char = get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value)",
"== new_value def test_set_value_valid_values(): valid_values = {\"foo\": 2, \"bar\": 3, } char =",
"char.set_value(3, should_callback=True) assert char.setter_callback.called def test_override_properties_properties(): new_properties = {'minValue': 10, 'maxValue': 20, 'step':",
"not char.setter_callback.called char.set_value(3, should_callback=True) assert char.setter_callback.called def test_override_properties_properties(): new_properties = {'minValue': 10, 'maxValue':",
"Char\", type_id=uuid.uuid1(), properties=props) return c def test_default_value(): char = get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] ==",
"for pyhap.characteristic \"\"\" import uuid from unittest import mock import pytest import pyhap.characteristic",
"\"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ] } def get_char(props, valid=None, min_value=None, max_value=None): if valid is",
"3} char = get_char(PROPERTIES.copy(), valid=valid_values) assert char.value in valid_values.values() def test_set_value(): char =",
"2}) char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues'] == new_valid_values def test_get_hap_value(): max_value = 5 raw_value =",
"valid_values = {\"foo\": 2, \"bar\": 3} char = get_char(PROPERTIES.copy(), valid=valid_values) assert char.value in",
"should_callback=False) assert not char.setter_callback.called char.set_value(3, should_callback=True) assert char.setter_callback.called def test_override_properties_properties(): new_properties = {'minValue':",
"= max_value c = Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(), properties=props) return c def test_default_value(): char",
"1, 'bar': 2}) char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues'] == new_valid_values def test_get_hap_value(): max_value = 5",
"mock.Mock() char.broker = broker_mock notify_value = 3 expected = { \"type_id\": char.type_id, \"value\":",
"if valid is not None: props[\"ValidValues\"] = valid if min_value is not None:",
"char = get_char(PROPERTIES.copy(), valid={'foo': 1, 'bar': 2}) char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues'] == new_valid_values def",
"mock import pytest import pyhap.characteristic as characteristic from pyhap.characteristic import Characteristic PROPERTIES =",
"\"Permissions\": [characteristic.HAP_PERMISSIONS.READ] } def get_char(props, valid=None, min_value=None, max_value=None): if valid is not None:",
"valid_values.values() def test_set_value(): char = get_char(PROPERTIES.copy()) new_value = 3 char.set_value(new_value) assert char.value ==",
"is not None: props[\"maxValue\"] = max_value c = Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(), properties=props) return",
"test_override_properties_valid_values(): new_valid_values = {'foo2': 2, 'bar2': 3} char = get_char(PROPERTIES.copy(), valid={'foo': 1, 'bar':",
"= { \"type_id\": char.type_id, \"value\": notify_value, } char.value = notify_value char.notify() assert broker_mock.publish.called",
"char.value in valid_values.values() def test_set_value(): char = get_char(PROPERTIES.copy()) new_value = 3 char.set_value(new_value) assert",
"min_value if max_value is not None: props[\"maxValue\"] = max_value c = Characteristic(display_name=\"Test Char\",",
"char.properties['minValue'] == new_properties['minValue'] assert char.properties['maxValue'] == new_properties['maxValue'] assert char.properties['step'] == new_properties['step'] def test_override_properties_valid_values():",
"= broker_mock notify_value = 3 expected = { \"type_id\": char.type_id, \"value\": notify_value, }",
"2, \"bar\": 3, } char = get_char(PROPERTIES.copy(), valid=valid_values) with pytest.raises(ValueError): char.set_value(4) def test_set_value_callback_toggle():",
"= 3 expected = { \"type_id\": char.type_id, \"value\": notify_value, } char.value = notify_value",
"\"type_id\": char.type_id, \"value\": notify_value, } char.value = notify_value char.notify() assert broker_mock.publish.called broker_mock.publish.assert_called_with(expected, char)",
"assert char.value == raw_value assert char.get_hap_value() == max_value def test_notify(): char = get_char(PROPERTIES.copy())",
"Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(), properties=props) return c def test_default_value(): char = get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]]",
"get_char(PROPERTIES.copy()) broker_mock = mock.Mock() char.broker = broker_mock notify_value = 3 expected = {",
"[characteristic.HAP_PERMISSIONS.READ] } def get_char(props, valid=None, min_value=None, max_value=None): if valid is not None: props[\"ValidValues\"]",
"assert char.properties['ValidValues'] == new_valid_values def test_get_hap_value(): max_value = 5 raw_value = 6 char",
"test_set_value(): char = get_char(PROPERTIES.copy()) new_value = 3 char.set_value(new_value) assert char.value == new_value def",
"notify_value char.notify() assert broker_mock.publish.called broker_mock.publish.assert_called_with(expected, char) def test_notify_except_no_broker(): char = get_char(PROPERTIES.copy()) with pytest.raises(characteristic.NotConfiguredError):",
"char.notify() assert broker_mock.publish.called broker_mock.publish.assert_called_with(expected, char) def test_notify_except_no_broker(): char = get_char(PROPERTIES.copy()) with pytest.raises(characteristic.NotConfiguredError): char.notify()",
"{ \"type_id\": char.type_id, \"value\": notify_value, } char.value = notify_value char.notify() assert broker_mock.publish.called broker_mock.publish.assert_called_with(expected,",
"3 char.set_value(new_value) assert char.value == new_value def test_set_value_valid_values(): valid_values = {\"foo\": 2, \"bar\":",
"with pytest.raises(ValueError): char.set_value(4) def test_set_value_callback_toggle(): char = get_char(PROPERTIES.copy()) char.setter_callback = mock.Mock() char.set_value(3, should_callback=False)",
"== new_properties['maxValue'] assert char.properties['step'] == new_properties['step'] def test_override_properties_valid_values(): new_valid_values = {'foo2': 2, 'bar2':",
"should_callback=True) assert char.setter_callback.called def test_override_properties_properties(): new_properties = {'minValue': 10, 'maxValue': 20, 'step': 1}",
"10, 'maxValue': 20, 'step': 1} char = get_char(PROPERTIES.copy(), min_value=0, max_value=1) char.override_properties(properties=new_properties) assert char.properties['minValue']",
"new_value def test_set_value_valid_values(): valid_values = {\"foo\": 2, \"bar\": 3, } char = get_char(PROPERTIES.copy(),",
"20, 'step': 1} char = get_char(PROPERTIES.copy(), min_value=0, max_value=1) char.override_properties(properties=new_properties) assert char.properties['minValue'] == new_properties['minValue']",
"import uuid from unittest import mock import pytest import pyhap.characteristic as characteristic from",
"get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value, should_notify=False) assert char.value == raw_value assert char.get_hap_value() == max_value def",
"None: props[\"maxValue\"] = max_value c = Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(), properties=props) return c def",
"assert not char.setter_callback.called char.set_value(3, should_callback=True) assert char.setter_callback.called def test_override_properties_properties(): new_properties = {'minValue': 10,",
"max_value=None): if valid is not None: props[\"ValidValues\"] = valid if min_value is not",
"def test_override_properties_valid_values(): new_valid_values = {'foo2': 2, 'bar2': 3} char = get_char(PROPERTIES.copy(), valid={'foo': 1,",
"PROPERTIES = { \"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ] } def get_char(props, valid=None, min_value=None, max_value=None):",
"get_char(PROPERTIES.copy(), valid=valid_values) assert char.value in valid_values.values() def test_set_value(): char = get_char(PROPERTIES.copy()) new_value =",
"Tests for pyhap.characteristic \"\"\" import uuid from unittest import mock import pytest import",
"test_default_valid_value(): valid_values = {\"foo\": 2, \"bar\": 3} char = get_char(PROPERTIES.copy(), valid=valid_values) assert char.value",
"max_value=1) char.override_properties(properties=new_properties) assert char.properties['minValue'] == new_properties['minValue'] assert char.properties['maxValue'] == new_properties['maxValue'] assert char.properties['step'] ==",
"broker_mock = mock.Mock() char.broker = broker_mock notify_value = 3 expected = { \"type_id\":",
"max_value = 5 raw_value = 6 char = get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value, should_notify=False) assert",
"= notify_value char.notify() assert broker_mock.publish.called broker_mock.publish.assert_called_with(expected, char) def test_notify_except_no_broker(): char = get_char(PROPERTIES.copy()) with",
"= { \"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ] } def get_char(props, valid=None, min_value=None, max_value=None): if",
"{ \"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ] } def get_char(props, valid=None, min_value=None, max_value=None): if valid",
"valid=valid_values) with pytest.raises(ValueError): char.set_value(4) def test_set_value_callback_toggle(): char = get_char(PROPERTIES.copy()) char.setter_callback = mock.Mock() char.set_value(3,",
"} char.value = notify_value char.notify() assert broker_mock.publish.called broker_mock.publish.assert_called_with(expected, char) def test_notify_except_no_broker(): char =",
"pyhap.characteristic \"\"\" import uuid from unittest import mock import pytest import pyhap.characteristic as",
"def get_char(props, valid=None, min_value=None, max_value=None): if valid is not None: props[\"ValidValues\"] = valid",
"char = get_char(PROPERTIES.copy(), min_value=0, max_value=1) char.override_properties(properties=new_properties) assert char.properties['minValue'] == new_properties['minValue'] assert char.properties['maxValue'] ==",
"new_properties = {'minValue': 10, 'maxValue': 20, 'step': 1} char = get_char(PROPERTIES.copy(), min_value=0, max_value=1)",
"== new_valid_values def test_get_hap_value(): max_value = 5 raw_value = 6 char = get_char(PROPERTIES.copy(),",
"'bar': 2}) char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues'] == new_valid_values def test_get_hap_value(): max_value = 5 raw_value",
"None: props[\"minValue\"] = min_value if max_value is not None: props[\"maxValue\"] = max_value c",
"= get_char(PROPERTIES.copy()) broker_mock = mock.Mock() char.broker = broker_mock notify_value = 3 expected =",
"is not None: props[\"ValidValues\"] = valid if min_value is not None: props[\"minValue\"] =",
"props[\"minValue\"] = min_value if max_value is not None: props[\"maxValue\"] = max_value c =",
"assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value) def test_default_valid_value(): valid_values = {\"foo\": 2, \"bar\": 3} char",
"char.override_properties(properties=new_properties) assert char.properties['minValue'] == new_properties['minValue'] assert char.properties['maxValue'] == new_properties['maxValue'] assert char.properties['step'] == new_properties['step']",
"= get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value, should_notify=False) assert char.value == raw_value assert char.get_hap_value() == max_value",
"max_value def test_notify(): char = get_char(PROPERTIES.copy()) broker_mock = mock.Mock() char.broker = broker_mock notify_value",
"assert char.get_hap_value() == max_value def test_notify(): char = get_char(PROPERTIES.copy()) broker_mock = mock.Mock() char.broker",
"min_value=None, max_value=None): if valid is not None: props[\"ValidValues\"] = valid if min_value is",
"if min_value is not None: props[\"minValue\"] = min_value if max_value is not None:",
"max_value=max_value) char.set_value(raw_value, should_notify=False) assert char.value == raw_value assert char.get_hap_value() == max_value def test_notify():",
"} char = get_char(PROPERTIES.copy(), valid=valid_values) with pytest.raises(ValueError): char.set_value(4) def test_set_value_callback_toggle(): char = get_char(PROPERTIES.copy())",
"== new_properties['minValue'] assert char.properties['maxValue'] == new_properties['maxValue'] assert char.properties['step'] == new_properties['step'] def test_override_properties_valid_values(): new_valid_values",
"import pyhap.characteristic as characteristic from pyhap.characteristic import Characteristic PROPERTIES = { \"Format\": characteristic.HAP_FORMAT.INT,",
"\"value\": notify_value, } char.value = notify_value char.notify() assert broker_mock.publish.called broker_mock.publish.assert_called_with(expected, char) def test_notify_except_no_broker():",
"not None: props[\"minValue\"] = min_value if max_value is not None: props[\"maxValue\"] = max_value",
"\"bar\": 3} char = get_char(PROPERTIES.copy(), valid=valid_values) assert char.value in valid_values.values() def test_set_value(): char",
"assert char.properties['maxValue'] == new_properties['maxValue'] assert char.properties['step'] == new_properties['step'] def test_override_properties_valid_values(): new_valid_values = {'foo2':",
"should_notify=False) assert char.value == raw_value assert char.get_hap_value() == max_value def test_notify(): char =",
"== max_value def test_notify(): char = get_char(PROPERTIES.copy()) broker_mock = mock.Mock() char.broker = broker_mock",
"3 expected = { \"type_id\": char.type_id, \"value\": notify_value, } char.value = notify_value char.notify()",
"get_char(PROPERTIES.copy()) new_value = 3 char.set_value(new_value) assert char.value == new_value def test_set_value_valid_values(): valid_values =",
"import Characteristic PROPERTIES = { \"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ] } def get_char(props, valid=None,",
"pytest import pyhap.characteristic as characteristic from pyhap.characteristic import Characteristic PROPERTIES = { \"Format\":",
"char = get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value, should_notify=False) assert char.value == raw_value assert char.get_hap_value() ==",
"= 3 char.set_value(new_value) assert char.value == new_value def test_set_value_valid_values(): valid_values = {\"foo\": 2,",
"get_char(props, valid=None, min_value=None, max_value=None): if valid is not None: props[\"ValidValues\"] = valid if",
"def test_set_value_valid_values(): valid_values = {\"foo\": 2, \"bar\": 3, } char = get_char(PROPERTIES.copy(), valid=valid_values)",
"mock.Mock() char.set_value(3, should_callback=False) assert not char.setter_callback.called char.set_value(3, should_callback=True) assert char.setter_callback.called def test_override_properties_properties(): new_properties",
"def test_override_properties_properties(): new_properties = {'minValue': 10, 'maxValue': 20, 'step': 1} char = get_char(PROPERTIES.copy(),",
"test_override_properties_properties(): new_properties = {'minValue': 10, 'maxValue': 20, 'step': 1} char = get_char(PROPERTIES.copy(), min_value=0,",
"'step': 1} char = get_char(PROPERTIES.copy(), min_value=0, max_value=1) char.override_properties(properties=new_properties) assert char.properties['minValue'] == new_properties['minValue'] assert",
"as characteristic from pyhap.characteristic import Characteristic PROPERTIES = { \"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ]",
"raw_value assert char.get_hap_value() == max_value def test_notify(): char = get_char(PROPERTIES.copy()) broker_mock = mock.Mock()",
"pyhap.characteristic as characteristic from pyhap.characteristic import Characteristic PROPERTIES = { \"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\":",
"= Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(), properties=props) return c def test_default_value(): char = get_char(PROPERTIES.copy()) assert",
"import pytest import pyhap.characteristic as characteristic from pyhap.characteristic import Characteristic PROPERTIES = {",
"c = Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(), properties=props) return c def test_default_value(): char = get_char(PROPERTIES.copy())",
"== char.value) def test_default_valid_value(): valid_values = {\"foo\": 2, \"bar\": 3} char = get_char(PROPERTIES.copy(),",
"char = get_char(PROPERTIES.copy()) char.setter_callback = mock.Mock() char.set_value(3, should_callback=False) assert not char.setter_callback.called char.set_value(3, should_callback=True)",
"broker_mock notify_value = 3 expected = { \"type_id\": char.type_id, \"value\": notify_value, } char.value",
"valid=None, min_value=None, max_value=None): if valid is not None: props[\"ValidValues\"] = valid if min_value",
"= get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value) def test_default_valid_value(): valid_values = {\"foo\": 2, \"bar\":",
"= get_char(PROPERTIES.copy(), valid={'foo': 1, 'bar': 2}) char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues'] == new_valid_values def test_get_hap_value():",
"test_default_value(): char = get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value) def test_default_valid_value(): valid_values = {\"foo\":",
"assert char.setter_callback.called def test_override_properties_properties(): new_properties = {'minValue': 10, 'maxValue': 20, 'step': 1} char",
"{\"foo\": 2, \"bar\": 3, } char = get_char(PROPERTIES.copy(), valid=valid_values) with pytest.raises(ValueError): char.set_value(4) def",
"is not None: props[\"minValue\"] = min_value if max_value is not None: props[\"maxValue\"] =",
"= min_value if max_value is not None: props[\"maxValue\"] = max_value c = Characteristic(display_name=\"Test",
"if max_value is not None: props[\"maxValue\"] = max_value c = Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(),",
"not None: props[\"ValidValues\"] = valid if min_value is not None: props[\"minValue\"] = min_value",
"in valid_values.values() def test_set_value(): char = get_char(PROPERTIES.copy()) new_value = 3 char.set_value(new_value) assert char.value",
"== new_properties['step'] def test_override_properties_valid_values(): new_valid_values = {'foo2': 2, 'bar2': 3} char = get_char(PROPERTIES.copy(),",
"= {'minValue': 10, 'maxValue': 20, 'step': 1} char = get_char(PROPERTIES.copy(), min_value=0, max_value=1) char.override_properties(properties=new_properties)",
"5 raw_value = 6 char = get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value, should_notify=False) assert char.value ==",
"valid_values = {\"foo\": 2, \"bar\": 3, } char = get_char(PROPERTIES.copy(), valid=valid_values) with pytest.raises(ValueError):",
"new_properties['step'] def test_override_properties_valid_values(): new_valid_values = {'foo2': 2, 'bar2': 3} char = get_char(PROPERTIES.copy(), valid={'foo':",
"assert char.value == new_value def test_set_value_valid_values(): valid_values = {\"foo\": 2, \"bar\": 3, }",
"char.value == raw_value assert char.get_hap_value() == max_value def test_notify(): char = get_char(PROPERTIES.copy()) broker_mock",
"= get_char(PROPERTIES.copy(), valid=valid_values) with pytest.raises(ValueError): char.set_value(4) def test_set_value_callback_toggle(): char = get_char(PROPERTIES.copy()) char.setter_callback =",
"def test_set_value_callback_toggle(): char = get_char(PROPERTIES.copy()) char.setter_callback = mock.Mock() char.set_value(3, should_callback=False) assert not char.setter_callback.called",
"test_get_hap_value(): max_value = 5 raw_value = 6 char = get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value, should_notify=False)",
"assert char.properties['step'] == new_properties['step'] def test_override_properties_valid_values(): new_valid_values = {'foo2': 2, 'bar2': 3} char",
"= get_char(PROPERTIES.copy()) char.setter_callback = mock.Mock() char.set_value(3, should_callback=False) assert not char.setter_callback.called char.set_value(3, should_callback=True) assert",
"char.setter_callback = mock.Mock() char.set_value(3, should_callback=False) assert not char.setter_callback.called char.set_value(3, should_callback=True) assert char.setter_callback.called def",
"2, 'bar2': 3} char = get_char(PROPERTIES.copy(), valid={'foo': 1, 'bar': 2}) char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues']",
"= get_char(PROPERTIES.copy(), min_value=0, max_value=1) char.override_properties(properties=new_properties) assert char.properties['minValue'] == new_properties['minValue'] assert char.properties['maxValue'] == new_properties['maxValue']",
"expected = { \"type_id\": char.type_id, \"value\": notify_value, } char.value = notify_value char.notify() assert",
"'maxValue': 20, 'step': 1} char = get_char(PROPERTIES.copy(), min_value=0, max_value=1) char.override_properties(properties=new_properties) assert char.properties['minValue'] ==",
"characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ] } def get_char(props, valid=None, min_value=None, max_value=None): if valid is not",
"char.get_hap_value() == max_value def test_notify(): char = get_char(PROPERTIES.copy()) broker_mock = mock.Mock() char.broker =",
"return c def test_default_value(): char = get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value) def test_default_valid_value():",
"char = get_char(PROPERTIES.copy()) new_value = 3 char.set_value(new_value) assert char.value == new_value def test_set_value_valid_values():",
"char = get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value) def test_default_valid_value(): valid_values = {\"foo\": 2,",
"get_char(PROPERTIES.copy()) char.setter_callback = mock.Mock() char.set_value(3, should_callback=False) assert not char.setter_callback.called char.set_value(3, should_callback=True) assert char.setter_callback.called",
"= mock.Mock() char.set_value(3, should_callback=False) assert not char.setter_callback.called char.set_value(3, should_callback=True) assert char.setter_callback.called def test_override_properties_properties():",
"pyhap.characteristic import Characteristic PROPERTIES = { \"Format\": characteristic.HAP_FORMAT.INT, \"Permissions\": [characteristic.HAP_PERMISSIONS.READ] } def get_char(props,",
"\"\"\" Tests for pyhap.characteristic \"\"\" import uuid from unittest import mock import pytest",
"char.value) def test_default_valid_value(): valid_values = {\"foo\": 2, \"bar\": 3} char = get_char(PROPERTIES.copy(), valid=valid_values)",
"char.setter_callback.called char.set_value(3, should_callback=True) assert char.setter_callback.called def test_override_properties_properties(): new_properties = {'minValue': 10, 'maxValue': 20,",
"== raw_value assert char.get_hap_value() == max_value def test_notify(): char = get_char(PROPERTIES.copy()) broker_mock =",
"char.set_value(4) def test_set_value_callback_toggle(): char = get_char(PROPERTIES.copy()) char.setter_callback = mock.Mock() char.set_value(3, should_callback=False) assert not",
"\"bar\": 3, } char = get_char(PROPERTIES.copy(), valid=valid_values) with pytest.raises(ValueError): char.set_value(4) def test_set_value_callback_toggle(): char",
"test_set_value_callback_toggle(): char = get_char(PROPERTIES.copy()) char.setter_callback = mock.Mock() char.set_value(3, should_callback=False) assert not char.setter_callback.called char.set_value(3,",
"3, } char = get_char(PROPERTIES.copy(), valid=valid_values) with pytest.raises(ValueError): char.set_value(4) def test_set_value_callback_toggle(): char =",
"char = get_char(PROPERTIES.copy()) broker_mock = mock.Mock() char.broker = broker_mock notify_value = 3 expected",
"assert char.value in valid_values.values() def test_set_value(): char = get_char(PROPERTIES.copy()) new_value = 3 char.set_value(new_value)",
"valid is not None: props[\"ValidValues\"] = valid if min_value is not None: props[\"minValue\"]",
"char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues'] == new_valid_values def test_get_hap_value(): max_value = 5 raw_value = 6",
"valid if min_value is not None: props[\"minValue\"] = min_value if max_value is not",
"= get_char(PROPERTIES.copy(), valid=valid_values) assert char.value in valid_values.values() def test_set_value(): char = get_char(PROPERTIES.copy()) new_value",
"assert char.properties['minValue'] == new_properties['minValue'] assert char.properties['maxValue'] == new_properties['maxValue'] assert char.properties['step'] == new_properties['step'] def",
"get_char(PROPERTIES.copy(), valid={'foo': 1, 'bar': 2}) char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues'] == new_valid_values def test_get_hap_value(): max_value",
"valid={'foo': 1, 'bar': 2}) char.override_properties(valid_values=new_valid_values) assert char.properties['ValidValues'] == new_valid_values def test_get_hap_value(): max_value =",
"char.type_id, \"value\": notify_value, } char.value = notify_value char.notify() assert broker_mock.publish.called broker_mock.publish.assert_called_with(expected, char) def",
"{'foo2': 2, 'bar2': 3} char = get_char(PROPERTIES.copy(), valid={'foo': 1, 'bar': 2}) char.override_properties(valid_values=new_valid_values) assert",
"char = get_char(PROPERTIES.copy(), valid=valid_values) with pytest.raises(ValueError): char.set_value(4) def test_set_value_callback_toggle(): char = get_char(PROPERTIES.copy()) char.setter_callback",
"valid=valid_values) assert char.value in valid_values.values() def test_set_value(): char = get_char(PROPERTIES.copy()) new_value = 3",
"get_char(PROPERTIES.copy(), min_value=0, max_value=1) char.override_properties(properties=new_properties) assert char.properties['minValue'] == new_properties['minValue'] assert char.properties['maxValue'] == new_properties['maxValue'] assert",
"max_value c = Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(), properties=props) return c def test_default_value(): char =",
"} def get_char(props, valid=None, min_value=None, max_value=None): if valid is not None: props[\"ValidValues\"] =",
"new_valid_values = {'foo2': 2, 'bar2': 3} char = get_char(PROPERTIES.copy(), valid={'foo': 1, 'bar': 2})",
"uuid from unittest import mock import pytest import pyhap.characteristic as characteristic from pyhap.characteristic",
"def test_set_value(): char = get_char(PROPERTIES.copy()) new_value = 3 char.set_value(new_value) assert char.value == new_value",
"char.setter_callback.called def test_override_properties_properties(): new_properties = {'minValue': 10, 'maxValue': 20, 'step': 1} char =",
"props[\"maxValue\"] = max_value c = Characteristic(display_name=\"Test Char\", type_id=uuid.uuid1(), properties=props) return c def test_default_value():",
"= 5 raw_value = 6 char = get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value, should_notify=False) assert char.value",
"= mock.Mock() char.broker = broker_mock notify_value = 3 expected = { \"type_id\": char.type_id,",
"= get_char(PROPERTIES.copy()) new_value = 3 char.set_value(new_value) assert char.value == new_value def test_set_value_valid_values(): valid_values",
"= {\"foo\": 2, \"bar\": 3, } char = get_char(PROPERTIES.copy(), valid=valid_values) with pytest.raises(ValueError): char.set_value(4)",
"from unittest import mock import pytest import pyhap.characteristic as characteristic from pyhap.characteristic import",
"get_char(PROPERTIES.copy()) assert (characteristic.HAP_FORMAT.DEFAULT[PROPERTIES[\"Format\"]] == char.value) def test_default_valid_value(): valid_values = {\"foo\": 2, \"bar\": 3}",
"raw_value = 6 char = get_char(PROPERTIES.copy(), max_value=max_value) char.set_value(raw_value, should_notify=False) assert char.value == raw_value",
"def test_default_valid_value(): valid_values = {\"foo\": 2, \"bar\": 3} char = get_char(PROPERTIES.copy(), valid=valid_values) assert",
"1} char = get_char(PROPERTIES.copy(), min_value=0, max_value=1) char.override_properties(properties=new_properties) assert char.properties['minValue'] == new_properties['minValue'] assert char.properties['maxValue']",
"pytest.raises(ValueError): char.set_value(4) def test_set_value_callback_toggle(): char = get_char(PROPERTIES.copy()) char.setter_callback = mock.Mock() char.set_value(3, should_callback=False) assert",
"unittest import mock import pytest import pyhap.characteristic as characteristic from pyhap.characteristic import Characteristic",
"new_value = 3 char.set_value(new_value) assert char.value == new_value def test_set_value_valid_values(): valid_values = {\"foo\":",
"= valid if min_value is not None: props[\"minValue\"] = min_value if max_value is",
"= {'foo2': 2, 'bar2': 3} char = get_char(PROPERTIES.copy(), valid={'foo': 1, 'bar': 2}) char.override_properties(valid_values=new_valid_values)",
"{\"foo\": 2, \"bar\": 3} char = get_char(PROPERTIES.copy(), valid=valid_values) assert char.value in valid_values.values() def"
] |
[
"datasets.load_rossi() # Attention: duration column must be index 0, event column index 1",
"= RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10) rsf = rsf.fit(X, y) print(\"--- %s seconds ---\" %",
"y) print(\"--- %s seconds ---\" % (time.time() - start_time)) y_pred = rsf.predict(X_test) c_val",
"column index 1 in y y = rossi.loc[:, [\"arrest\", \"week\"]] X = rossi.drop([\"arrest\",",
"\"week\"], axis=1) X, X_test, y, y_test = train_test_split(X, y, test_size=0.25, random_state=10) print(\"RSF\") start_time",
"(time.time() - start_time)) y_pred = rsf.predict(X_test) c_val = concordance_index(y_time=y_test[\"week\"], y_pred=y_pred, y_event=y_test[\"arrest\"]) print(\"C-index\", round(c_val,",
"RandomSurvivalForest, concordance_index from lifelines import datasets from sklearn.model_selection import train_test_split import time rossi",
"= train_test_split(X, y, test_size=0.25, random_state=10) print(\"RSF\") start_time = time.time() rsf = RandomSurvivalForest(n_estimators=20, n_jobs=-1,",
"event column index 1 in y y = rossi.loc[:, [\"arrest\", \"week\"]] X =",
"= rossi.loc[:, [\"arrest\", \"week\"]] X = rossi.drop([\"arrest\", \"week\"], axis=1) X, X_test, y, y_test",
"random_survival_forest import RandomSurvivalForest, concordance_index from lifelines import datasets from sklearn.model_selection import train_test_split import",
"must be index 0, event column index 1 in y y = rossi.loc[:,",
"index 0, event column index 1 in y y = rossi.loc[:, [\"arrest\", \"week\"]]",
"index 1 in y y = rossi.loc[:, [\"arrest\", \"week\"]] X = rossi.drop([\"arrest\", \"week\"],",
"datasets from sklearn.model_selection import train_test_split import time rossi = datasets.load_rossi() # Attention: duration",
"y = rossi.loc[:, [\"arrest\", \"week\"]] X = rossi.drop([\"arrest\", \"week\"], axis=1) X, X_test, y,",
"random_state=10) print(\"RSF\") start_time = time.time() rsf = RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10) rsf = rsf.fit(X,",
"% (time.time() - start_time)) y_pred = rsf.predict(X_test) c_val = concordance_index(y_time=y_test[\"week\"], y_pred=y_pred, y_event=y_test[\"arrest\"]) print(\"C-index\",",
"X_test, y, y_test = train_test_split(X, y, test_size=0.25, random_state=10) print(\"RSF\") start_time = time.time() rsf",
"- start_time)) y_pred = rsf.predict(X_test) c_val = concordance_index(y_time=y_test[\"week\"], y_pred=y_pred, y_event=y_test[\"arrest\"]) print(\"C-index\", round(c_val, 3))",
"concordance_index from lifelines import datasets from sklearn.model_selection import train_test_split import time rossi =",
"rsf = rsf.fit(X, y) print(\"--- %s seconds ---\" % (time.time() - start_time)) y_pred",
"be index 0, event column index 1 in y y = rossi.loc[:, [\"arrest\",",
"from random_survival_forest import RandomSurvivalForest, concordance_index from lifelines import datasets from sklearn.model_selection import train_test_split",
"= rossi.drop([\"arrest\", \"week\"], axis=1) X, X_test, y, y_test = train_test_split(X, y, test_size=0.25, random_state=10)",
"seconds ---\" % (time.time() - start_time)) y_pred = rsf.predict(X_test) c_val = concordance_index(y_time=y_test[\"week\"], y_pred=y_pred,",
"rossi.loc[:, [\"arrest\", \"week\"]] X = rossi.drop([\"arrest\", \"week\"], axis=1) X, X_test, y, y_test =",
"X = rossi.drop([\"arrest\", \"week\"], axis=1) X, X_test, y, y_test = train_test_split(X, y, test_size=0.25,",
"time.time() rsf = RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10) rsf = rsf.fit(X, y) print(\"--- %s seconds",
"y_test = train_test_split(X, y, test_size=0.25, random_state=10) print(\"RSF\") start_time = time.time() rsf = RandomSurvivalForest(n_estimators=20,",
"rsf = RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10) rsf = rsf.fit(X, y) print(\"--- %s seconds ---\"",
"import RandomSurvivalForest, concordance_index from lifelines import datasets from sklearn.model_selection import train_test_split import time",
"print(\"--- %s seconds ---\" % (time.time() - start_time)) y_pred = rsf.predict(X_test) c_val =",
"[\"arrest\", \"week\"]] X = rossi.drop([\"arrest\", \"week\"], axis=1) X, X_test, y, y_test = train_test_split(X,",
"Attention: duration column must be index 0, event column index 1 in y",
"rossi.drop([\"arrest\", \"week\"], axis=1) X, X_test, y, y_test = train_test_split(X, y, test_size=0.25, random_state=10) print(\"RSF\")",
"# Attention: duration column must be index 0, event column index 1 in",
"RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10) rsf = rsf.fit(X, y) print(\"--- %s seconds ---\" % (time.time()",
"time rossi = datasets.load_rossi() # Attention: duration column must be index 0, event",
"train_test_split import time rossi = datasets.load_rossi() # Attention: duration column must be index",
"from sklearn.model_selection import train_test_split import time rossi = datasets.load_rossi() # Attention: duration column",
"duration column must be index 0, event column index 1 in y y",
"in y y = rossi.loc[:, [\"arrest\", \"week\"]] X = rossi.drop([\"arrest\", \"week\"], axis=1) X,",
"= time.time() rsf = RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10) rsf = rsf.fit(X, y) print(\"--- %s",
"rossi = datasets.load_rossi() # Attention: duration column must be index 0, event column",
"X, X_test, y, y_test = train_test_split(X, y, test_size=0.25, random_state=10) print(\"RSF\") start_time = time.time()",
"lifelines import datasets from sklearn.model_selection import train_test_split import time rossi = datasets.load_rossi() #",
"import time rossi = datasets.load_rossi() # Attention: duration column must be index 0,",
"0, event column index 1 in y y = rossi.loc[:, [\"arrest\", \"week\"]] X",
"1 in y y = rossi.loc[:, [\"arrest\", \"week\"]] X = rossi.drop([\"arrest\", \"week\"], axis=1)",
"%s seconds ---\" % (time.time() - start_time)) y_pred = rsf.predict(X_test) c_val = concordance_index(y_time=y_test[\"week\"],",
"n_jobs=-1, min_leaf=10) rsf = rsf.fit(X, y) print(\"--- %s seconds ---\" % (time.time() -",
"y, test_size=0.25, random_state=10) print(\"RSF\") start_time = time.time() rsf = RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10) rsf",
"from lifelines import datasets from sklearn.model_selection import train_test_split import time rossi = datasets.load_rossi()",
"\"week\"]] X = rossi.drop([\"arrest\", \"week\"], axis=1) X, X_test, y, y_test = train_test_split(X, y,",
"y, y_test = train_test_split(X, y, test_size=0.25, random_state=10) print(\"RSF\") start_time = time.time() rsf =",
"column must be index 0, event column index 1 in y y =",
"train_test_split(X, y, test_size=0.25, random_state=10) print(\"RSF\") start_time = time.time() rsf = RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10)",
"print(\"RSF\") start_time = time.time() rsf = RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10) rsf = rsf.fit(X, y)",
"= rsf.fit(X, y) print(\"--- %s seconds ---\" % (time.time() - start_time)) y_pred =",
"test_size=0.25, random_state=10) print(\"RSF\") start_time = time.time() rsf = RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10) rsf =",
"y y = rossi.loc[:, [\"arrest\", \"week\"]] X = rossi.drop([\"arrest\", \"week\"], axis=1) X, X_test,",
"min_leaf=10) rsf = rsf.fit(X, y) print(\"--- %s seconds ---\" % (time.time() - start_time))",
"axis=1) X, X_test, y, y_test = train_test_split(X, y, test_size=0.25, random_state=10) print(\"RSF\") start_time =",
"import train_test_split import time rossi = datasets.load_rossi() # Attention: duration column must be",
"sklearn.model_selection import train_test_split import time rossi = datasets.load_rossi() # Attention: duration column must",
"rsf.fit(X, y) print(\"--- %s seconds ---\" % (time.time() - start_time)) y_pred = rsf.predict(X_test)",
"---\" % (time.time() - start_time)) y_pred = rsf.predict(X_test) c_val = concordance_index(y_time=y_test[\"week\"], y_pred=y_pred, y_event=y_test[\"arrest\"])",
"= datasets.load_rossi() # Attention: duration column must be index 0, event column index",
"import datasets from sklearn.model_selection import train_test_split import time rossi = datasets.load_rossi() # Attention:",
"start_time = time.time() rsf = RandomSurvivalForest(n_estimators=20, n_jobs=-1, min_leaf=10) rsf = rsf.fit(X, y) print(\"---"
] |
[
"the platform devices (compute) puppet resource. \"\"\" device_config = {} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE]",
"{ 'qat_idx': idx, \"device_id\": \"dh895xcc\", } device_config.update({name: dev}) if len(device_config) == 0: return",
"configuration only required for compute hosts return {} devices = self._get_device_id_index(host) if len(devices)",
"host.subfunctions: # configuration only required for compute hosts return {} devices = self._get_device_id_index(host)",
"len(devices) == 0: # no pci devices on the system return {} device_config",
"sysinv.puppet import base class DevicePuppet(base.BasePuppet): \"\"\"Class to encapsulate puppet operations for device configuration\"\"\"",
"dictionary for QAT devices to be used by the platform devices (compute) puppet",
"<reponame>etaivan/stx-config<filename>sysinv/sysinv/sysinv/sysinv/puppet/device.py # # Copyright (c) 2017 Wind River Systems, Inc. # # SPDX-License-Identifier:",
"pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) != 0: for idx, device in enumerate(qat_c62x_devices): name = 'pci-%s'",
"0: # no pci devices on the system return {} device_config = {}",
"to be used by the platform devices (compute) puppet resource. \"\"\" device_config =",
"devices = self._get_device_id_index(host) if len(devices) == 0: # no pci devices on the",
"= collections.defaultdict(list) for device in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return devices def _get_host_qat_device_config(self, pci_device_list): \"\"\"",
"required for compute hosts return {} devices = self._get_device_id_index(host) if len(devices) == 0:",
"self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return devices def _get_host_qat_device_config(self, pci_device_list): \"\"\" Builds a config dictionary for",
"on the system return {} device_config = {} qat_devices = self._get_host_qat_device_config(devices) if qat_devices:",
"by device id. \"\"\" devices = collections.defaultdict(list) for device in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return",
"= { 'qat_idx': idx, \"device_id\": \"c62x\", } device_config.update({name: dev}) qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if",
"== 0: return {} return { 'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled': True, } def get_host_config(self,",
"QAT devices to be used by the platform devices (compute) puppet resource. \"\"\"",
"(c) 2017 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import collections",
"} def get_host_config(self, host): if constants.WORKER not in host.subfunctions: # configuration only required",
"host): if constants.WORKER not in host.subfunctions: # configuration only required for compute hosts",
"dev}) qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices) != 0: for idx, device in enumerate(qat_dh895xcc_devices):",
"of device lists indexed by device id. \"\"\" devices = collections.defaultdict(list) for device",
"\"\"\"Class to encapsulate puppet operations for device configuration\"\"\" def _get_device_id_index(self, host): \"\"\" Builds",
"puppet operations for device configuration\"\"\" def _get_device_id_index(self, host): \"\"\" Builds a dictionary of",
"\"\"\" Builds a dictionary of device lists indexed by device id. \"\"\" devices",
"!= 0: for idx, device in enumerate(qat_c62x_devices): name = 'pci-%s' % device.pciaddr dev",
"idx, device in enumerate(qat_dh895xcc_devices): name = 'pci-%s' % device.pciaddr dev = { 'qat_idx':",
"platform devices (compute) puppet resource. \"\"\" device_config = {} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if",
"system return {} device_config = {} qat_devices = self._get_host_qat_device_config(devices) if qat_devices: device_config.update(qat_devices) return",
"device_config = {} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) != 0: for idx, device",
"device in enumerate(qat_dh895xcc_devices): name = 'pci-%s' % device.pciaddr dev = { 'qat_idx': idx,",
"from sysinv.puppet import base class DevicePuppet(base.BasePuppet): \"\"\"Class to encapsulate puppet operations for device",
"{} devices = self._get_device_id_index(host) if len(devices) == 0: # no pci devices on",
"2017 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import collections from",
"Copyright (c) 2017 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import",
"config dictionary for QAT devices to be used by the platform devices (compute)",
"% device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"dh895xcc\", } device_config.update({name: dev}) if",
"\"\"\" Builds a config dictionary for QAT devices to be used by the",
"host): \"\"\" Builds a dictionary of device lists indexed by device id. \"\"\"",
"\"c62x\", } device_config.update({name: dev}) qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices) != 0: for idx,",
"# # Copyright (c) 2017 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0",
"'qat_idx': idx, \"device_id\": \"dh895xcc\", } device_config.update({name: dev}) if len(device_config) == 0: return {}",
"(compute) puppet resource. \"\"\" device_config = {} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) !=",
"device_config.update({name: dev}) if len(device_config) == 0: return {} return { 'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled':",
"device lists indexed by device id. \"\"\" devices = collections.defaultdict(list) for device in",
"return devices def _get_host_qat_device_config(self, pci_device_list): \"\"\" Builds a config dictionary for QAT devices",
"encapsulate puppet operations for device configuration\"\"\" def _get_device_id_index(self, host): \"\"\" Builds a dictionary",
"return { 'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled': True, } def get_host_config(self, host): if constants.WORKER not",
"not in host.subfunctions: # configuration only required for compute hosts return {} devices",
"enumerate(qat_dh895xcc_devices): name = 'pci-%s' % device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"dh895xcc\",",
"device in enumerate(qat_c62x_devices): name = 'pci-%s' % device.pciaddr dev = { 'qat_idx': idx,",
"Builds a config dictionary for QAT devices to be used by the platform",
"# configuration only required for compute hosts return {} devices = self._get_device_id_index(host) if",
"devices = collections.defaultdict(list) for device in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return devices def _get_host_qat_device_config(self, pci_device_list):",
"= pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) != 0: for idx, device in enumerate(qat_c62x_devices): name =",
"Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import collections from sysinv.common",
"= {} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) != 0: for idx, device in",
"operations for device configuration\"\"\" def _get_device_id_index(self, host): \"\"\" Builds a dictionary of device",
"return {} device_config = {} qat_devices = self._get_host_qat_device_config(devices) if qat_devices: device_config.update(qat_devices) return device_config",
"for device in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return devices def _get_host_qat_device_config(self, pci_device_list): \"\"\" Builds a",
"devices to be used by the platform devices (compute) puppet resource. \"\"\" device_config",
"'qat_idx': idx, \"device_id\": \"c62x\", } device_config.update({name: dev}) qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices) !=",
"'pci-%s' % device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"dh895xcc\", } device_config.update({name: dev})",
"indexed by device id. \"\"\" devices = collections.defaultdict(list) for device in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device)",
"'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled': True, } def get_host_config(self, host): if constants.WORKER not in host.subfunctions:",
"def get_host_config(self, host): if constants.WORKER not in host.subfunctions: # configuration only required for",
"a dictionary of device lists indexed by device id. \"\"\" devices = collections.defaultdict(list)",
"devices on the system return {} device_config = {} qat_devices = self._get_host_qat_device_config(devices) if",
"\"\"\" device_config = {} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) != 0: for idx,",
"{ 'qat_idx': idx, \"device_id\": \"c62x\", } device_config.update({name: dev}) qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices)",
"import constants from sysinv.puppet import base class DevicePuppet(base.BasePuppet): \"\"\"Class to encapsulate puppet operations",
"Inc. # # SPDX-License-Identifier: Apache-2.0 # import collections from sysinv.common import constants from",
"puppet resource. \"\"\" device_config = {} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) != 0:",
"a config dictionary for QAT devices to be used by the platform devices",
"True, } def get_host_config(self, host): if constants.WORKER not in host.subfunctions: # configuration only",
"== 0: # no pci devices on the system return {} device_config =",
"idx, device in enumerate(qat_c62x_devices): name = 'pci-%s' % device.pciaddr dev = { 'qat_idx':",
"device_config.update({name: dev}) qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices) != 0: for idx, device in",
"SPDX-License-Identifier: Apache-2.0 # import collections from sysinv.common import constants from sysinv.puppet import base",
"= 'pci-%s' % device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"c62x\", } device_config.update({name:",
"= self._get_device_id_index(host) if len(devices) == 0: # no pci devices on the system",
"for idx, device in enumerate(qat_dh895xcc_devices): name = 'pci-%s' % device.pciaddr dev = {",
"collections from sysinv.common import constants from sysinv.puppet import base class DevicePuppet(base.BasePuppet): \"\"\"Class to",
"device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"dh895xcc\", } device_config.update({name: dev}) if len(device_config)",
"if constants.WORKER not in host.subfunctions: # configuration only required for compute hosts return",
"used by the platform devices (compute) puppet resource. \"\"\" device_config = {} qat_c62x_devices",
"{ 'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled': True, } def get_host_config(self, host): if constants.WORKER not in",
"be used by the platform devices (compute) puppet resource. \"\"\" device_config = {}",
"return {} devices = self._get_device_id_index(host) if len(devices) == 0: # no pci devices",
"{} return { 'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled': True, } def get_host_config(self, host): if constants.WORKER",
"\"device_id\": \"dh895xcc\", } device_config.update({name: dev}) if len(device_config) == 0: return {} return {",
"in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return devices def _get_host_qat_device_config(self, pci_device_list): \"\"\" Builds a config dictionary",
"if len(device_config) == 0: return {} return { 'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled': True, }",
"len(device_config) == 0: return {} return { 'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled': True, } def",
"DevicePuppet(base.BasePuppet): \"\"\"Class to encapsulate puppet operations for device configuration\"\"\" def _get_device_id_index(self, host): \"\"\"",
"'platform::devices::qat::service_enabled': True, } def get_host_config(self, host): if constants.WORKER not in host.subfunctions: # configuration",
"dev}) if len(device_config) == 0: return {} return { 'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled': True,",
"class DevicePuppet(base.BasePuppet): \"\"\"Class to encapsulate puppet operations for device configuration\"\"\" def _get_device_id_index(self, host):",
"name = 'pci-%s' % device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"dh895xcc\", }",
"len(qat_dh895xcc_devices) != 0: for idx, device in enumerate(qat_dh895xcc_devices): name = 'pci-%s' % device.pciaddr",
"in enumerate(qat_dh895xcc_devices): name = 'pci-%s' % device.pciaddr dev = { 'qat_idx': idx, \"device_id\":",
"% device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"c62x\", } device_config.update({name: dev}) qat_dh895xcc_devices",
"devices (compute) puppet resource. \"\"\" device_config = {} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices)",
"constants from sysinv.puppet import base class DevicePuppet(base.BasePuppet): \"\"\"Class to encapsulate puppet operations for",
"sysinv.common import constants from sysinv.puppet import base class DevicePuppet(base.BasePuppet): \"\"\"Class to encapsulate puppet",
"import base class DevicePuppet(base.BasePuppet): \"\"\"Class to encapsulate puppet operations for device configuration\"\"\" def",
"device id. \"\"\" devices = collections.defaultdict(list) for device in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return devices",
"device configuration\"\"\" def _get_device_id_index(self, host): \"\"\" Builds a dictionary of device lists indexed",
"resource. \"\"\" device_config = {} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) != 0: for",
"Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import collections from sysinv.common import constants",
"for idx, device in enumerate(qat_c62x_devices): name = 'pci-%s' % device.pciaddr dev = {",
"idx, \"device_id\": \"c62x\", } device_config.update({name: dev}) qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices) != 0:",
"dev = { 'qat_idx': idx, \"device_id\": \"dh895xcc\", } device_config.update({name: dev}) if len(device_config) ==",
"hosts return {} devices = self._get_device_id_index(host) if len(devices) == 0: # no pci",
"self._get_device_id_index(host) if len(devices) == 0: # no pci devices on the system return",
"# no pci devices on the system return {} device_config = {} qat_devices",
"{} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) != 0: for idx, device in enumerate(qat_c62x_devices):",
"device in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return devices def _get_host_qat_device_config(self, pci_device_list): \"\"\" Builds a config",
"# # SPDX-License-Identifier: Apache-2.0 # import collections from sysinv.common import constants from sysinv.puppet",
"qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) != 0: for idx, device in enumerate(qat_c62x_devices): name",
"} device_config.update({name: dev}) if len(device_config) == 0: return {} return { 'platform::devices::qat::device_config': device_config,",
"'pci-%s' % device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"c62x\", } device_config.update({name: dev})",
"compute hosts return {} devices = self._get_device_id_index(host) if len(devices) == 0: # no",
"len(qat_c62x_devices) != 0: for idx, device in enumerate(qat_c62x_devices): name = 'pci-%s' % device.pciaddr",
"!= 0: for idx, device in enumerate(qat_dh895xcc_devices): name = 'pci-%s' % device.pciaddr dev",
"from sysinv.common import constants from sysinv.puppet import base class DevicePuppet(base.BasePuppet): \"\"\"Class to encapsulate",
"to encapsulate puppet operations for device configuration\"\"\" def _get_device_id_index(self, host): \"\"\" Builds a",
"in host.subfunctions: # configuration only required for compute hosts return {} devices =",
"# Copyright (c) 2017 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 #",
"for QAT devices to be used by the platform devices (compute) puppet resource.",
"for compute hosts return {} devices = self._get_device_id_index(host) if len(devices) == 0: #",
"dictionary of device lists indexed by device id. \"\"\" devices = collections.defaultdict(list) for",
"device_config, 'platform::devices::qat::service_enabled': True, } def get_host_config(self, host): if constants.WORKER not in host.subfunctions: #",
"= 'pci-%s' % device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"dh895xcc\", } device_config.update({name:",
"= pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices) != 0: for idx, device in enumerate(qat_dh895xcc_devices): name =",
"pci_device_list): \"\"\" Builds a config dictionary for QAT devices to be used by",
"by the platform devices (compute) puppet resource. \"\"\" device_config = {} qat_c62x_devices =",
"Builds a dictionary of device lists indexed by device id. \"\"\" devices =",
"for device configuration\"\"\" def _get_device_id_index(self, host): \"\"\" Builds a dictionary of device lists",
"if len(devices) == 0: # no pci devices on the system return {}",
"qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices) != 0: for idx, device in enumerate(qat_dh895xcc_devices): name",
"id. \"\"\" devices = collections.defaultdict(list) for device in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return devices def",
"pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices) != 0: for idx, device in enumerate(qat_dh895xcc_devices): name = 'pci-%s'",
"constants.WORKER not in host.subfunctions: # configuration only required for compute hosts return {}",
"idx, \"device_id\": \"dh895xcc\", } device_config.update({name: dev}) if len(device_config) == 0: return {} return",
"} device_config.update({name: dev}) qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices) != 0: for idx, device",
"\"\"\" devices = collections.defaultdict(list) for device in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return devices def _get_host_qat_device_config(self,",
"0: return {} return { 'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled': True, } def get_host_config(self, host):",
"= { 'qat_idx': idx, \"device_id\": \"dh895xcc\", } device_config.update({name: dev}) if len(device_config) == 0:",
"devices def _get_host_qat_device_config(self, pci_device_list): \"\"\" Builds a config dictionary for QAT devices to",
"no pci devices on the system return {} device_config = {} qat_devices =",
"_get_device_id_index(self, host): \"\"\" Builds a dictionary of device lists indexed by device id.",
"if len(qat_c62x_devices) != 0: for idx, device in enumerate(qat_c62x_devices): name = 'pci-%s' %",
"def _get_host_qat_device_config(self, pci_device_list): \"\"\" Builds a config dictionary for QAT devices to be",
"return {} return { 'platform::devices::qat::device_config': device_config, 'platform::devices::qat::service_enabled': True, } def get_host_config(self, host): if",
"configuration\"\"\" def _get_device_id_index(self, host): \"\"\" Builds a dictionary of device lists indexed by",
"# import collections from sysinv.common import constants from sysinv.puppet import base class DevicePuppet(base.BasePuppet):",
"0: for idx, device in enumerate(qat_dh895xcc_devices): name = 'pci-%s' % device.pciaddr dev =",
"lists indexed by device id. \"\"\" devices = collections.defaultdict(list) for device in self.dbapi.pci_device_get_all(hostid=host.id):",
"import collections from sysinv.common import constants from sysinv.puppet import base class DevicePuppet(base.BasePuppet): \"\"\"Class",
"base class DevicePuppet(base.BasePuppet): \"\"\"Class to encapsulate puppet operations for device configuration\"\"\" def _get_device_id_index(self,",
"_get_host_qat_device_config(self, pci_device_list): \"\"\" Builds a config dictionary for QAT devices to be used",
"name = 'pci-%s' % device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"c62x\", }",
"pci devices on the system return {} device_config = {} qat_devices = self._get_host_qat_device_config(devices)",
"dev = { 'qat_idx': idx, \"device_id\": \"c62x\", } device_config.update({name: dev}) qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE]",
"River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import collections from sysinv.common import",
"collections.defaultdict(list) for device in self.dbapi.pci_device_get_all(hostid=host.id): devices[device.pdevice_id].append(device) return devices def _get_host_qat_device_config(self, pci_device_list): \"\"\" Builds",
"in enumerate(qat_c62x_devices): name = 'pci-%s' % device.pciaddr dev = { 'qat_idx': idx, \"device_id\":",
"0: for idx, device in enumerate(qat_c62x_devices): name = 'pci-%s' % device.pciaddr dev =",
"devices[device.pdevice_id].append(device) return devices def _get_host_qat_device_config(self, pci_device_list): \"\"\" Builds a config dictionary for QAT",
"device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"c62x\", } device_config.update({name: dev}) qat_dh895xcc_devices =",
"enumerate(qat_c62x_devices): name = 'pci-%s' % device.pciaddr dev = { 'qat_idx': idx, \"device_id\": \"c62x\",",
"Apache-2.0 # import collections from sysinv.common import constants from sysinv.puppet import base class",
"if len(qat_dh895xcc_devices) != 0: for idx, device in enumerate(qat_dh895xcc_devices): name = 'pci-%s' %",
"get_host_config(self, host): if constants.WORKER not in host.subfunctions: # configuration only required for compute",
"# SPDX-License-Identifier: Apache-2.0 # import collections from sysinv.common import constants from sysinv.puppet import",
"def _get_device_id_index(self, host): \"\"\" Builds a dictionary of device lists indexed by device",
"\"device_id\": \"c62x\", } device_config.update({name: dev}) qat_dh895xcc_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_DH895XCC_PF_DEVICE] if len(qat_dh895xcc_devices) != 0: for",
"only required for compute hosts return {} devices = self._get_device_id_index(host) if len(devices) ==",
"the system return {} device_config = {} qat_devices = self._get_host_qat_device_config(devices) if qat_devices: device_config.update(qat_devices)",
"\"dh895xcc\", } device_config.update({name: dev}) if len(device_config) == 0: return {} return { 'platform::devices::qat::device_config':"
] |
[
"-1 minimum = 0 result = None while (result != target): m =",
"< midPoint): maximum = m -1 else: return m result = midPoint return",
"while (result != target): m = (maximum + minimum) // 2 midPoint =",
"len(list) -1 minimum = 0 result = None while (result != target): m",
"> midPoint): minimum = m +1 elif(target < midPoint): maximum = m -1",
"if(target > midPoint): minimum = m +1 elif(target < midPoint): maximum = m",
"(result != target): m = (maximum + minimum) // 2 midPoint = list[m]",
"// 2 midPoint = list[m] if(target > midPoint): minimum = m +1 elif(target",
"= 0 result = None while (result != target): m = (maximum +",
"int(input(\"enter search target: \")) def binarySearch(list,target): maximum = len(list) -1 minimum = 0",
"= (maximum + minimum) // 2 midPoint = list[m] if(target > midPoint): minimum",
"search target: \")) def binarySearch(list,target): maximum = len(list) -1 minimum = 0 result",
"elif(target < midPoint): maximum = m -1 else: return m result = midPoint",
"def binarySearch(list,target): maximum = len(list) -1 minimum = 0 result = None while",
"target: \")) def binarySearch(list,target): maximum = len(list) -1 minimum = 0 result =",
"None while (result != target): m = (maximum + minimum) // 2 midPoint",
"= int(input(\"enter search target: \")) def binarySearch(list,target): maximum = len(list) -1 minimum =",
"target = int(input(\"enter search target: \")) def binarySearch(list,target): maximum = len(list) -1 minimum",
"target): m = (maximum + minimum) // 2 midPoint = list[m] if(target >",
"midPoint = list[m] if(target > midPoint): minimum = m +1 elif(target < midPoint):",
"= list[m] if(target > midPoint): minimum = m +1 elif(target < midPoint): maximum",
"list[m] if(target > midPoint): minimum = m +1 elif(target < midPoint): maximum =",
"m +1 elif(target < midPoint): maximum = m -1 else: return m result",
"binarySearch(list,target): maximum = len(list) -1 minimum = 0 result = None while (result",
"midPoint): maximum = m -1 else: return m result = midPoint return m",
"0 result = None while (result != target): m = (maximum + minimum)",
"(maximum + minimum) // 2 midPoint = list[m] if(target > midPoint): minimum =",
"minimum = m +1 elif(target < midPoint): maximum = m -1 else: return",
"maximum = len(list) -1 minimum = 0 result = None while (result !=",
"= None while (result != target): m = (maximum + minimum) // 2",
"result = None while (result != target): m = (maximum + minimum) //",
"minimum) // 2 midPoint = list[m] if(target > midPoint): minimum = m +1",
"+1 elif(target < midPoint): maximum = m -1 else: return m result =",
"midPoint): minimum = m +1 elif(target < midPoint): maximum = m -1 else:",
"= len(list) -1 minimum = 0 result = None while (result != target):",
"maximum = m -1 else: return m result = midPoint return m print(binarySearch([1,2,3,4,5,6,7,8,9,10],target))",
"!= target): m = (maximum + minimum) // 2 midPoint = list[m] if(target",
"\")) def binarySearch(list,target): maximum = len(list) -1 minimum = 0 result = None",
"minimum = 0 result = None while (result != target): m = (maximum",
"2 midPoint = list[m] if(target > midPoint): minimum = m +1 elif(target <",
"+ minimum) // 2 midPoint = list[m] if(target > midPoint): minimum = m",
"m = (maximum + minimum) // 2 midPoint = list[m] if(target > midPoint):",
"= m +1 elif(target < midPoint): maximum = m -1 else: return m"
] |
[
"from accounts.views import login, send_login_email app_name = 'accounts' urlpatterns = [ path(\"send_login_email\", send_login_email,",
"accounts.views import login, send_login_email app_name = 'accounts' urlpatterns = [ path(\"send_login_email\", send_login_email, name=\"send_login_email\"),",
"import LogoutView from django.urls import path from accounts.views import login, send_login_email app_name =",
"django.urls import path from accounts.views import login, send_login_email app_name = 'accounts' urlpatterns =",
"django.contrib.auth.views import LogoutView from django.urls import path from accounts.views import login, send_login_email app_name",
"import login, send_login_email app_name = 'accounts' urlpatterns = [ path(\"send_login_email\", send_login_email, name=\"send_login_email\"), path(\"login\",",
"path from accounts.views import login, send_login_email app_name = 'accounts' urlpatterns = [ path(\"send_login_email\",",
"login, send_login_email app_name = 'accounts' urlpatterns = [ path(\"send_login_email\", send_login_email, name=\"send_login_email\"), path(\"login\", login,",
"app_name = 'accounts' urlpatterns = [ path(\"send_login_email\", send_login_email, name=\"send_login_email\"), path(\"login\", login, name=\"login\"), path('logout',",
"<filename>accounts/urls.py<gh_stars>1-10 from django.contrib.auth.views import LogoutView from django.urls import path from accounts.views import login,",
"send_login_email app_name = 'accounts' urlpatterns = [ path(\"send_login_email\", send_login_email, name=\"send_login_email\"), path(\"login\", login, name=\"login\"),",
"'accounts' urlpatterns = [ path(\"send_login_email\", send_login_email, name=\"send_login_email\"), path(\"login\", login, name=\"login\"), path('logout', LogoutView.as_view(), name='logout'),",
"from django.contrib.auth.views import LogoutView from django.urls import path from accounts.views import login, send_login_email",
"from django.urls import path from accounts.views import login, send_login_email app_name = 'accounts' urlpatterns",
"urlpatterns = [ path(\"send_login_email\", send_login_email, name=\"send_login_email\"), path(\"login\", login, name=\"login\"), path('logout', LogoutView.as_view(), name='logout'), ]",
"= 'accounts' urlpatterns = [ path(\"send_login_email\", send_login_email, name=\"send_login_email\"), path(\"login\", login, name=\"login\"), path('logout', LogoutView.as_view(),",
"LogoutView from django.urls import path from accounts.views import login, send_login_email app_name = 'accounts'",
"import path from accounts.views import login, send_login_email app_name = 'accounts' urlpatterns = ["
] |
[] |
[
"kernelized_vector)) theta_0= (theta_0 + labels[i]) print(theta) else: theta_0= theta_0 theta= theta return((theta, theta_0))",
"return np.array((1 + np.dot(data_vector, data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix, labels, T): # Your code here",
"if (labels[i]*(np.dot(kernelized_vector, theta) + theta_0))[1] <= 0: theta= theta + (np.dot(labels[i], kernelized_vector)) theta_0=",
"T): # Your code here theta_0 = 0 theta= np.zeros(len(feature_matrix[0])) for epoch in",
"here theta_0 = 0 theta= np.zeros(len(feature_matrix[0])) for epoch in range(T): for i, x",
"in range(T): for i, x in enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector, theta) +",
"np.array([[0,0], [2,0],[3,0], [0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector): return np.array((1 + np.dot(data_vector, data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix, labels,",
"0 theta= np.zeros(len(feature_matrix[0])) for epoch in range(T): for i, x in enumerate(feature_matrix): kernelized_vector=",
"# Your code here theta_0 = 0 theta= np.zeros(len(feature_matrix[0])) for epoch in range(T):",
"np.zeros(len(feature_matrix[0])) for epoch in range(T): for i, x in enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i]) if",
"+ theta_0))[1] <= 0: theta= theta + (np.dot(labels[i], kernelized_vector)) theta_0= (theta_0 + labels[i])",
"theta) + theta_0))[1] <= 0: theta= theta + (np.dot(labels[i], kernelized_vector)) theta_0= (theta_0 +",
"theta= np.zeros(len(feature_matrix[0])) for epoch in range(T): for i, x in enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i])",
"theta + (np.dot(labels[i], kernelized_vector)) theta_0= (theta_0 + labels[i]) print(theta) else: theta_0= theta_0 theta=",
"np classification_vector= np.array([-1,-1,-1,-1,-1,1,1,1,1,1]) data_vector= np.array([[0,0], [2,0],[3,0], [0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector): return np.array((1 + np.dot(data_vector,",
"[0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector): return np.array((1 + np.dot(data_vector, data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix, labels, T): #",
"def quadratic_kernel(data_vector): return np.array((1 + np.dot(data_vector, data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix, labels, T): # Your",
"+ np.dot(data_vector, data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix, labels, T): # Your code here theta_0 =",
"<= 0: theta= theta + (np.dot(labels[i], kernelized_vector)) theta_0= (theta_0 + labels[i]) print(theta) else:",
"np.array([-1,-1,-1,-1,-1,1,1,1,1,1]) data_vector= np.array([[0,0], [2,0],[3,0], [0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector): return np.array((1 + np.dot(data_vector, data_vector.T))**2) def",
"data_vector= np.array([[0,0], [2,0],[3,0], [0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector): return np.array((1 + np.dot(data_vector, data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix,",
"def perceptron_quadratic_kernel(feature_matrix, labels, T): # Your code here theta_0 = 0 theta= np.zeros(len(feature_matrix[0]))",
"for i, x in enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector, theta) + theta_0))[1] <=",
"numpy as np classification_vector= np.array([-1,-1,-1,-1,-1,1,1,1,1,1]) data_vector= np.array([[0,0], [2,0],[3,0], [0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector): return np.array((1",
"for epoch in range(T): for i, x in enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector,",
"x in enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector, theta) + theta_0))[1] <= 0: theta=",
"theta_0 = 0 theta= np.zeros(len(feature_matrix[0])) for epoch in range(T): for i, x in",
"classification_vector= np.array([-1,-1,-1,-1,-1,1,1,1,1,1]) data_vector= np.array([[0,0], [2,0],[3,0], [0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector): return np.array((1 + np.dot(data_vector, data_vector.T))**2)",
"enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector, theta) + theta_0))[1] <= 0: theta= theta +",
"labels, T): # Your code here theta_0 = 0 theta= np.zeros(len(feature_matrix[0])) for epoch",
"i, x in enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector, theta) + theta_0))[1] <= 0:",
"kernelized_vector= quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector, theta) + theta_0))[1] <= 0: theta= theta + (np.dot(labels[i],",
"import numpy as np classification_vector= np.array([-1,-1,-1,-1,-1,1,1,1,1,1]) data_vector= np.array([[0,0], [2,0],[3,0], [0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector): return",
"= 0 theta= np.zeros(len(feature_matrix[0])) for epoch in range(T): for i, x in enumerate(feature_matrix):",
"as np classification_vector= np.array([-1,-1,-1,-1,-1,1,1,1,1,1]) data_vector= np.array([[0,0], [2,0],[3,0], [0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector): return np.array((1 +",
"np.dot(data_vector, data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix, labels, T): # Your code here theta_0 = 0",
"np.array((1 + np.dot(data_vector, data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix, labels, T): # Your code here theta_0",
"theta= theta + (np.dot(labels[i], kernelized_vector)) theta_0= (theta_0 + labels[i]) print(theta) else: theta_0= theta_0",
"range(T): for i, x in enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector, theta) + theta_0))[1]",
"perceptron_quadratic_kernel(feature_matrix, labels, T): # Your code here theta_0 = 0 theta= np.zeros(len(feature_matrix[0])) for",
"theta_0))[1] <= 0: theta= theta + (np.dot(labels[i], kernelized_vector)) theta_0= (theta_0 + labels[i]) print(theta)",
"(labels[i]*(np.dot(kernelized_vector, theta) + theta_0))[1] <= 0: theta= theta + (np.dot(labels[i], kernelized_vector)) theta_0= (theta_0",
"0: theta= theta + (np.dot(labels[i], kernelized_vector)) theta_0= (theta_0 + labels[i]) print(theta) else: theta_0=",
"(np.dot(labels[i], kernelized_vector)) theta_0= (theta_0 + labels[i]) print(theta) else: theta_0= theta_0 theta= theta return((theta,",
"epoch in range(T): for i, x in enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector, theta)",
"Your code here theta_0 = 0 theta= np.zeros(len(feature_matrix[0])) for epoch in range(T): for",
"quadratic_kernel(data_vector): return np.array((1 + np.dot(data_vector, data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix, labels, T): # Your code",
"<gh_stars>1-10 import numpy as np classification_vector= np.array([-1,-1,-1,-1,-1,1,1,1,1,1]) data_vector= np.array([[0,0], [2,0],[3,0], [0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector):",
"in enumerate(feature_matrix): kernelized_vector= quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector, theta) + theta_0))[1] <= 0: theta= theta",
"data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix, labels, T): # Your code here theta_0 = 0 theta=",
"+ (np.dot(labels[i], kernelized_vector)) theta_0= (theta_0 + labels[i]) print(theta) else: theta_0= theta_0 theta= theta",
"quadratic_kernel(feature_matrix[i]) if (labels[i]*(np.dot(kernelized_vector, theta) + theta_0))[1] <= 0: theta= theta + (np.dot(labels[i], kernelized_vector))",
"code here theta_0 = 0 theta= np.zeros(len(feature_matrix[0])) for epoch in range(T): for i,",
"[2,0],[3,0], [0,2],[2,2],[5,1],[5,2],[2,4],[4,4],[5,5]]) def quadratic_kernel(data_vector): return np.array((1 + np.dot(data_vector, data_vector.T))**2) def perceptron_quadratic_kernel(feature_matrix, labels, T):"
] |
[
"dist, _ = model(state) action = dist.sample().cpu().numpy()[0] next_state, reward, done, _ = env.step(action)",
"if frame_idx % save_iteration == 0: test_reward = np.mean([my_ppo.test_env() for _ in range(num_envs)])",
"# plot(frame_idx, test_rewards) if test_reward > threshold_reward: early_stop = True if frame_idx %",
"= False def trch_ft_device(input, device): output = torch.FloatTensor(input).to(device) return output saver_model = save_files()",
"threshold_reward: early_stop = True if frame_idx % model_save_iteration == 0: saver_model.model_save(model) next_state =",
"optim.Adam(model.parameters(), lr=lr) max_frames = 1_500_0000 frame_idx = 0 test_rewards = [] save_iteration =",
"if frame_idx % model_save_iteration == 0: saver_model.model_save(model) next_state = trch_ft_device(next_state, device) _, next_value",
"\"CustomEnv-v0\" envs = [make_env(env_name) for i in range(num_envs)] envs = SubprocVecEnv(envs) num_inputs =",
"state = trch_ft_device(state, device) dist, value = model(state) action = dist.sample() next_state, reward,",
"actions, log_probs, returns, advantage, optimizer) max_expert_num = 50000 num_steps = 0 expert_traj =",
"1 if frame_idx % save_iteration == 0: test_reward = np.mean([my_ppo.test_env() for _ in",
"False total_reward = 0 while not done: state = torch.FloatTensor(state).unsqueeze(0).to(device) dist, _ =",
"masks, values) returns = torch.cat(returns).detach() log_probs = torch.cat(log_probs).detach() values = torch.cat(values).detach() states =",
"action = dist.sample() next_state, reward, done, _ = envs.step(action.cpu().numpy()) log_prob = dist.log_prob(action) entropy",
"early_stop = False def trch_ft_device(input, device): output = torch.FloatTensor(input).to(device) return output saver_model =",
"neural_network import ActorCritic from ppo_method import ppo from common.multiprocessing_env import SubprocVecEnv from itertools",
"trch_ft_device(input, device): output = torch.FloatTensor(input).to(device) return output saver_model = save_files() while frame_idx <",
"for _ in range(num_envs)]) test_rewards.append(test_reward) # plot(frame_idx, test_rewards) if test_reward > threshold_reward: early_stop",
"output = torch.FloatTensor(input).to(device) return output saver_model = save_files() while frame_idx < max_frames and",
"expert_traj.append(np.hstack([state, action])) num_steps += 1 print(\"episode:\", i_episode, \"reward:\", total_reward) if num_steps >= max_expert_num:",
"- done).unsqueeze(1).to(device)) states.append(state) actions.append(action) # next iteration init. state = next_state frame_idx +=",
"action])) num_steps += 1 print(\"episode:\", i_episode, \"reward:\", total_reward) if num_steps >= max_expert_num: break",
"test_reward > threshold_reward: early_stop = True if frame_idx % model_save_iteration == 0: saver_model.model_save(model)",
"appending log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) states.append(state) actions.append(action) # next iteration init.",
"gym import numpy as np import torch import torch.optim as optim from utils_main",
"_ in range(num_steps): state = trch_ft_device(state, device) dist, value = model(state) action =",
"[] states = [] actions = [] rewards = [] masks = []",
"from itertools import count use_cuda = torch.cuda.is_available() device = torch.device(\"cuda\" if use_cuda else",
"= [] rewards = [] masks = [] entropy = 0 for _",
"[] save_iteration = 1000 model_save_iteration = 1000 state = envs.reset() early_stop = False",
"in count(): state = env.reset() done = False total_reward = 0 while not",
"# appending log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) states.append(state) actions.append(action) # next iteration",
"hidden_size = 400 lr = 3e-6 num_steps = 20 mini_batch_size = 5 ppo_epochs",
"import torch import torch.optim as optim from utils_main import make_env, save_files from neural_network",
"init. state = next_state frame_idx += 1 if frame_idx % save_iteration == 0:",
"= env.reset() done = False total_reward = 0 while not done: state =",
"+= reward expert_traj.append(np.hstack([state, action])) num_steps += 1 print(\"episode:\", i_episode, \"reward:\", total_reward) if num_steps",
"= dist.sample() next_state, reward, done, _ = envs.step(action.cpu().numpy()) log_prob = dist.log_prob(action) entropy +=",
"entropy += dist.entropy().mean() # appending log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) states.append(state) actions.append(action)",
"log_prob = dist.log_prob(action) entropy += dist.entropy().mean() # appending log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 -",
"_ = env.step(action) state = next_state total_reward += reward expert_traj.append(np.hstack([state, action])) num_steps +=",
"= torch.FloatTensor(state).unsqueeze(0).to(device) dist, _ = model(state) action = dist.sample().cpu().numpy()[0] next_state, reward, done, _",
"num_steps = 20 mini_batch_size = 5 ppo_epochs = 4 threshold_reward = -0.01 model",
"for _ in range(num_steps): state = trch_ft_device(state, device) dist, value = model(state) action",
"values = [] states = [] actions = [] rewards = [] masks",
"env.step(action) state = next_state total_reward += reward expert_traj.append(np.hstack([state, action])) num_steps += 1 print(\"episode:\",",
"[] values = [] states = [] actions = [] rewards = []",
"device) _, next_value = model(next_state) returns = my_ppo.compute_gae(next_value, rewards, masks, values) returns =",
"value = model(state) action = dist.sample() next_state, reward, done, _ = envs.step(action.cpu().numpy()) log_prob",
"test_reward = np.mean([my_ppo.test_env() for _ in range(num_envs)]) test_rewards.append(test_reward) # plot(frame_idx, test_rewards) if test_reward",
"torch.cat(states) actions = torch.cat(actions) advantage = returns - values my_ppo.ppo_update(ppo_epochs, mini_batch_size, states, actions,",
"20 mini_batch_size = 5 ppo_epochs = 4 threshold_reward = -0.01 model = ActorCritic(num_inputs,",
"returns = torch.cat(returns).detach() log_probs = torch.cat(log_probs).detach() values = torch.cat(values).detach() states = torch.cat(states) actions",
"next_value = model(next_state) returns = my_ppo.compute_gae(next_value, rewards, masks, values) returns = torch.cat(returns).detach() log_probs",
"env = gym.make(env_name) my_ppo = ppo(model, env) optimizer = optim.Adam(model.parameters(), lr=lr) max_frames =",
"while not done: state = torch.FloatTensor(state).unsqueeze(0).to(device) dist, _ = model(state) action = dist.sample().cpu().numpy()[0]",
"make_env, save_files from neural_network import ActorCritic from ppo_method import ppo from common.multiprocessing_env import",
"= \"CustomEnv-v0\" envs = [make_env(env_name) for i in range(num_envs)] envs = SubprocVecEnv(envs) num_inputs",
"ActorCritic from ppo_method import ppo from common.multiprocessing_env import SubprocVecEnv from itertools import count",
"import ActorCritic from ppo_method import ppo from common.multiprocessing_env import SubprocVecEnv from itertools import",
"envs.action_space.shape[0] # Hyper params: hidden_size = 400 lr = 3e-6 num_steps = 20",
"model_save_iteration = 1000 state = envs.reset() early_stop = False def trch_ft_device(input, device): output",
"ActorCritic(num_inputs, num_outputs, hidden_size).to(device) env = gym.make(env_name) my_ppo = ppo(model, env) optimizer = optim.Adam(model.parameters(),",
"frame_idx = 0 test_rewards = [] save_iteration = 1000 model_save_iteration = 1000 state",
"my_ppo.compute_gae(next_value, rewards, masks, values) returns = torch.cat(returns).detach() log_probs = torch.cat(log_probs).detach() values = torch.cat(values).detach()",
"log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) states.append(state) actions.append(action) # next iteration init. state",
"+= dist.entropy().mean() # appending log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) states.append(state) actions.append(action) #",
"0 test_rewards = [] save_iteration = 1000 model_save_iteration = 1000 state = envs.reset()",
"torch.FloatTensor(state).unsqueeze(0).to(device) dist, _ = model(state) action = dist.sample().cpu().numpy()[0] next_state, reward, done, _ =",
"reward, done, _ = envs.step(action.cpu().numpy()) log_prob = dist.log_prob(action) entropy += dist.entropy().mean() # appending",
"next_state, reward, done, _ = envs.step(action.cpu().numpy()) log_prob = dist.log_prob(action) entropy += dist.entropy().mean() #",
"and not early_stop: log_probs = [] values = [] states = [] actions",
"early_stop: log_probs = [] values = [] states = [] actions = []",
"= envs.action_space.shape[0] # Hyper params: hidden_size = 400 lr = 3e-6 num_steps =",
"test_rewards.append(test_reward) # plot(frame_idx, test_rewards) if test_reward > threshold_reward: early_stop = True if frame_idx",
"= envs.reset() early_stop = False def trch_ft_device(input, device): output = torch.FloatTensor(input).to(device) return output",
"env) optimizer = optim.Adam(model.parameters(), lr=lr) max_frames = 1_500_0000 frame_idx = 0 test_rewards =",
"values) returns = torch.cat(returns).detach() log_probs = torch.cat(log_probs).detach() values = torch.cat(values).detach() states = torch.cat(states)",
"state = next_state frame_idx += 1 if frame_idx % save_iteration == 0: test_reward",
"for i_episode in count(): state = env.reset() done = False total_reward = 0",
"save_files() while frame_idx < max_frames and not early_stop: log_probs = [] values =",
"= my_ppo.compute_gae(next_value, rewards, masks, values) returns = torch.cat(returns).detach() log_probs = torch.cat(log_probs).detach() values =",
"states = [] actions = [] rewards = [] masks = [] entropy",
"mini_batch_size = 5 ppo_epochs = 4 threshold_reward = -0.01 model = ActorCritic(num_inputs, num_outputs,",
"-0.01 model = ActorCritic(num_inputs, num_outputs, hidden_size).to(device) env = gym.make(env_name) my_ppo = ppo(model, env)",
"reward, done, _ = env.step(action) state = next_state total_reward += reward expert_traj.append(np.hstack([state, action]))",
"= torch.FloatTensor(input).to(device) return output saver_model = save_files() while frame_idx < max_frames and not",
"entropy = 0 for _ in range(num_steps): state = trch_ft_device(state, device) dist, value",
"values = torch.cat(values).detach() states = torch.cat(states) actions = torch.cat(actions) advantage = returns -",
"range(num_steps): state = trch_ft_device(state, device) dist, value = model(state) action = dist.sample() next_state,",
"= 0 test_rewards = [] save_iteration = 1000 model_save_iteration = 1000 state =",
"= ActorCritic(num_inputs, num_outputs, hidden_size).to(device) env = gym.make(env_name) my_ppo = ppo(model, env) optimizer =",
"env_name = \"CustomEnv-v0\" envs = [make_env(env_name) for i in range(num_envs)] envs = SubprocVecEnv(envs)",
"log_probs = [] values = [] states = [] actions = [] rewards",
"action = dist.sample().cpu().numpy()[0] next_state, reward, done, _ = env.step(action) state = next_state total_reward",
"torch.cuda.is_available() device = torch.device(\"cuda\" if use_cuda else \"cpu\") num_envs = 2 env_name =",
"done, _ = env.step(action) state = next_state total_reward += reward expert_traj.append(np.hstack([state, action])) num_steps",
"numpy as np import torch import torch.optim as optim from utils_main import make_env,",
"states = torch.cat(states) actions = torch.cat(actions) advantage = returns - values my_ppo.ppo_update(ppo_epochs, mini_batch_size,",
"masks = [] entropy = 0 for _ in range(num_steps): state = trch_ft_device(state,",
"frame_idx < max_frames and not early_stop: log_probs = [] values = [] states",
"0: saver_model.model_save(model) next_state = trch_ft_device(next_state, device) _, next_value = model(next_state) returns = my_ppo.compute_gae(next_value,",
"actions = torch.cat(actions) advantage = returns - values my_ppo.ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs,",
"= np.mean([my_ppo.test_env() for _ in range(num_envs)]) test_rewards.append(test_reward) # plot(frame_idx, test_rewards) if test_reward >",
"model_save_iteration == 0: saver_model.model_save(model) next_state = trch_ft_device(next_state, device) _, next_value = model(next_state) returns",
"plot(frame_idx, test_rewards) if test_reward > threshold_reward: early_stop = True if frame_idx % model_save_iteration",
"= 50000 num_steps = 0 expert_traj = [] # building an episode based",
"_ in range(num_envs)]) test_rewards.append(test_reward) # plot(frame_idx, test_rewards) if test_reward > threshold_reward: early_stop =",
"envs.reset() early_stop = False def trch_ft_device(input, device): output = torch.FloatTensor(input).to(device) return output saver_model",
"ppo_method import ppo from common.multiprocessing_env import SubprocVecEnv from itertools import count use_cuda =",
"values my_ppo.ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantage, optimizer) max_expert_num = 50000 num_steps",
"== 0: test_reward = np.mean([my_ppo.test_env() for _ in range(num_envs)]) test_rewards.append(test_reward) # plot(frame_idx, test_rewards)",
"model(state) action = dist.sample().cpu().numpy()[0] next_state, reward, done, _ = env.step(action) state = next_state",
"3e-6 num_steps = 20 mini_batch_size = 5 ppo_epochs = 4 threshold_reward = -0.01",
"= optim.Adam(model.parameters(), lr=lr) max_frames = 1_500_0000 frame_idx = 0 test_rewards = [] save_iteration",
"next_state frame_idx += 1 if frame_idx % save_iteration == 0: test_reward = np.mean([my_ppo.test_env()",
"reward expert_traj.append(np.hstack([state, action])) num_steps += 1 print(\"episode:\", i_episode, \"reward:\", total_reward) if num_steps >=",
"1_500_0000 frame_idx = 0 test_rewards = [] save_iteration = 1000 model_save_iteration = 1000",
"= 0 for _ in range(num_steps): state = trch_ft_device(state, device) dist, value =",
"trch_ft_device(state, device) dist, value = model(state) action = dist.sample() next_state, reward, done, _",
"actions.append(action) # next iteration init. state = next_state frame_idx += 1 if frame_idx",
"= 3e-6 num_steps = 20 mini_batch_size = 5 ppo_epochs = 4 threshold_reward =",
"done, _ = envs.step(action.cpu().numpy()) log_prob = dist.log_prob(action) entropy += dist.entropy().mean() # appending log_probs.append(log_prob)",
"import torch.optim as optim from utils_main import make_env, save_files from neural_network import ActorCritic",
"early_stop = True if frame_idx % model_save_iteration == 0: saver_model.model_save(model) next_state = trch_ft_device(next_state,",
"next iteration init. state = next_state frame_idx += 1 if frame_idx % save_iteration",
"i_episode in count(): state = env.reset() done = False total_reward = 0 while",
"= 20 mini_batch_size = 5 ppo_epochs = 4 threshold_reward = -0.01 model =",
"= save_files() while frame_idx < max_frames and not early_stop: log_probs = [] values",
"= [] values = [] states = [] actions = [] rewards =",
"ppo_epochs = 4 threshold_reward = -0.01 model = ActorCritic(num_inputs, num_outputs, hidden_size).to(device) env =",
"expert_traj = [] # building an episode based on the current model. for",
"4 threshold_reward = -0.01 model = ActorCritic(num_inputs, num_outputs, hidden_size).to(device) env = gym.make(env_name) my_ppo",
"% save_iteration == 0: test_reward = np.mean([my_ppo.test_env() for _ in range(num_envs)]) test_rewards.append(test_reward) #",
"= 1000 state = envs.reset() early_stop = False def trch_ft_device(input, device): output =",
"if test_reward > threshold_reward: early_stop = True if frame_idx % model_save_iteration == 0:",
"1000 model_save_iteration = 1000 state = envs.reset() early_stop = False def trch_ft_device(input, device):",
"= [] entropy = 0 for _ in range(num_steps): state = trch_ft_device(state, device)",
"import count use_cuda = torch.cuda.is_available() device = torch.device(\"cuda\" if use_cuda else \"cpu\") num_envs",
"i in range(num_envs)] envs = SubprocVecEnv(envs) num_inputs = envs.observation_space.shape[0] num_outputs = envs.action_space.shape[0] #",
"return output saver_model = save_files() while frame_idx < max_frames and not early_stop: log_probs",
"num_inputs = envs.observation_space.shape[0] num_outputs = envs.action_space.shape[0] # Hyper params: hidden_size = 400 lr",
"= 0 while not done: state = torch.FloatTensor(state).unsqueeze(0).to(device) dist, _ = model(state) action",
"building an episode based on the current model. for i_episode in count(): state",
"lr = 3e-6 num_steps = 20 mini_batch_size = 5 ppo_epochs = 4 threshold_reward",
"save_iteration = 1000 model_save_iteration = 1000 state = envs.reset() early_stop = False def",
"[] rewards = [] masks = [] entropy = 0 for _ in",
"optim from utils_main import make_env, save_files from neural_network import ActorCritic from ppo_method import",
"env.reset() done = False total_reward = 0 while not done: state = torch.FloatTensor(state).unsqueeze(0).to(device)",
"ppo from common.multiprocessing_env import SubprocVecEnv from itertools import count use_cuda = torch.cuda.is_available() device",
"import make_env, save_files from neural_network import ActorCritic from ppo_method import ppo from common.multiprocessing_env",
"_, next_value = model(next_state) returns = my_ppo.compute_gae(next_value, rewards, masks, values) returns = torch.cat(returns).detach()",
"= model(state) action = dist.sample().cpu().numpy()[0] next_state, reward, done, _ = env.step(action) state =",
"from utils_main import make_env, save_files from neural_network import ActorCritic from ppo_method import ppo",
"model(next_state) returns = my_ppo.compute_gae(next_value, rewards, masks, values) returns = torch.cat(returns).detach() log_probs = torch.cat(log_probs).detach()",
"optimizer = optim.Adam(model.parameters(), lr=lr) max_frames = 1_500_0000 frame_idx = 0 test_rewards = []",
"[] entropy = 0 for _ in range(num_steps): state = trch_ft_device(state, device) dist,",
"= torch.cuda.is_available() device = torch.device(\"cuda\" if use_cuda else \"cpu\") num_envs = 2 env_name",
"for i in range(num_envs)] envs = SubprocVecEnv(envs) num_inputs = envs.observation_space.shape[0] num_outputs = envs.action_space.shape[0]",
"state = env.reset() done = False total_reward = 0 while not done: state",
"num_outputs, hidden_size).to(device) env = gym.make(env_name) my_ppo = ppo(model, env) optimizer = optim.Adam(model.parameters(), lr=lr)",
"0 for _ in range(num_steps): state = trch_ft_device(state, device) dist, value = model(state)",
"as np import torch import torch.optim as optim from utils_main import make_env, save_files",
"= model(next_state) returns = my_ppo.compute_gae(next_value, rewards, masks, values) returns = torch.cat(returns).detach() log_probs =",
"np import torch import torch.optim as optim from utils_main import make_env, save_files from",
"state = torch.FloatTensor(state).unsqueeze(0).to(device) dist, _ = model(state) action = dist.sample().cpu().numpy()[0] next_state, reward, done,",
"if use_cuda else \"cpu\") num_envs = 2 env_name = \"CustomEnv-v0\" envs = [make_env(env_name)",
"= torch.cat(states) actions = torch.cat(actions) advantage = returns - values my_ppo.ppo_update(ppo_epochs, mini_batch_size, states,",
"lr=lr) max_frames = 1_500_0000 frame_idx = 0 test_rewards = [] save_iteration = 1000",
"= 1_500_0000 frame_idx = 0 test_rewards = [] save_iteration = 1000 model_save_iteration =",
"= 0 expert_traj = [] # building an episode based on the current",
"num_steps = 0 expert_traj = [] # building an episode based on the",
"1000 state = envs.reset() early_stop = False def trch_ft_device(input, device): output = torch.FloatTensor(input).to(device)",
"model(state) action = dist.sample() next_state, reward, done, _ = envs.step(action.cpu().numpy()) log_prob = dist.log_prob(action)",
"< max_frames and not early_stop: log_probs = [] values = [] states =",
"advantage, optimizer) max_expert_num = 50000 num_steps = 0 expert_traj = [] # building",
"rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) states.append(state) actions.append(action) # next iteration init. state = next_state",
"= env.step(action) state = next_state total_reward += reward expert_traj.append(np.hstack([state, action])) num_steps += 1",
"current model. for i_episode in count(): state = env.reset() done = False total_reward",
"done).unsqueeze(1).to(device)) states.append(state) actions.append(action) # next iteration init. state = next_state frame_idx += 1",
"[make_env(env_name) for i in range(num_envs)] envs = SubprocVecEnv(envs) num_inputs = envs.observation_space.shape[0] num_outputs =",
"= returns - values my_ppo.ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantage, optimizer) max_expert_num",
"num_steps += 1 print(\"episode:\", i_episode, \"reward:\", total_reward) if num_steps >= max_expert_num: break expert_traj",
"dist.log_prob(action) entropy += dist.entropy().mean() # appending log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) states.append(state)",
"an episode based on the current model. for i_episode in count(): state =",
"torch.cat(log_probs).detach() values = torch.cat(values).detach() states = torch.cat(states) actions = torch.cat(actions) advantage = returns",
"dist.sample() next_state, reward, done, _ = envs.step(action.cpu().numpy()) log_prob = dist.log_prob(action) entropy += dist.entropy().mean()",
"model. for i_episode in count(): state = env.reset() done = False total_reward =",
"in range(num_steps): state = trch_ft_device(state, device) dist, value = model(state) action = dist.sample()",
"if num_steps >= max_expert_num: break expert_traj = np.stack(expert_traj) print() print(expert_traj.shape) print() np.save(\"expert_traj.npy\", expert_traj)",
"= [make_env(env_name) for i in range(num_envs)] envs = SubprocVecEnv(envs) num_inputs = envs.observation_space.shape[0] num_outputs",
"= dist.log_prob(action) entropy += dist.entropy().mean() # appending log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device))",
"max_frames and not early_stop: log_probs = [] values = [] states = []",
"states, actions, log_probs, returns, advantage, optimizer) max_expert_num = 50000 num_steps = 0 expert_traj",
"import SubprocVecEnv from itertools import count use_cuda = torch.cuda.is_available() device = torch.device(\"cuda\" if",
"0: test_reward = np.mean([my_ppo.test_env() for _ in range(num_envs)]) test_rewards.append(test_reward) # plot(frame_idx, test_rewards) if",
"done: state = torch.FloatTensor(state).unsqueeze(0).to(device) dist, _ = model(state) action = dist.sample().cpu().numpy()[0] next_state, reward,",
"= -0.01 model = ActorCritic(num_inputs, num_outputs, hidden_size).to(device) env = gym.make(env_name) my_ppo = ppo(model,",
"= True if frame_idx % model_save_iteration == 0: saver_model.model_save(model) next_state = trch_ft_device(next_state, device)",
"num_outputs = envs.action_space.shape[0] # Hyper params: hidden_size = 400 lr = 3e-6 num_steps",
"5 ppo_epochs = 4 threshold_reward = -0.01 model = ActorCritic(num_inputs, num_outputs, hidden_size).to(device) env",
"output saver_model = save_files() while frame_idx < max_frames and not early_stop: log_probs =",
"states.append(state) actions.append(action) # next iteration init. state = next_state frame_idx += 1 if",
"SubprocVecEnv(envs) num_inputs = envs.observation_space.shape[0] num_outputs = envs.action_space.shape[0] # Hyper params: hidden_size = 400",
"test_rewards = [] save_iteration = 1000 model_save_iteration = 1000 state = envs.reset() early_stop",
"import gym import numpy as np import torch import torch.optim as optim from",
"optimizer) max_expert_num = 50000 num_steps = 0 expert_traj = [] # building an",
"not early_stop: log_probs = [] values = [] states = [] actions =",
"state = next_state total_reward += reward expert_traj.append(np.hstack([state, action])) num_steps += 1 print(\"episode:\", i_episode,",
"values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) states.append(state) actions.append(action) # next iteration init. state =",
"total_reward += reward expert_traj.append(np.hstack([state, action])) num_steps += 1 print(\"episode:\", i_episode, \"reward:\", total_reward) if",
"total_reward) if num_steps >= max_expert_num: break expert_traj = np.stack(expert_traj) print() print(expert_traj.shape) print() np.save(\"expert_traj.npy\",",
"threshold_reward = -0.01 model = ActorCritic(num_inputs, num_outputs, hidden_size).to(device) env = gym.make(env_name) my_ppo =",
"actions = [] rewards = [] masks = [] entropy = 0 for",
"True if frame_idx % model_save_iteration == 0: saver_model.model_save(model) next_state = trch_ft_device(next_state, device) _,",
"params: hidden_size = 400 lr = 3e-6 num_steps = 20 mini_batch_size = 5",
"frame_idx += 1 if frame_idx % save_iteration == 0: test_reward = np.mean([my_ppo.test_env() for",
"SubprocVecEnv from itertools import count use_cuda = torch.cuda.is_available() device = torch.device(\"cuda\" if use_cuda",
"log_probs, returns, advantage, optimizer) max_expert_num = 50000 num_steps = 0 expert_traj = []",
"returns, advantage, optimizer) max_expert_num = 50000 num_steps = 0 expert_traj = [] #",
"count use_cuda = torch.cuda.is_available() device = torch.device(\"cuda\" if use_cuda else \"cpu\") num_envs =",
"in range(num_envs)] envs = SubprocVecEnv(envs) num_inputs = envs.observation_space.shape[0] num_outputs = envs.action_space.shape[0] # Hyper",
"= envs.observation_space.shape[0] num_outputs = envs.action_space.shape[0] # Hyper params: hidden_size = 400 lr =",
"= trch_ft_device(state, device) dist, value = model(state) action = dist.sample() next_state, reward, done,",
"50000 num_steps = 0 expert_traj = [] # building an episode based on",
"returns = my_ppo.compute_gae(next_value, rewards, masks, values) returns = torch.cat(returns).detach() log_probs = torch.cat(log_probs).detach() values",
"= [] save_iteration = 1000 model_save_iteration = 1000 state = envs.reset() early_stop =",
"state = envs.reset() early_stop = False def trch_ft_device(input, device): output = torch.FloatTensor(input).to(device) return",
"save_files from neural_network import ActorCritic from ppo_method import ppo from common.multiprocessing_env import SubprocVecEnv",
"\"cpu\") num_envs = 2 env_name = \"CustomEnv-v0\" envs = [make_env(env_name) for i in",
"def trch_ft_device(input, device): output = torch.FloatTensor(input).to(device) return output saver_model = save_files() while frame_idx",
"False def trch_ft_device(input, device): output = torch.FloatTensor(input).to(device) return output saver_model = save_files() while",
"import ppo from common.multiprocessing_env import SubprocVecEnv from itertools import count use_cuda = torch.cuda.is_available()",
"0 while not done: state = torch.FloatTensor(state).unsqueeze(0).to(device) dist, _ = model(state) action =",
"= 1000 model_save_iteration = 1000 state = envs.reset() early_stop = False def trch_ft_device(input,",
"next_state, reward, done, _ = env.step(action) state = next_state total_reward += reward expert_traj.append(np.hstack([state,",
"dist, value = model(state) action = dist.sample() next_state, reward, done, _ = envs.step(action.cpu().numpy())",
"iteration init. state = next_state frame_idx += 1 if frame_idx % save_iteration ==",
"= ppo(model, env) optimizer = optim.Adam(model.parameters(), lr=lr) max_frames = 1_500_0000 frame_idx = 0",
"in range(num_envs)]) test_rewards.append(test_reward) # plot(frame_idx, test_rewards) if test_reward > threshold_reward: early_stop = True",
"dist.sample().cpu().numpy()[0] next_state, reward, done, _ = env.step(action) state = next_state total_reward += reward",
"= False total_reward = 0 while not done: state = torch.FloatTensor(state).unsqueeze(0).to(device) dist, _",
"+= 1 if frame_idx % save_iteration == 0: test_reward = np.mean([my_ppo.test_env() for _",
"= 400 lr = 3e-6 num_steps = 20 mini_batch_size = 5 ppo_epochs =",
"2 env_name = \"CustomEnv-v0\" envs = [make_env(env_name) for i in range(num_envs)] envs =",
"hidden_size).to(device) env = gym.make(env_name) my_ppo = ppo(model, env) optimizer = optim.Adam(model.parameters(), lr=lr) max_frames",
"max_expert_num = 50000 num_steps = 0 expert_traj = [] # building an episode",
"= [] masks = [] entropy = 0 for _ in range(num_steps): state",
"next_state total_reward += reward expert_traj.append(np.hstack([state, action])) num_steps += 1 print(\"episode:\", i_episode, \"reward:\", total_reward)",
"trch_ft_device(next_state, device) _, next_value = model(next_state) returns = my_ppo.compute_gae(next_value, rewards, masks, values) returns",
"# next iteration init. state = next_state frame_idx += 1 if frame_idx %",
"torch.FloatTensor(input).to(device) return output saver_model = save_files() while frame_idx < max_frames and not early_stop:",
"mini_batch_size, states, actions, log_probs, returns, advantage, optimizer) max_expert_num = 50000 num_steps = 0",
"= SubprocVecEnv(envs) num_inputs = envs.observation_space.shape[0] num_outputs = envs.action_space.shape[0] # Hyper params: hidden_size =",
"= torch.cat(returns).detach() log_probs = torch.cat(log_probs).detach() values = torch.cat(values).detach() states = torch.cat(states) actions =",
"= next_state frame_idx += 1 if frame_idx % save_iteration == 0: test_reward =",
"torch.cat(actions) advantage = returns - values my_ppo.ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantage,",
"> threshold_reward: early_stop = True if frame_idx % model_save_iteration == 0: saver_model.model_save(model) next_state",
"+= 1 print(\"episode:\", i_episode, \"reward:\", total_reward) if num_steps >= max_expert_num: break expert_traj =",
"torch.cat(values).detach() states = torch.cat(states) actions = torch.cat(actions) advantage = returns - values my_ppo.ppo_update(ppo_epochs,",
"[] actions = [] rewards = [] masks = [] entropy = 0",
"envs.step(action.cpu().numpy()) log_prob = dist.log_prob(action) entropy += dist.entropy().mean() # appending log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1",
"test_rewards) if test_reward > threshold_reward: early_stop = True if frame_idx % model_save_iteration ==",
"torch.optim as optim from utils_main import make_env, save_files from neural_network import ActorCritic from",
"= 5 ppo_epochs = 4 threshold_reward = -0.01 model = ActorCritic(num_inputs, num_outputs, hidden_size).to(device)",
"% model_save_iteration == 0: saver_model.model_save(model) next_state = trch_ft_device(next_state, device) _, next_value = model(next_state)",
"max_frames = 1_500_0000 frame_idx = 0 test_rewards = [] save_iteration = 1000 model_save_iteration",
"frame_idx % save_iteration == 0: test_reward = np.mean([my_ppo.test_env() for _ in range(num_envs)]) test_rewards.append(test_reward)",
"range(num_envs)] envs = SubprocVecEnv(envs) num_inputs = envs.observation_space.shape[0] num_outputs = envs.action_space.shape[0] # Hyper params:",
"range(num_envs)]) test_rewards.append(test_reward) # plot(frame_idx, test_rewards) if test_reward > threshold_reward: early_stop = True if",
"log_probs = torch.cat(log_probs).detach() values = torch.cat(values).detach() states = torch.cat(states) actions = torch.cat(actions) advantage",
"dist.entropy().mean() # appending log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device)) masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) states.append(state) actions.append(action) # next",
"my_ppo.ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantage, optimizer) max_expert_num = 50000 num_steps =",
"frame_idx % model_save_iteration == 0: saver_model.model_save(model) next_state = trch_ft_device(next_state, device) _, next_value =",
"from neural_network import ActorCritic from ppo_method import ppo from common.multiprocessing_env import SubprocVecEnv from",
"count(): state = env.reset() done = False total_reward = 0 while not done:",
"from ppo_method import ppo from common.multiprocessing_env import SubprocVecEnv from itertools import count use_cuda",
"next_state = trch_ft_device(next_state, device) _, next_value = model(next_state) returns = my_ppo.compute_gae(next_value, rewards, masks,",
"np.mean([my_ppo.test_env() for _ in range(num_envs)]) test_rewards.append(test_reward) # plot(frame_idx, test_rewards) if test_reward > threshold_reward:",
"1 print(\"episode:\", i_episode, \"reward:\", total_reward) if num_steps >= max_expert_num: break expert_traj = np.stack(expert_traj)",
"my_ppo = ppo(model, env) optimizer = optim.Adam(model.parameters(), lr=lr) max_frames = 1_500_0000 frame_idx =",
"rewards, masks, values) returns = torch.cat(returns).detach() log_probs = torch.cat(log_probs).detach() values = torch.cat(values).detach() states",
"= torch.cat(values).detach() states = torch.cat(states) actions = torch.cat(actions) advantage = returns - values",
"itertools import count use_cuda = torch.cuda.is_available() device = torch.device(\"cuda\" if use_cuda else \"cpu\")",
"envs.observation_space.shape[0] num_outputs = envs.action_space.shape[0] # Hyper params: hidden_size = 400 lr = 3e-6",
"total_reward = 0 while not done: state = torch.FloatTensor(state).unsqueeze(0).to(device) dist, _ = model(state)",
"= [] actions = [] rewards = [] masks = [] entropy =",
"num_envs = 2 env_name = \"CustomEnv-v0\" envs = [make_env(env_name) for i in range(num_envs)]",
"while frame_idx < max_frames and not early_stop: log_probs = [] values = []",
"saver_model = save_files() while frame_idx < max_frames and not early_stop: log_probs = []",
"else \"cpu\") num_envs = 2 env_name = \"CustomEnv-v0\" envs = [make_env(env_name) for i",
"torch.cat(returns).detach() log_probs = torch.cat(log_probs).detach() values = torch.cat(values).detach() states = torch.cat(states) actions = torch.cat(actions)",
"based on the current model. for i_episode in count(): state = env.reset() done",
"0 expert_traj = [] # building an episode based on the current model.",
"not done: state = torch.FloatTensor(state).unsqueeze(0).to(device) dist, _ = model(state) action = dist.sample().cpu().numpy()[0] next_state,",
"== 0: saver_model.model_save(model) next_state = trch_ft_device(next_state, device) _, next_value = model(next_state) returns =",
"Hyper params: hidden_size = 400 lr = 3e-6 num_steps = 20 mini_batch_size =",
"= envs.step(action.cpu().numpy()) log_prob = dist.log_prob(action) entropy += dist.entropy().mean() # appending log_probs.append(log_prob) values.append(value) rewards.append(torch.FloatTensor(reward).unsqueeze(1).to(device))",
"the current model. for i_episode in count(): state = env.reset() done = False",
"[] masks = [] entropy = 0 for _ in range(num_steps): state =",
"= next_state total_reward += reward expert_traj.append(np.hstack([state, action])) num_steps += 1 print(\"episode:\", i_episode, \"reward:\",",
"= [] # building an episode based on the current model. for i_episode",
"torch.device(\"cuda\" if use_cuda else \"cpu\") num_envs = 2 env_name = \"CustomEnv-v0\" envs =",
"= dist.sample().cpu().numpy()[0] next_state, reward, done, _ = env.step(action) state = next_state total_reward +=",
"= trch_ft_device(next_state, device) _, next_value = model(next_state) returns = my_ppo.compute_gae(next_value, rewards, masks, values)",
"save_iteration == 0: test_reward = np.mean([my_ppo.test_env() for _ in range(num_envs)]) test_rewards.append(test_reward) # plot(frame_idx,",
"utils_main import make_env, save_files from neural_network import ActorCritic from ppo_method import ppo from",
"= torch.cat(actions) advantage = returns - values my_ppo.ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns,",
"episode based on the current model. for i_episode in count(): state = env.reset()",
"model = ActorCritic(num_inputs, num_outputs, hidden_size).to(device) env = gym.make(env_name) my_ppo = ppo(model, env) optimizer",
"= 4 threshold_reward = -0.01 model = ActorCritic(num_inputs, num_outputs, hidden_size).to(device) env = gym.make(env_name)",
"= gym.make(env_name) my_ppo = ppo(model, env) optimizer = optim.Adam(model.parameters(), lr=lr) max_frames = 1_500_0000",
"400 lr = 3e-6 num_steps = 20 mini_batch_size = 5 ppo_epochs = 4",
"use_cuda else \"cpu\") num_envs = 2 env_name = \"CustomEnv-v0\" envs = [make_env(env_name) for",
"from common.multiprocessing_env import SubprocVecEnv from itertools import count use_cuda = torch.cuda.is_available() device =",
"= model(state) action = dist.sample() next_state, reward, done, _ = envs.step(action.cpu().numpy()) log_prob =",
"print(\"episode:\", i_episode, \"reward:\", total_reward) if num_steps >= max_expert_num: break expert_traj = np.stack(expert_traj) print()",
"i_episode, \"reward:\", total_reward) if num_steps >= max_expert_num: break expert_traj = np.stack(expert_traj) print() print(expert_traj.shape)",
"import numpy as np import torch import torch.optim as optim from utils_main import",
"# Hyper params: hidden_size = 400 lr = 3e-6 num_steps = 20 mini_batch_size",
"[] # building an episode based on the current model. for i_episode in",
"_ = envs.step(action.cpu().numpy()) log_prob = dist.log_prob(action) entropy += dist.entropy().mean() # appending log_probs.append(log_prob) values.append(value)",
"= torch.cat(log_probs).detach() values = torch.cat(values).detach() states = torch.cat(states) actions = torch.cat(actions) advantage =",
"= torch.device(\"cuda\" if use_cuda else \"cpu\") num_envs = 2 env_name = \"CustomEnv-v0\" envs",
"device): output = torch.FloatTensor(input).to(device) return output saver_model = save_files() while frame_idx < max_frames",
"# building an episode based on the current model. for i_episode in count():",
"device = torch.device(\"cuda\" if use_cuda else \"cpu\") num_envs = 2 env_name = \"CustomEnv-v0\"",
"common.multiprocessing_env import SubprocVecEnv from itertools import count use_cuda = torch.cuda.is_available() device = torch.device(\"cuda\"",
"envs = [make_env(env_name) for i in range(num_envs)] envs = SubprocVecEnv(envs) num_inputs = envs.observation_space.shape[0]",
"as optim from utils_main import make_env, save_files from neural_network import ActorCritic from ppo_method",
"masks.append(torch.FloatTensor(1 - done).unsqueeze(1).to(device)) states.append(state) actions.append(action) # next iteration init. state = next_state frame_idx",
"= [] states = [] actions = [] rewards = [] masks =",
"_ = model(state) action = dist.sample().cpu().numpy()[0] next_state, reward, done, _ = env.step(action) state",
"- values my_ppo.ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantage, optimizer) max_expert_num = 50000",
"ppo(model, env) optimizer = optim.Adam(model.parameters(), lr=lr) max_frames = 1_500_0000 frame_idx = 0 test_rewards",
"saver_model.model_save(model) next_state = trch_ft_device(next_state, device) _, next_value = model(next_state) returns = my_ppo.compute_gae(next_value, rewards,",
"advantage = returns - values my_ppo.ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantage, optimizer)",
"gym.make(env_name) my_ppo = ppo(model, env) optimizer = optim.Adam(model.parameters(), lr=lr) max_frames = 1_500_0000 frame_idx",
"done = False total_reward = 0 while not done: state = torch.FloatTensor(state).unsqueeze(0).to(device) dist,",
"rewards = [] masks = [] entropy = 0 for _ in range(num_steps):",
"device) dist, value = model(state) action = dist.sample() next_state, reward, done, _ =",
"= 2 env_name = \"CustomEnv-v0\" envs = [make_env(env_name) for i in range(num_envs)] envs",
"torch import torch.optim as optim from utils_main import make_env, save_files from neural_network import",
"on the current model. for i_episode in count(): state = env.reset() done =",
"use_cuda = torch.cuda.is_available() device = torch.device(\"cuda\" if use_cuda else \"cpu\") num_envs = 2",
"envs = SubprocVecEnv(envs) num_inputs = envs.observation_space.shape[0] num_outputs = envs.action_space.shape[0] # Hyper params: hidden_size",
"\"reward:\", total_reward) if num_steps >= max_expert_num: break expert_traj = np.stack(expert_traj) print() print(expert_traj.shape) print()",
"returns - values my_ppo.ppo_update(ppo_epochs, mini_batch_size, states, actions, log_probs, returns, advantage, optimizer) max_expert_num ="
] |
[
"by Django 2.1.2 on 2019-02-20 15:47 import django.contrib.postgres.fields.jsonb from django.db import migrations class",
"Generated by Django 2.1.2 on 2019-02-20 15:47 import django.contrib.postgres.fields.jsonb from django.db import migrations",
"Migration(migrations.Migration): dependencies = [(\"contentstore\", \"0010_auto_20181126_1104\")] operations = [ migrations.AddField( model_name=\"message\", name=\"metadata\", field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), )",
"dependencies = [(\"contentstore\", \"0010_auto_20181126_1104\")] operations = [ migrations.AddField( model_name=\"message\", name=\"metadata\", field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ) ]",
"15:47 import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [(\"contentstore\", \"0010_auto_20181126_1104\")]",
"# Generated by Django 2.1.2 on 2019-02-20 15:47 import django.contrib.postgres.fields.jsonb from django.db import",
"django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [(\"contentstore\", \"0010_auto_20181126_1104\")] operations =",
"import migrations class Migration(migrations.Migration): dependencies = [(\"contentstore\", \"0010_auto_20181126_1104\")] operations = [ migrations.AddField( model_name=\"message\",",
"class Migration(migrations.Migration): dependencies = [(\"contentstore\", \"0010_auto_20181126_1104\")] operations = [ migrations.AddField( model_name=\"message\", name=\"metadata\", field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),",
"on 2019-02-20 15:47 import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies =",
"import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [(\"contentstore\", \"0010_auto_20181126_1104\")] operations",
"Django 2.1.2 on 2019-02-20 15:47 import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration):",
"2019-02-20 15:47 import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [(\"contentstore\",",
"migrations class Migration(migrations.Migration): dependencies = [(\"contentstore\", \"0010_auto_20181126_1104\")] operations = [ migrations.AddField( model_name=\"message\", name=\"metadata\",",
"2.1.2 on 2019-02-20 15:47 import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies",
"django.db import migrations class Migration(migrations.Migration): dependencies = [(\"contentstore\", \"0010_auto_20181126_1104\")] operations = [ migrations.AddField(",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [(\"contentstore\", \"0010_auto_20181126_1104\")] operations = ["
] |
[
"self.assertIn('Anonymous', rv.data) class TestPostRequest(BaseTestCase): data = {'title':'Lewiathanus livus', 'content':'A book by Hobbes is",
"self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me), follow_redirects=True) def test_update_profile(self): rv = self.update_profile(\"maniana\", \"Curious explorer of new",
"self.assertIn(\"reviews of drafts published by\", rv.data) def test_show_responses(self): rv = self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def",
"category=category, deadline=deadline), follow_redirects=True) def test_request_review(self): rv = self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make review request",
"self.logout() def login(self,username,password): return self.app.post('/login', data=dict( username=username, password=password), follow_redirects=True) def logout (self): return",
"message informing about it message = \"following formats are allowed:\" for ext in",
"title\",\"new content with a lot of blah\", \\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data) def test_all_reviews(self): rv",
"for ext in self.rather_not: self.upload_something(ext, message) def test_no_file(self): rv = self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No",
"TestConfig from utilities import manipulate_db from tests import test_login timestamp = datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG)",
"= ['sh', 'ps1','ghost','exe'] def do_post(self, data): return self.app.post('/request_review', data=data, follow_redirects=True) def upload_something(self, extension,",
"has been updated\", rv.data) def make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\", data=dict( title=title, content=content, category=category, deadline=deadline),",
"test_all_reviews(self): rv = self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All reviews written by all users',rv.data) self.assertIn('Anonymous', rv.data)",
"self.app.get(url) self.assertIn(\"Update Request\", rv.data) url = \"/req/\" + str(3) rv = self.app.get(url) self.assertNotIn(\"Update",
"is always worth reading', 'category':'academic', 'deadline':str(timestamp)} rather_not = ['sh', 'ps1','ghost','exe'] def do_post(self, data):",
"\"09/12/2012\") self.assertEqual(200,rv.status_code) def main_thread(self): return self.app.get('/', follow_redirects=True) def test_main_thread(self): rv = self.main_thread() self.assertEqual(200,",
"rv = self.review_this( \"nice work this is amazing\", 5, 101) self.assertEqual(rv.status_code,200) self.assertIn(\"has been",
"= self.data.copy() data[\"content\"] = \"\" rv = self.do_post(data) self.assertEqual(rv.status_code,200) self.assertIn(\"Invalid form.\",rv.data) if __name__",
"request response = self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data) rv = self.review_this( \"nice work this is",
"self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All reviews written by all users',rv.data) self.assertIn('Anonymous', rv.data) class TestPostRequest(BaseTestCase): data",
"\"following formats are allowed:\" for ext in self.rather_not: self.upload_something(ext, message) def test_no_file(self): rv",
"work\",99,102) self.assertIn(\"errors\",response.data) rv = self.review_this( \"nice work this is amazing\", 5, 101) self.assertEqual(rv.status_code,200)",
"rv.data) def make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\", data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) def test_request_review(self):",
"self.app.post(url,data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) <EMAIL>(\"not implemented yet\") def test_update_post(self): # what",
"a lot of blah\", \\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data) def test_all_reviews(self): rv = self.app.get('/reviews') self.assertEqual(rv.status_code,200)",
"a message informing about it message = \"following formats are allowed:\" for ext",
"\"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data) # now a valid request rv = self.update_post(101,\"new title\",\"new",
"response = self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def test_upload_allowed_formats(self): # valid formats for ext in",
"utilities import manipulate_db from tests import test_login timestamp = datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger =",
"= self.app.get(url) self.assertIn(\"Update Request\", rv.data) url = \"/req/\" + str(3) rv = self.app.get(url)",
"test_update_post(self): # what if update is not allowed? Hugo's article has id 101,",
"self.assertIn(\"has been added\",rv.data) def test_reviews_of_user(self): rv = self.app.get(\"/reviews_of_user/%s\" % 2, follow_redirects=True) self.assertEqual(rv.status_code, 200)",
"Message, expected message in flash. \"\"\" data = self.data.copy() filename = 'file.%s' %",
"'deadline':str(timestamp)} rather_not = ['sh', 'ps1','ghost','exe'] def do_post(self, data): return self.app.post('/request_review', data=data, follow_redirects=True) def",
"for ext in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request sucessfuly') def test_upload_invalid_data(self): # Invalid extensions #",
"new lands\") self.assertIn(\"Your profile has been updated\", rv.data) def make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\", data=dict(",
"import url_for from src import flaskr from src import modele from src.config import",
"content with a lot of blah\", \\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data) def test_all_reviews(self): rv =",
"by all users',rv.data) self.assertIn('Anonymous', rv.data) class TestPostRequest(BaseTestCase): data = {'title':'Lewiathanus livus', 'content':'A book",
"= self.update_post(101,\"new title\",\"new content with a lot of blah\", \\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data) def",
"return self.app.get('/', follow_redirects=True) def test_main_thread(self): rv = self.main_thread() self.assertEqual(200, rv.status_code) self.assertIn('Review Someone',rv.data) def",
"str(id) return self.app.post(url,data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) <EMAIL>(\"not implemented yet\") def test_update_post(self):",
"def edit_profile(self): return self.app.get(\"/edit_profile\", follow_redirects=True) def test_edit_profile(self): rv = self.edit_profile() self.assertIn(\"Edit your profile",
"# Invalid extensions # we expect a message informing about it message =",
"deadline=deadline), follow_redirects=True) def test_request_review(self): rv = self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make review request tested",
"+ str(3) rv = self.app.get(url) self.assertNotIn(\"Update Request\", rv.data) def update_post(self,id,title,content,category,deadline): url = \"/req/update/\"",
"def test_show_responses(self): rv = self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def test_update_possible(self): url = \"/req/\" + str(101)",
"self.app.get('/logout', follow_redirects=True) class GeneralTestCase(BaseTestCase): def edit_profile(self): return self.app.get(\"/edit_profile\", follow_redirects=True) def test_edit_profile(self): rv =",
"self.assertIn(\"ok\",rv.data) def test_all_reviews(self): rv = self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All reviews written by all users',rv.data)",
"self.update_post(102,\"new title\",\"new content with long soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data) # now a",
"= self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All reviews written by all users',rv.data) self.assertIn('Anonymous', rv.data) class TestPostRequest(BaseTestCase):",
"wos of so much importance to literature.\", \"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code) def main_thread(self): return",
"soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data) # now a valid request rv = self.update_post(101,\"new",
"str(3) rv = self.app.get(url) self.assertNotIn(\"Update Request\", rv.data) def update_post(self,id,title,content,category,deadline): url = \"/req/update/\" +",
"self.make_review_request(\"title\", \"In this wos of so much importance to literature.\", \"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code)",
"review_text=review_text, rating=rating), follow_redirects=True) def test_review_this(self): # invalid request response = self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data)",
"\"\"\" data = self.data.copy() filename = 'file.%s' % extension data[\"file\"] = (StringIO.StringIO('new file'),",
"def test_upload_allowed_formats(self): # valid formats for ext in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request sucessfuly') def",
"= self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No file added\",rv.data) def test_invalid_form(self): data = self.data.copy() data[\"content\"] =",
"def upload_something(self, extension, message): \"\"\" Message, expected message in flash. \"\"\" data =",
"rv.status_code) def display_user_requests(self,uid): return self.app.get('/display_user_requests/%s' % uid, follow_redirects=True) def test_display_user_request(self): rv = self.display_user_requests(1)",
"from datetime import datetime import time import StringIO import logging from flask import",
"flaskr.app.test_client() self.login(\"Hugo\", \"secret\") def tearDown(self): self.logout() def login(self,username,password): return self.app.post('/login', data=dict( username=username, password=password),",
"200) self.assertIn(\"reviews of drafts published by\", rv.data) def test_show_responses(self): rv = self.app.get('/reviews/201') self.assertEqual(200,rv.status_code)",
"+ str(id) return self.app.post(url,data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) <EMAIL>(\"not implemented yet\") def",
"unittest from contextlib import closing from datetime import datetime import time import StringIO",
"= self.data.copy() filename = 'file.%s' % extension data[\"file\"] = (StringIO.StringIO('new file'), filename) response",
"def make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\", data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) def test_request_review(self): rv",
"extensions # we expect a message informing about it message = \"following formats",
"logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class BaseTestCase(unittest.TestCase): def setUp(self): \"\"\"Before each test, set up",
"test_upload_invalid_data(self): # Invalid extensions # we expect a message informing about it message",
"'/req/post/' + str(request_id) return self.app.post(url, data=dict( review_text=review_text, rating=rating), follow_redirects=True) def test_review_this(self): # invalid",
"self.assertIn('Review Someone',rv.data) def click_reviews(self,id): url = \"/req/\" + str(id) return self.app.get(url, follow_redirects=True) def",
"def test_invalid_form(self): data = self.data.copy() data[\"content\"] = \"\" rv = self.do_post(data) self.assertEqual(rv.status_code,200) self.assertIn(\"Invalid",
"rv = self.click_reviews(1) self.assertEqual(200, rv.status_code) def display_user_requests(self,uid): return self.app.get('/display_user_requests/%s' % uid, follow_redirects=True) def",
"'file.%s' % extension data[\"file\"] = (StringIO.StringIO('new file'), filename) response = self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data)",
"def main_thread(self): return self.app.get('/', follow_redirects=True) def test_main_thread(self): rv = self.main_thread() self.assertEqual(200, rv.status_code) self.assertIn('Review",
"tests for the app. \"\"\" import os,sys import unittest from contextlib import closing",
"test_reviews_of_user(self): rv = self.app.get(\"/reviews_of_user/%s\" % 2, follow_redirects=True) self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews of drafts published",
"self.assertIn('All reviews written by all users',rv.data) self.assertIn('Anonymous', rv.data) class TestPostRequest(BaseTestCase): data = {'title':'Lewiathanus",
"allowed? Hugo's article has id 101, he tries # to update 102 rv",
"class BaseTestCase(unittest.TestCase): def setUp(self): \"\"\"Before each test, set up a blank database\"\"\" self.app",
"import flaskr from src import modele from src.config import TestConfig from utilities import",
"<EMAIL>(\"not implemented yet\") def test_update_post(self): # what if update is not allowed? Hugo's",
"of blah\", \\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data) def test_all_reviews(self): rv = self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All reviews",
"a valid request rv = self.update_post(101,\"new title\",\"new content with a lot of blah\",",
"implemented yet\") def test_update_post(self): # what if update is not allowed? Hugo's article",
"def test_update_post(self): # what if update is not allowed? Hugo's article has id",
"file added\",rv.data) def test_invalid_form(self): data = self.data.copy() data[\"content\"] = \"\" rv = self.do_post(data)",
"rv.data) # now a valid request rv = self.update_post(101,\"new title\",\"new content with a",
"modele from src.config import TestConfig from utilities import manipulate_db from tests import test_login",
"title=title, content=content, category=category, deadline=deadline), follow_redirects=True) def test_request_review(self): rv = self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make",
"so much importance to literature.\", \"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code) def main_thread(self): return self.app.get('/', follow_redirects=True)",
"def setUp(self): \"\"\"Before each test, set up a blank database\"\"\" self.app = flaskr.app.test_client()",
"def test_no_file(self): rv = self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No file added\",rv.data) def test_invalid_form(self): data =",
"to literature.\", \"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code) def main_thread(self): return self.app.get('/', follow_redirects=True) def test_main_thread(self): rv",
"import os,sys import unittest from contextlib import closing from datetime import datetime import",
"follow_redirects=True) def test_review_this(self): # invalid request response = self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data) rv =",
"rv = self.main_thread() self.assertEqual(200, rv.status_code) self.assertIn('Review Someone',rv.data) def click_reviews(self,id): url = \"/req/\" +",
"rv.status_code) self.assertIn('Review Someone',rv.data) def click_reviews(self,id): url = \"/req/\" + str(id) return self.app.get(url, follow_redirects=True)",
"def test_all_reviews(self): rv = self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All reviews written by all users',rv.data) self.assertIn('Anonymous',",
"published by\", rv.data) def test_show_responses(self): rv = self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def test_update_possible(self): url =",
"@unittest.skip(\"make review request tested with files\") def test_make_review_request(self): rv = self.make_review_request(\"title\", \"In this",
"self.review_this( \"nice work this is amazing\", 5, 101) self.assertEqual(rv.status_code,200) self.assertIn(\"has been added\",rv.data) def",
"tearDown(self): self.logout() def login(self,username,password): return self.app.post('/login', data=dict( username=username, password=password), follow_redirects=True) def logout (self):",
"url = \"/req/\" + str(3) rv = self.app.get(url) self.assertNotIn(\"Update Request\", rv.data) def update_post(self,id,title,content,category,deadline):",
"tries # to update 102 rv = self.update_post(102,\"new title\",\"new content with long soom\",\\",
"this wos of so much importance to literature.\", \"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code) def main_thread(self):",
"username=username, password=password), follow_redirects=True) def logout (self): return self.app.get('/logout', follow_redirects=True) class GeneralTestCase(BaseTestCase): def edit_profile(self):",
"from src.config import TestConfig from utilities import manipulate_db from tests import test_login timestamp",
"def test_edit_profile(self): rv = self.edit_profile() self.assertIn(\"Edit your profile Hugo\", rv.data) def update_profile(self, email,about_me):",
"\"Curious explorer of new lands\") self.assertIn(\"Your profile has been updated\", rv.data) def make_review_request(self,title,content,category,deadline):",
"rather_not = ['sh', 'ps1','ghost','exe'] def do_post(self, data): return self.app.post('/request_review', data=data, follow_redirects=True) def upload_something(self,",
"def test_main_thread(self): rv = self.main_thread() self.assertEqual(200, rv.status_code) self.assertIn('Review Someone',rv.data) def click_reviews(self,id): url =",
"def test_reviews_of_user(self): rv = self.app.get(\"/reviews_of_user/%s\" % 2, follow_redirects=True) self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews of drafts",
"about_me=about_me), follow_redirects=True) def test_update_profile(self): rv = self.update_profile(\"maniana\", \"Curious explorer of new lands\") self.assertIn(\"Your",
"lands\") self.assertIn(\"Your profile has been updated\", rv.data) def make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\", data=dict( title=title,",
"main_thread(self): return self.app.get('/', follow_redirects=True) def test_main_thread(self): rv = self.main_thread() self.assertEqual(200, rv.status_code) self.assertIn('Review Someone',rv.data)",
"def test_display_user_request(self): rv = self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id): url = '/req/post/' +",
"= \"/req/update/\" + str(id) return self.app.post(url,data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) <EMAIL>(\"not implemented",
"response = self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data) rv = self.review_this( \"nice work this is amazing\",",
"by Hobbes is always worth reading', 'category':'academic', 'deadline':str(timestamp)} rather_not = ['sh', 'ps1','ghost','exe'] def",
"has id 101, he tries # to update 102 rv = self.update_post(102,\"new title\",\"new",
"self.click_reviews(1) self.assertEqual(200, rv.status_code) def display_user_requests(self,uid): return self.app.get('/display_user_requests/%s' % uid, follow_redirects=True) def test_display_user_request(self): rv",
"message in flash. \"\"\" data = self.data.copy() filename = 'file.%s' % extension data[\"file\"]",
"self.app.post(url, data=dict( review_text=review_text, rating=rating), follow_redirects=True) def test_review_this(self): # invalid request response = self.review_this(\"good",
"= flaskr.app.test_client() self.login(\"Hugo\", \"secret\") def tearDown(self): self.logout() def login(self,username,password): return self.app.post('/login', data=dict( username=username,",
"+ str(request_id) return self.app.post(url, data=dict( review_text=review_text, rating=rating), follow_redirects=True) def test_review_this(self): # invalid request",
"valid formats for ext in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request sucessfuly') def test_upload_invalid_data(self): # Invalid",
"str(request_id) return self.app.post(url, data=dict( review_text=review_text, rating=rating), follow_redirects=True) def test_review_this(self): # invalid request response",
"content=content, category=category, deadline=deadline), follow_redirects=True) <EMAIL>(\"not implemented yet\") def test_update_post(self): # what if update",
"5, 101) self.assertEqual(rv.status_code,200) self.assertIn(\"has been added\",rv.data) def test_reviews_of_user(self): rv = self.app.get(\"/reviews_of_user/%s\" % 2,",
"we expect a message informing about it message = \"following formats are allowed:\"",
"= self.main_thread() self.assertEqual(200, rv.status_code) self.assertIn('Review Someone',rv.data) def click_reviews(self,id): url = \"/req/\" + str(id)",
"self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data) rv = self.review_this( \"nice work this is amazing\", 5, 101)",
"manipulate_db from tests import test_login timestamp = datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class",
"def logout (self): return self.app.get('/logout', follow_redirects=True) class GeneralTestCase(BaseTestCase): def edit_profile(self): return self.app.get(\"/edit_profile\", follow_redirects=True)",
"= self.click_reviews(1) self.assertEqual(200, rv.status_code) def display_user_requests(self,uid): return self.app.get('/display_user_requests/%s' % uid, follow_redirects=True) def test_display_user_request(self):",
"data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) def test_request_review(self): rv = self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code)",
"self.assertIn(\"No file added\",rv.data) def test_invalid_form(self): data = self.data.copy() data[\"content\"] = \"\" rv =",
"test_invalid_form(self): data = self.data.copy() data[\"content\"] = \"\" rv = self.do_post(data) self.assertEqual(rv.status_code,200) self.assertIn(\"Invalid form.\",rv.data)",
"= \"\" rv = self.do_post(data) self.assertEqual(rv.status_code,200) self.assertIn(\"Invalid form.\",rv.data) if __name__ == '__main__': manipulate_db.populateDb(TestConfig.DATABASE)",
"follow_redirects=True) def test_click_reviews(self): rv = self.click_reviews(1) self.assertEqual(200, rv.status_code) def display_user_requests(self,uid): return self.app.get('/display_user_requests/%s' %",
"= (StringIO.StringIO('new file'), filename) response = self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def test_upload_allowed_formats(self): # valid",
"to update 102 rv = self.update_post(102,\"new title\",\"new content with long soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code)",
"self.data.copy() data[\"content\"] = \"\" rv = self.do_post(data) self.assertEqual(rv.status_code,200) self.assertIn(\"Invalid form.\",rv.data) if __name__ ==",
"is not allowed? Hugo's article has id 101, he tries # to update",
"\"nice work this is amazing\", 5, 101) self.assertEqual(rv.status_code,200) self.assertIn(\"has been added\",rv.data) def test_reviews_of_user(self):",
"def test_update_possible(self): url = \"/req/\" + str(101) rv = self.app.get(url) self.assertIn(\"Update Request\", rv.data)",
"def display_user_requests(self,uid): return self.app.get('/display_user_requests/%s' % uid, follow_redirects=True) def test_display_user_request(self): rv = self.display_user_requests(1) self.assertEqual(rv.status_code,200)",
"def update_profile(self, email,about_me): return self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me), follow_redirects=True) def test_update_profile(self): rv = self.update_profile(\"maniana\",",
"rv = self.update_profile(\"maniana\", \"Curious explorer of new lands\") self.assertIn(\"Your profile has been updated\",",
"\"/req/\" + str(id) return self.app.get(url, follow_redirects=True) def test_click_reviews(self): rv = self.click_reviews(1) self.assertEqual(200, rv.status_code)",
"with files\") def test_make_review_request(self): rv = self.make_review_request(\"title\", \"In this wos of so much",
"'content':'A book by Hobbes is always worth reading', 'category':'academic', 'deadline':str(timestamp)} rather_not = ['sh',",
"filename) response = self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def test_upload_allowed_formats(self): # valid formats for ext",
"self.assertIn(\"Update Request\", rv.data) url = \"/req/\" + str(3) rv = self.app.get(url) self.assertNotIn(\"Update Request\",",
"updated\", rv.data) def make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\", data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) def",
"def update_post(self,id,title,content,category,deadline): url = \"/req/update/\" + str(id) return self.app.post(url,data=dict( title=title, content=content, category=category, deadline=deadline),",
"database\"\"\" self.app = flaskr.app.test_client() self.login(\"Hugo\", \"secret\") def tearDown(self): self.logout() def login(self,username,password): return self.app.post('/login',",
"this is amazing\", 5, 101) self.assertEqual(rv.status_code,200) self.assertIn(\"has been added\",rv.data) def test_reviews_of_user(self): rv =",
"% uid, follow_redirects=True) def test_display_user_request(self): rv = self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id): url",
"logging.getLogger(__name__) class BaseTestCase(unittest.TestCase): def setUp(self): \"\"\"Before each test, set up a blank database\"\"\"",
"# invalid request response = self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data) rv = self.review_this( \"nice work",
"Hugo\", rv.data) def update_profile(self, email,about_me): return self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me), follow_redirects=True) def test_update_profile(self): rv",
"'ps1','ghost','exe'] def do_post(self, data): return self.app.post('/request_review', data=data, follow_redirects=True) def upload_something(self, extension, message): \"\"\"",
"def test_request_review(self): rv = self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make review request tested with files\")",
"follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make review request tested with files\") def test_make_review_request(self): rv = self.make_review_request(\"title\",",
"reading', 'category':'academic', 'deadline':str(timestamp)} rather_not = ['sh', 'ps1','ghost','exe'] def do_post(self, data): return self.app.post('/request_review', data=data,",
"self.update_post(101,\"new title\",\"new content with a lot of blah\", \\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data) def test_all_reviews(self):",
"rv = self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make review request tested with files\") def test_make_review_request(self):",
"explorer of new lands\") self.assertIn(\"Your profile has been updated\", rv.data) def make_review_request(self,title,content,category,deadline): return",
"self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews of drafts published by\", rv.data) def test_show_responses(self): rv = self.app.get('/reviews/201')",
"url_for from src import flaskr from src import modele from src.config import TestConfig",
"setUp(self): \"\"\"Before each test, set up a blank database\"\"\" self.app = flaskr.app.test_client() self.login(\"Hugo\",",
"= \"/req/\" + str(id) return self.app.get(url, follow_redirects=True) def test_click_reviews(self): rv = self.click_reviews(1) self.assertEqual(200,",
"what if update is not allowed? Hugo's article has id 101, he tries",
"= self.edit_profile() self.assertIn(\"Edit your profile Hugo\", rv.data) def update_profile(self, email,about_me): return self.app.post(\"/edit_profile\", data=dict(email=email,",
"def review_this(self,review_text,rating,request_id): url = '/req/post/' + str(request_id) return self.app.post(url, data=dict( review_text=review_text, rating=rating), follow_redirects=True)",
"of so much importance to literature.\", \"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code) def main_thread(self): return self.app.get('/',",
"self.app.post(\"/post_request_review\", data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) def test_request_review(self): rv = self.app.get(\"/request_review\", follow_redirects=True)",
"TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request sucessfuly') def test_upload_invalid_data(self): # Invalid extensions # we expect a",
"self.assertNotIn(\"Update Request\", rv.data) def update_post(self,id,title,content,category,deadline): url = \"/req/update/\" + str(id) return self.app.post(url,data=dict( title=title,",
"Request\", rv.data) url = \"/req/\" + str(3) rv = self.app.get(url) self.assertNotIn(\"Update Request\", rv.data)",
"= 'file.%s' % extension data[\"file\"] = (StringIO.StringIO('new file'), filename) response = self.do_post(data) self.assertEqual(response.status_code,200)",
"follow_redirects=True) def test_edit_profile(self): rv = self.edit_profile() self.assertIn(\"Edit your profile Hugo\", rv.data) def update_profile(self,",
"self.app.post('/request_review', data=data, follow_redirects=True) def upload_something(self, extension, message): \"\"\" Message, expected message in flash.",
"self.update_profile(\"maniana\", \"Curious explorer of new lands\") self.assertIn(\"Your profile has been updated\", rv.data) def",
"(StringIO.StringIO('new file'), filename) response = self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def test_upload_allowed_formats(self): # valid formats",
"import time import StringIO import logging from flask import url_for from src import",
"= self.update_post(102,\"new title\",\"new content with long soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data) # now",
"self.assertEqual(200,rv.status_code) def test_update_possible(self): url = \"/req/\" + str(101) rv = self.app.get(url) self.assertIn(\"Update Request\",",
"rv.data) class TestPostRequest(BaseTestCase): data = {'title':'Lewiathanus livus', 'content':'A book by Hobbes is always",
"test, set up a blank database\"\"\" self.app = flaskr.app.test_client() self.login(\"Hugo\", \"secret\") def tearDown(self):",
"message): \"\"\" Message, expected message in flash. \"\"\" data = self.data.copy() filename =",
"return self.app.post('/login', data=dict( username=username, password=password), follow_redirects=True) def logout (self): return self.app.get('/logout', follow_redirects=True) class",
"yet\") def test_update_post(self): # what if update is not allowed? Hugo's article has",
"up a blank database\"\"\" self.app = flaskr.app.test_client() self.login(\"Hugo\", \"secret\") def tearDown(self): self.logout() def",
"data=dict(email=email, about_me=about_me), follow_redirects=True) def test_update_profile(self): rv = self.update_profile(\"maniana\", \"Curious explorer of new lands\")",
"rv = self.edit_profile() self.assertIn(\"Edit your profile Hugo\", rv.data) def update_profile(self, email,about_me): return self.app.post(\"/edit_profile\",",
"if update is not allowed? Hugo's article has id 101, he tries #",
"\\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data) def test_all_reviews(self): rv = self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All reviews written by",
"return self.app.post(\"/post_request_review\", data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) def test_request_review(self): rv = self.app.get(\"/request_review\",",
"update 102 rv = self.update_post(102,\"new title\",\"new content with long soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\",",
"= \"/req/\" + str(101) rv = self.app.get(url) self.assertIn(\"Update Request\", rv.data) url = \"/req/\"",
"= {'title':'Lewiathanus livus', 'content':'A book by Hobbes is always worth reading', 'category':'academic', 'deadline':str(timestamp)}",
"import modele from src.config import TestConfig from utilities import manipulate_db from tests import",
"added\",rv.data) def test_reviews_of_user(self): rv = self.app.get(\"/reviews_of_user/%s\" % 2, follow_redirects=True) self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews of",
"self.assertIn(\"Your profile has been updated\", rv.data) def make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\", data=dict( title=title, content=content,",
"test_show_responses(self): rv = self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def test_update_possible(self): url = \"/req/\" + str(101) rv",
"self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def test_upload_allowed_formats(self): # valid formats for ext in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request",
"now a valid request rv = self.update_post(101,\"new title\",\"new content with a lot of",
"self.login(\"Hugo\", \"secret\") def tearDown(self): self.logout() def login(self,username,password): return self.app.post('/login', data=dict( username=username, password=password), follow_redirects=True)",
"been updated\", rv.data) def make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\", data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True)",
"test_request_review(self): rv = self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make review request tested with files\") def",
"os,sys import unittest from contextlib import closing from datetime import datetime import time",
"rating=rating), follow_redirects=True) def test_review_this(self): # invalid request response = self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data) rv",
"it message = \"following formats are allowed:\" for ext in self.rather_not: self.upload_something(ext, message)",
"amazing\", 5, 101) self.assertEqual(rv.status_code,200) self.assertIn(\"has been added\",rv.data) def test_reviews_of_user(self): rv = self.app.get(\"/reviews_of_user/%s\" %",
"import closing from datetime import datetime import time import StringIO import logging from",
"rv = self.app.get(url) self.assertIn(\"Update Request\", rv.data) url = \"/req/\" + str(3) rv =",
"self.rather_not: self.upload_something(ext, message) def test_no_file(self): rv = self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No file added\",rv.data) def",
"blah\", \\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data) def test_all_reviews(self): rv = self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All reviews written",
"\"\"\"Before each test, set up a blank database\"\"\" self.app = flaskr.app.test_client() self.login(\"Hugo\", \"secret\")",
"valid request rv = self.update_post(101,\"new title\",\"new content with a lot of blah\", \\",
"Invalid extensions # we expect a message informing about it message = \"following",
"return self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me), follow_redirects=True) def test_update_profile(self): rv = self.update_profile(\"maniana\", \"Curious explorer of",
"email,about_me): return self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me), follow_redirects=True) def test_update_profile(self): rv = self.update_profile(\"maniana\", \"Curious explorer",
"are allowed:\" for ext in self.rather_not: self.upload_something(ext, message) def test_no_file(self): rv = self.do_post(self.data)",
"import datetime import time import StringIO import logging from flask import url_for from",
"= self.app.get(url) self.assertNotIn(\"Update Request\", rv.data) def update_post(self,id,title,content,category,deadline): url = \"/req/update/\" + str(id) return",
"the app. \"\"\" import os,sys import unittest from contextlib import closing from datetime",
"login(self,username,password): return self.app.post('/login', data=dict( username=username, password=password), follow_redirects=True) def logout (self): return self.app.get('/logout', follow_redirects=True)",
"data=data, follow_redirects=True) def upload_something(self, extension, message): \"\"\" Message, expected message in flash. \"\"\"",
"literature.\", \"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code) def main_thread(self): return self.app.get('/', follow_redirects=True) def test_main_thread(self): rv =",
"GeneralTestCase(BaseTestCase): def edit_profile(self): return self.app.get(\"/edit_profile\", follow_redirects=True) def test_edit_profile(self): rv = self.edit_profile() self.assertIn(\"Edit your",
"much importance to literature.\", \"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code) def main_thread(self): return self.app.get('/', follow_redirects=True) def",
"test_review_this(self): # invalid request response = self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data) rv = self.review_this( \"nice",
"= self.review_this( \"nice work this is amazing\", 5, 101) self.assertEqual(rv.status_code,200) self.assertIn(\"has been added\",rv.data)",
"\"\" rv = self.do_post(data) self.assertEqual(rv.status_code,200) self.assertIn(\"Invalid form.\",rv.data) if __name__ == '__main__': manipulate_db.populateDb(TestConfig.DATABASE) unittest.main()",
"of new lands\") self.assertIn(\"Your profile has been updated\", rv.data) def make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\",",
"= self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make review request tested with files\") def test_make_review_request(self): rv",
"rv = self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No file added\",rv.data) def test_invalid_form(self): data = self.data.copy() data[\"content\"]",
"(self): return self.app.get('/logout', follow_redirects=True) class GeneralTestCase(BaseTestCase): def edit_profile(self): return self.app.get(\"/edit_profile\", follow_redirects=True) def test_edit_profile(self):",
"logging from flask import url_for from src import flaskr from src import modele",
"extension, message): \"\"\" Message, expected message in flash. \"\"\" data = self.data.copy() filename",
"follow_redirects=True) def test_request_review(self): rv = self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make review request tested with",
"= self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def test_update_possible(self): url = \"/req/\" + str(101) rv = self.app.get(url)",
"time import StringIO import logging from flask import url_for from src import flaskr",
"your profile Hugo\", rv.data) def update_profile(self, email,about_me): return self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me), follow_redirects=True) def",
"self.app.get(\"/reviews_of_user/%s\" % 2, follow_redirects=True) self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews of drafts published by\", rv.data) def",
"update_post(self,id,title,content,category,deadline): url = \"/req/update/\" + str(id) return self.app.post(url,data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True)",
"return self.app.get('/display_user_requests/%s' % uid, follow_redirects=True) def test_display_user_request(self): rv = self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def",
"= \"following formats are allowed:\" for ext in self.rather_not: self.upload_something(ext, message) def test_no_file(self):",
"in flash. \"\"\" data = self.data.copy() filename = 'file.%s' % extension data[\"file\"] =",
"data = self.data.copy() data[\"content\"] = \"\" rv = self.do_post(data) self.assertEqual(rv.status_code,200) self.assertIn(\"Invalid form.\",rv.data) if",
"by\", rv.data) def test_show_responses(self): rv = self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def test_update_possible(self): url = \"/req/\"",
"expect a message informing about it message = \"following formats are allowed:\" for",
"from src import flaskr from src import modele from src.config import TestConfig from",
"sucessfuly') def test_upload_invalid_data(self): # Invalid extensions # we expect a message informing about",
"test_update_profile(self): rv = self.update_profile(\"maniana\", \"Curious explorer of new lands\") self.assertIn(\"Your profile has been",
"from contextlib import closing from datetime import datetime import time import StringIO import",
"follow_redirects=True) def test_display_user_request(self): rv = self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id): url = '/req/post/'",
"= datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class BaseTestCase(unittest.TestCase): def setUp(self): \"\"\"Before each test,",
"self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make review request tested with files\") def test_make_review_request(self): rv =",
"{'title':'Lewiathanus livus', 'content':'A book by Hobbes is always worth reading', 'category':'academic', 'deadline':str(timestamp)} rather_not",
"request sucessfuly') def test_upload_invalid_data(self): # Invalid extensions # we expect a message informing",
"test_edit_profile(self): rv = self.edit_profile() self.assertIn(\"Edit your profile Hugo\", rv.data) def update_profile(self, email,about_me): return",
"follow_redirects=True) class GeneralTestCase(BaseTestCase): def edit_profile(self): return self.app.get(\"/edit_profile\", follow_redirects=True) def test_edit_profile(self): rv = self.edit_profile()",
"= self.update_profile(\"maniana\", \"Curious explorer of new lands\") self.assertIn(\"Your profile has been updated\", rv.data)",
"flask import url_for from src import flaskr from src import modele from src.config",
"update_profile(self, email,about_me): return self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me), follow_redirects=True) def test_update_profile(self): rv = self.update_profile(\"maniana\", \"Curious",
"request rv = self.update_post(101,\"new title\",\"new content with a lot of blah\", \\ \"academic\",timestamp)",
"follow_redirects=True) def test_update_profile(self): rv = self.update_profile(\"maniana\", \"Curious explorer of new lands\") self.assertIn(\"Your profile",
"password=password), follow_redirects=True) def logout (self): return self.app.get('/logout', follow_redirects=True) class GeneralTestCase(BaseTestCase): def edit_profile(self): return",
"self.upload_something(ext,'review request sucessfuly') def test_upload_invalid_data(self): # Invalid extensions # we expect a message",
"test_login timestamp = datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class BaseTestCase(unittest.TestCase): def setUp(self): \"\"\"Before",
"+ str(101) rv = self.app.get(url) self.assertIn(\"Update Request\", rv.data) url = \"/req/\" + str(3)",
"def test_click_reviews(self): rv = self.click_reviews(1) self.assertEqual(200, rv.status_code) def display_user_requests(self,uid): return self.app.get('/display_user_requests/%s' % uid,",
"rv = self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def test_update_possible(self): url = \"/req/\" + str(101) rv =",
"url = \"/req/\" + str(id) return self.app.get(url, follow_redirects=True) def test_click_reviews(self): rv = self.click_reviews(1)",
"id 101, he tries # to update 102 rv = self.update_post(102,\"new title\",\"new content",
"profile Hugo\", rv.data) def update_profile(self, email,about_me): return self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me), follow_redirects=True) def test_update_profile(self):",
"he tries # to update 102 rv = self.update_post(102,\"new title\",\"new content with long",
"src import modele from src.config import TestConfig from utilities import manipulate_db from tests",
"\"academic\",timestamp) self.assertIn(\"ok\",rv.data) def test_all_reviews(self): rv = self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All reviews written by all",
"message) def test_no_file(self): rv = self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No file added\",rv.data) def test_invalid_form(self): data",
"\"In this wos of so much importance to literature.\", \"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code) def",
"with a lot of blah\", \\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data) def test_all_reviews(self): rv = self.app.get('/reviews')",
"self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No file added\",rv.data) def test_invalid_form(self): data = self.data.copy() data[\"content\"] = \"\"",
"importance to literature.\", \"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code) def main_thread(self): return self.app.get('/', follow_redirects=True) def test_main_thread(self):",
"flash. \"\"\" data = self.data.copy() filename = 'file.%s' % extension data[\"file\"] = (StringIO.StringIO('new",
"self.app.get(url) self.assertNotIn(\"Update Request\", rv.data) def update_post(self,id,title,content,category,deadline): url = \"/req/update/\" + str(id) return self.app.post(url,data=dict(",
"lot of blah\", \\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data) def test_all_reviews(self): rv = self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All",
"self.assertEqual(200, rv.status_code) self.assertIn('Review Someone',rv.data) def click_reviews(self,id): url = \"/req/\" + str(id) return self.app.get(url,",
"url = \"/req/update/\" + str(id) return self.app.post(url,data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) <EMAIL>(\"not",
"about it message = \"following formats are allowed:\" for ext in self.rather_not: self.upload_something(ext,",
"do_post(self, data): return self.app.post('/request_review', data=data, follow_redirects=True) def upload_something(self, extension, message): \"\"\" Message, expected",
"uid, follow_redirects=True) def test_display_user_request(self): rv = self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id): url =",
"follow_redirects=True) def test_main_thread(self): rv = self.main_thread() self.assertEqual(200, rv.status_code) self.assertIn('Review Someone',rv.data) def click_reviews(self,id): url",
"from tests import test_login timestamp = datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class BaseTestCase(unittest.TestCase):",
"ext in self.rather_not: self.upload_something(ext, message) def test_no_file(self): rv = self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No file",
"title\",\"new content with long soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data) # now a valid",
"= self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data) rv = self.review_this( \"nice work this is amazing\", 5,",
"self.assertEqual(200, rv.status_code) def display_user_requests(self,uid): return self.app.get('/display_user_requests/%s' % uid, follow_redirects=True) def test_display_user_request(self): rv =",
"= self.app.get(\"/reviews_of_user/%s\" % 2, follow_redirects=True) self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews of drafts published by\", rv.data)",
"expected message in flash. \"\"\" data = self.data.copy() filename = 'file.%s' % extension",
"def test_make_review_request(self): rv = self.make_review_request(\"title\", \"In this wos of so much importance to",
"% extension data[\"file\"] = (StringIO.StringIO('new file'), filename) response = self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def",
"long soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data) # now a valid request rv =",
"# what if update is not allowed? Hugo's article has id 101, he",
"test_main_thread(self): rv = self.main_thread() self.assertEqual(200, rv.status_code) self.assertIn('Review Someone',rv.data) def click_reviews(self,id): url = \"/req/\"",
"# we expect a message informing about it message = \"following formats are",
"profile has been updated\", rv.data) def make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\", data=dict( title=title, content=content, category=category,",
"url = \"/req/\" + str(101) rv = self.app.get(url) self.assertIn(\"Update Request\", rv.data) url =",
"def click_reviews(self,id): url = \"/req/\" + str(id) return self.app.get(url, follow_redirects=True) def test_click_reviews(self): rv",
"follow_redirects=True) def logout (self): return self.app.get('/logout', follow_redirects=True) class GeneralTestCase(BaseTestCase): def edit_profile(self): return self.app.get(\"/edit_profile\",",
"informing about it message = \"following formats are allowed:\" for ext in self.rather_not:",
"= '/req/post/' + str(request_id) return self.app.post(url, data=dict( review_text=review_text, rating=rating), follow_redirects=True) def test_review_this(self): #",
"written by all users',rv.data) self.assertIn('Anonymous', rv.data) class TestPostRequest(BaseTestCase): data = {'title':'Lewiathanus livus', 'content':'A",
"always worth reading', 'category':'academic', 'deadline':str(timestamp)} rather_not = ['sh', 'ps1','ghost','exe'] def do_post(self, data): return",
"from src import modele from src.config import TestConfig from utilities import manipulate_db from",
"src.config import TestConfig from utilities import manipulate_db from tests import test_login timestamp =",
"closing from datetime import datetime import time import StringIO import logging from flask",
"livus', 'content':'A book by Hobbes is always worth reading', 'category':'academic', 'deadline':str(timestamp)} rather_not =",
"Hugo's article has id 101, he tries # to update 102 rv =",
"test_no_file(self): rv = self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No file added\",rv.data) def test_invalid_form(self): data = self.data.copy()",
"return self.app.get('/logout', follow_redirects=True) class GeneralTestCase(BaseTestCase): def edit_profile(self): return self.app.get(\"/edit_profile\", follow_redirects=True) def test_edit_profile(self): rv",
"import logging from flask import url_for from src import flaskr from src import",
"self.app.get('/display_user_requests/%s' % uid, follow_redirects=True) def test_display_user_request(self): rv = self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id):",
"self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id): url = '/req/post/' + str(request_id) return self.app.post(url, data=dict( review_text=review_text, rating=rating),",
"update is not allowed? Hugo's article has id 101, he tries # to",
"from utilities import manipulate_db from tests import test_login timestamp = datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger",
"datetime import datetime import time import StringIO import logging from flask import url_for",
"each test, set up a blank database\"\"\" self.app = flaskr.app.test_client() self.login(\"Hugo\", \"secret\") def",
"\"/req/\" + str(3) rv = self.app.get(url) self.assertNotIn(\"Update Request\", rv.data) def update_post(self,id,title,content,category,deadline): url =",
"test_click_reviews(self): rv = self.click_reviews(1) self.assertEqual(200, rv.status_code) def display_user_requests(self,uid): return self.app.get('/display_user_requests/%s' % uid, follow_redirects=True)",
"102 rv = self.update_post(102,\"new title\",\"new content with long soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data)",
"def test_upload_invalid_data(self): # Invalid extensions # we expect a message informing about it",
"def test_update_profile(self): rv = self.update_profile(\"maniana\", \"Curious explorer of new lands\") self.assertIn(\"Your profile has",
"in self.rather_not: self.upload_something(ext, message) def test_no_file(self): rv = self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No file added\",rv.data)",
"rv = self.make_review_request(\"title\", \"In this wos of so much importance to literature.\", \"academic\",",
"formats are allowed:\" for ext in self.rather_not: self.upload_something(ext, message) def test_no_file(self): rv =",
"self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id): url = '/req/post/' + str(request_id) return self.app.post(url, data=dict(",
"ext in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request sucessfuly') def test_upload_invalid_data(self): # Invalid extensions # we",
"title=title, content=content, category=category, deadline=deadline), follow_redirects=True) <EMAIL>(\"not implemented yet\") def test_update_post(self): # what if",
"with long soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data) # now a valid request rv",
"import test_login timestamp = datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class BaseTestCase(unittest.TestCase): def setUp(self):",
"datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class BaseTestCase(unittest.TestCase): def setUp(self): \"\"\"Before each test, set",
"self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def test_update_possible(self): url = \"/req/\" + str(101) rv = self.app.get(url) self.assertIn(\"Update",
"\"/req/\" + str(101) rv = self.app.get(url) self.assertIn(\"Update Request\", rv.data) url = \"/req/\" +",
"data = {'title':'Lewiathanus livus', 'content':'A book by Hobbes is always worth reading', 'category':'academic',",
"allowed:\" for ext in self.rather_not: self.upload_something(ext, message) def test_no_file(self): rv = self.do_post(self.data) self.assertEqual(rv.status_code,200)",
"file'), filename) response = self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def test_upload_allowed_formats(self): # valid formats for",
"content=content, category=category, deadline=deadline), follow_redirects=True) def test_request_review(self): rv = self.app.get(\"/request_review\", follow_redirects=True) self.assertEqual(200,rv.status_code) @unittest.skip(\"make review",
"work this is amazing\", 5, 101) self.assertEqual(rv.status_code,200) self.assertIn(\"has been added\",rv.data) def test_reviews_of_user(self): rv",
"\"\"\" import os,sys import unittest from contextlib import closing from datetime import datetime",
"been added\",rv.data) def test_reviews_of_user(self): rv = self.app.get(\"/reviews_of_user/%s\" % 2, follow_redirects=True) self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews",
"# now a valid request rv = self.update_post(101,\"new title\",\"new content with a lot",
"data[\"file\"] = (StringIO.StringIO('new file'), filename) response = self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def test_upload_allowed_formats(self): #",
"self.main_thread() self.assertEqual(200, rv.status_code) self.assertIn('Review Someone',rv.data) def click_reviews(self,id): url = \"/req/\" + str(id) return",
"101) self.assertEqual(rv.status_code,200) self.assertIn(\"has been added\",rv.data) def test_reviews_of_user(self): rv = self.app.get(\"/reviews_of_user/%s\" % 2, follow_redirects=True)",
"self.edit_profile() self.assertIn(\"Edit your profile Hugo\", rv.data) def update_profile(self, email,about_me): return self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me),",
"def test_review_this(self): # invalid request response = self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data) rv = self.review_this(",
"users',rv.data) self.assertIn('Anonymous', rv.data) class TestPostRequest(BaseTestCase): data = {'title':'Lewiathanus livus', 'content':'A book by Hobbes",
"self.assertIn(\"errors\",response.data) rv = self.review_this( \"nice work this is amazing\", 5, 101) self.assertEqual(rv.status_code,200) self.assertIn(\"has",
"in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request sucessfuly') def test_upload_invalid_data(self): # Invalid extensions # we expect",
"rv.data) def update_profile(self, email,about_me): return self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me), follow_redirects=True) def test_update_profile(self): rv =",
"follow_redirects=True) <EMAIL>(\"not implemented yet\") def test_update_post(self): # what if update is not allowed?",
"self.assertEqual(rv.status_code,200) self.assertIn(\"has been added\",rv.data) def test_reviews_of_user(self): rv = self.app.get(\"/reviews_of_user/%s\" % 2, follow_redirects=True) self.assertEqual(rv.status_code,",
"= logging.getLogger(__name__) class BaseTestCase(unittest.TestCase): def setUp(self): \"\"\"Before each test, set up a blank",
"self.assertIn(\"Edit your profile Hugo\", rv.data) def update_profile(self, email,about_me): return self.app.post(\"/edit_profile\", data=dict(email=email, about_me=about_me), follow_redirects=True)",
"<reponame>pawelmhm/recenseo.es \"\"\" Integration tests for the app. \"\"\" import os,sys import unittest from",
"data): return self.app.post('/request_review', data=data, follow_redirects=True) def upload_something(self, extension, message): \"\"\" Message, expected message",
"Someone',rv.data) def click_reviews(self,id): url = \"/req/\" + str(id) return self.app.get(url, follow_redirects=True) def test_click_reviews(self):",
"category=category, deadline=deadline), follow_redirects=True) <EMAIL>(\"not implemented yet\") def test_update_post(self): # what if update is",
"src import flaskr from src import modele from src.config import TestConfig from utilities",
"self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data) # now a valid request rv = self.update_post(101,\"new title\",\"new content",
"from flask import url_for from src import flaskr from src import modele from",
"for the app. \"\"\" import os,sys import unittest from contextlib import closing from",
"url = '/req/post/' + str(request_id) return self.app.post(url, data=dict( review_text=review_text, rating=rating), follow_redirects=True) def test_review_this(self):",
"review request tested with files\") def test_make_review_request(self): rv = self.make_review_request(\"title\", \"In this wos",
"filename = 'file.%s' % extension data[\"file\"] = (StringIO.StringIO('new file'), filename) response = self.do_post(data)",
"self.assertIn(message,response.data) def test_upload_allowed_formats(self): # valid formats for ext in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request sucessfuly')",
"test_upload_allowed_formats(self): # valid formats for ext in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request sucessfuly') def test_upload_invalid_data(self):",
"str(id) return self.app.get(url, follow_redirects=True) def test_click_reviews(self): rv = self.click_reviews(1) self.assertEqual(200, rv.status_code) def display_user_requests(self,uid):",
"formats for ext in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request sucessfuly') def test_upload_invalid_data(self): # Invalid extensions",
"str(101) rv = self.app.get(url) self.assertIn(\"Update Request\", rv.data) url = \"/req/\" + str(3) rv",
"self.assertEqual(rv.status_code,200) self.assertIn(\"No file added\",rv.data) def test_invalid_form(self): data = self.data.copy() data[\"content\"] = \"\" rv",
"import manipulate_db from tests import test_login timestamp = datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__)",
"rv = self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id): url = '/req/post/' + str(request_id) return",
"101, he tries # to update 102 rv = self.update_post(102,\"new title\",\"new content with",
"follow_redirects=True) def upload_something(self, extension, message): \"\"\" Message, expected message in flash. \"\"\" data",
"rv = self.update_post(102,\"new title\",\"new content with long soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data) #",
"all users',rv.data) self.assertIn('Anonymous', rv.data) class TestPostRequest(BaseTestCase): data = {'title':'Lewiathanus livus', 'content':'A book by",
"self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id): url = '/req/post/' + str(request_id) return self.app.post(url, data=dict( review_text=review_text,",
"Integration tests for the app. \"\"\" import os,sys import unittest from contextlib import",
"self.app.get('/', follow_redirects=True) def test_main_thread(self): rv = self.main_thread() self.assertEqual(200, rv.status_code) self.assertIn('Review Someone',rv.data) def click_reviews(self,id):",
"= \"/req/\" + str(3) rv = self.app.get(url) self.assertNotIn(\"Update Request\", rv.data) def update_post(self,id,title,content,category,deadline): url",
"review_this(self,review_text,rating,request_id): url = '/req/post/' + str(request_id) return self.app.post(url, data=dict( review_text=review_text, rating=rating), follow_redirects=True) def",
"edit_profile(self): return self.app.get(\"/edit_profile\", follow_redirects=True) def test_edit_profile(self): rv = self.edit_profile() self.assertIn(\"Edit your profile Hugo\",",
"2, follow_redirects=True) self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews of drafts published by\", rv.data) def test_show_responses(self): rv",
"self.app = flaskr.app.test_client() self.login(\"Hugo\", \"secret\") def tearDown(self): self.logout() def login(self,username,password): return self.app.post('/login', data=dict(",
"# valid formats for ext in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review request sucessfuly') def test_upload_invalid_data(self): #",
"return self.app.get(\"/edit_profile\", follow_redirects=True) def test_edit_profile(self): rv = self.edit_profile() self.assertIn(\"Edit your profile Hugo\", rv.data)",
"self.assertEqual(200,rv.status_code) @unittest.skip(\"make review request tested with files\") def test_make_review_request(self): rv = self.make_review_request(\"title\", \"In",
"import StringIO import logging from flask import url_for from src import flaskr from",
"rv.data) url = \"/req/\" + str(3) rv = self.app.get(url) self.assertNotIn(\"Update Request\", rv.data) def",
"class TestPostRequest(BaseTestCase): data = {'title':'Lewiathanus livus', 'content':'A book by Hobbes is always worth",
"app. \"\"\" import os,sys import unittest from contextlib import closing from datetime import",
"rv = self.app.get('/reviews') self.assertEqual(rv.status_code,200) self.assertIn('All reviews written by all users',rv.data) self.assertIn('Anonymous', rv.data) class",
"blank database\"\"\" self.app = flaskr.app.test_client() self.login(\"Hugo\", \"secret\") def tearDown(self): self.logout() def login(self,username,password): return",
"test_display_user_request(self): rv = self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id): url = '/req/post/' + str(request_id)",
"rv.data) def test_show_responses(self): rv = self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def test_update_possible(self): url = \"/req/\" +",
"book by Hobbes is always worth reading', 'category':'academic', 'deadline':str(timestamp)} rather_not = ['sh', 'ps1','ghost','exe']",
"worth reading', 'category':'academic', 'deadline':str(timestamp)} rather_not = ['sh', 'ps1','ghost','exe'] def do_post(self, data): return self.app.post('/request_review',",
"TestPostRequest(BaseTestCase): data = {'title':'Lewiathanus livus', 'content':'A book by Hobbes is always worth reading',",
"follow_redirects=True) self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews of drafts published by\", rv.data) def test_show_responses(self): rv =",
"= self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def test_upload_allowed_formats(self): # valid formats for ext in TestConfig.ALLOWED_EXTENSIONS:",
"return self.app.post('/request_review', data=data, follow_redirects=True) def upload_something(self, extension, message): \"\"\" Message, expected message in",
"contextlib import closing from datetime import datetime import time import StringIO import logging",
"make_review_request(self,title,content,category,deadline): return self.app.post(\"/post_request_review\", data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) def test_request_review(self): rv =",
"is amazing\", 5, 101) self.assertEqual(rv.status_code,200) self.assertIn(\"has been added\",rv.data) def test_reviews_of_user(self): rv = self.app.get(\"/reviews_of_user/%s\"",
"self.assertEqual(rv.status_code,200) self.assertIn('All reviews written by all users',rv.data) self.assertIn('Anonymous', rv.data) class TestPostRequest(BaseTestCase): data =",
"test_update_possible(self): url = \"/req/\" + str(101) rv = self.app.get(url) self.assertIn(\"Update Request\", rv.data) url",
"class GeneralTestCase(BaseTestCase): def edit_profile(self): return self.app.get(\"/edit_profile\", follow_redirects=True) def test_edit_profile(self): rv = self.edit_profile() self.assertIn(\"Edit",
"self.assertEqual(200,rv.status_code) def main_thread(self): return self.app.get('/', follow_redirects=True) def test_main_thread(self): rv = self.main_thread() self.assertEqual(200, rv.status_code)",
"'category':'academic', 'deadline':str(timestamp)} rather_not = ['sh', 'ps1','ghost','exe'] def do_post(self, data): return self.app.post('/request_review', data=data, follow_redirects=True)",
"['sh', 'ps1','ghost','exe'] def do_post(self, data): return self.app.post('/request_review', data=data, follow_redirects=True) def upload_something(self, extension, message):",
"test_make_review_request(self): rv = self.make_review_request(\"title\", \"In this wos of so much importance to literature.\",",
"self.app.get(\"/edit_profile\", follow_redirects=True) def test_edit_profile(self): rv = self.edit_profile() self.assertIn(\"Edit your profile Hugo\", rv.data) def",
"import unittest from contextlib import closing from datetime import datetime import time import",
"def tearDown(self): self.logout() def login(self,username,password): return self.app.post('/login', data=dict( username=username, password=password), follow_redirects=True) def logout",
"click_reviews(self,id): url = \"/req/\" + str(id) return self.app.get(url, follow_redirects=True) def test_click_reviews(self): rv =",
"self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def test_upload_allowed_formats(self): # valid formats for ext in TestConfig.ALLOWED_EXTENSIONS: self.upload_something(ext,'review",
"reviews written by all users',rv.data) self.assertIn('Anonymous', rv.data) class TestPostRequest(BaseTestCase): data = {'title':'Lewiathanus livus',",
"not allowed? Hugo's article has id 101, he tries # to update 102",
"BaseTestCase(unittest.TestCase): def setUp(self): \"\"\"Before each test, set up a blank database\"\"\" self.app =",
"rv = self.app.get(\"/reviews_of_user/%s\" % 2, follow_redirects=True) self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews of drafts published by\",",
"drafts published by\", rv.data) def test_show_responses(self): rv = self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def test_update_possible(self): url",
"set up a blank database\"\"\" self.app = flaskr.app.test_client() self.login(\"Hugo\", \"secret\") def tearDown(self): self.logout()",
"files\") def test_make_review_request(self): rv = self.make_review_request(\"title\", \"In this wos of so much importance",
"tests import test_login timestamp = datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class BaseTestCase(unittest.TestCase): def",
"return self.app.post(url,data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) <EMAIL>(\"not implemented yet\") def test_update_post(self): #",
"self.data.copy() filename = 'file.%s' % extension data[\"file\"] = (StringIO.StringIO('new file'), filename) response =",
"Request\", rv.data) def update_post(self,id,title,content,category,deadline): url = \"/req/update/\" + str(id) return self.app.post(url,data=dict( title=title, content=content,",
"def do_post(self, data): return self.app.post('/request_review', data=data, follow_redirects=True) def upload_something(self, extension, message): \"\"\" Message,",
"\"/req/update/\" + str(id) return self.app.post(url,data=dict( title=title, content=content, category=category, deadline=deadline), follow_redirects=True) <EMAIL>(\"not implemented yet\")",
"def login(self,username,password): return self.app.post('/login', data=dict( username=username, password=password), follow_redirects=True) def logout (self): return self.app.get('/logout',",
"data = self.data.copy() filename = 'file.%s' % extension data[\"file\"] = (StringIO.StringIO('new file'), filename)",
"a blank database\"\"\" self.app = flaskr.app.test_client() self.login(\"Hugo\", \"secret\") def tearDown(self): self.logout() def login(self,username,password):",
"rv = self.app.get(url) self.assertNotIn(\"Update Request\", rv.data) def update_post(self,id,title,content,category,deadline): url = \"/req/update/\" + str(id)",
"\"\"\" Message, expected message in flash. \"\"\" data = self.data.copy() filename = 'file.%s'",
"data[\"content\"] = \"\" rv = self.do_post(data) self.assertEqual(rv.status_code,200) self.assertIn(\"Invalid form.\",rv.data) if __name__ == '__main__':",
"= self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data) def review_this(self,review_text,rating,request_id): url = '/req/post/' + str(request_id) return self.app.post(url,",
"extension data[\"file\"] = (StringIO.StringIO('new file'), filename) response = self.do_post(data) self.assertEqual(response.status_code,200) self.assertIn(message,response.data) def test_upload_allowed_formats(self):",
"import TestConfig from utilities import manipulate_db from tests import test_login timestamp = datetime.fromtimestamp(time.time())",
"# to update 102 rv = self.update_post(102,\"new title\",\"new content with long soom\",\\ \"academic\",timestamp)",
"StringIO import logging from flask import url_for from src import flaskr from src",
"self.app.get(url, follow_redirects=True) def test_click_reviews(self): rv = self.click_reviews(1) self.assertEqual(200, rv.status_code) def display_user_requests(self,uid): return self.app.get('/display_user_requests/%s'",
"% 2, follow_redirects=True) self.assertEqual(rv.status_code, 200) self.assertIn(\"reviews of drafts published by\", rv.data) def test_show_responses(self):",
"invalid request response = self.review_this(\"good work\",99,102) self.assertIn(\"errors\",response.data) rv = self.review_this( \"nice work this",
"data=dict( review_text=review_text, rating=rating), follow_redirects=True) def test_review_this(self): # invalid request response = self.review_this(\"good work\",99,102)",
"deadline=deadline), follow_redirects=True) <EMAIL>(\"not implemented yet\") def test_update_post(self): # what if update is not",
"message = \"following formats are allowed:\" for ext in self.rather_not: self.upload_something(ext, message) def",
"of drafts published by\", rv.data) def test_show_responses(self): rv = self.app.get('/reviews/201') self.assertEqual(200,rv.status_code) def test_update_possible(self):",
"rv = self.update_post(101,\"new title\",\"new content with a lot of blah\", \\ \"academic\",timestamp) self.assertIn(\"ok\",rv.data)",
"\"academic\", \"09/12/2012\") self.assertEqual(200,rv.status_code) def main_thread(self): return self.app.get('/', follow_redirects=True) def test_main_thread(self): rv = self.main_thread()",
"article has id 101, he tries # to update 102 rv = self.update_post(102,\"new",
"display_user_requests(self,uid): return self.app.get('/display_user_requests/%s' % uid, follow_redirects=True) def test_display_user_request(self): rv = self.display_user_requests(1) self.assertEqual(rv.status_code,200) self.assertIn(\"Hugo\",rv.data)",
"datetime import time import StringIO import logging from flask import url_for from src",
"\"\"\" Integration tests for the app. \"\"\" import os,sys import unittest from contextlib",
"logger = logging.getLogger(__name__) class BaseTestCase(unittest.TestCase): def setUp(self): \"\"\"Before each test, set up a",
"data=dict( username=username, password=password), follow_redirects=True) def logout (self): return self.app.get('/logout', follow_redirects=True) class GeneralTestCase(BaseTestCase): def",
"upload_something(self, extension, message): \"\"\" Message, expected message in flash. \"\"\" data = self.data.copy()",
"return self.app.get(url, follow_redirects=True) def test_click_reviews(self): rv = self.click_reviews(1) self.assertEqual(200, rv.status_code) def display_user_requests(self,uid): return",
"logout (self): return self.app.get('/logout', follow_redirects=True) class GeneralTestCase(BaseTestCase): def edit_profile(self): return self.app.get(\"/edit_profile\", follow_redirects=True) def",
"return self.app.post(url, data=dict( review_text=review_text, rating=rating), follow_redirects=True) def test_review_this(self): # invalid request response =",
"\"secret\") def tearDown(self): self.logout() def login(self,username,password): return self.app.post('/login', data=dict( username=username, password=password), follow_redirects=True) def",
"timestamp = datetime.fromtimestamp(time.time()) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class BaseTestCase(unittest.TestCase): def setUp(self): \"\"\"Before each",
"content with long soom\",\\ \"academic\",timestamp) self.assertEqual(200,rv.status_code) self.assertIn(\"invalid\", rv.data) # now a valid request",
"flaskr from src import modele from src.config import TestConfig from utilities import manipulate_db",
"self.assertIn(\"invalid\", rv.data) # now a valid request rv = self.update_post(101,\"new title\",\"new content with",
"rv.data) def update_post(self,id,title,content,category,deadline): url = \"/req/update/\" + str(id) return self.app.post(url,data=dict( title=title, content=content, category=category,",
"self.app.post('/login', data=dict( username=username, password=password), follow_redirects=True) def logout (self): return self.app.get('/logout', follow_redirects=True) class GeneralTestCase(BaseTestCase):",
"= self.make_review_request(\"title\", \"In this wos of so much importance to literature.\", \"academic\", \"09/12/2012\")",
"Hobbes is always worth reading', 'category':'academic', 'deadline':str(timestamp)} rather_not = ['sh', 'ps1','ghost','exe'] def do_post(self,",
"+ str(id) return self.app.get(url, follow_redirects=True) def test_click_reviews(self): rv = self.click_reviews(1) self.assertEqual(200, rv.status_code) def",
"added\",rv.data) def test_invalid_form(self): data = self.data.copy() data[\"content\"] = \"\" rv = self.do_post(data) self.assertEqual(rv.status_code,200)",
"tested with files\") def test_make_review_request(self): rv = self.make_review_request(\"title\", \"In this wos of so",
"self.upload_something(ext, message) def test_no_file(self): rv = self.do_post(self.data) self.assertEqual(rv.status_code,200) self.assertIn(\"No file added\",rv.data) def test_invalid_form(self):",
"request tested with files\") def test_make_review_request(self): rv = self.make_review_request(\"title\", \"In this wos of"
] |
[] |
[
"contains the mongo_db_from_config code.\"\"\" from .mongo_db_from_config import db_from_config __version__ = \"0.0.1\" __all__ =",
"\"\"\"This package contains the mongo_db_from_config code.\"\"\" from .mongo_db_from_config import db_from_config __version__ = \"0.0.1\"",
"the mongo_db_from_config code.\"\"\" from .mongo_db_from_config import db_from_config __version__ = \"0.0.1\" __all__ = [\"db_from_config\"]",
"package contains the mongo_db_from_config code.\"\"\" from .mongo_db_from_config import db_from_config __version__ = \"0.0.1\" __all__"
] |
[
"range(number_qubits): for j in range(i): circuit.cu1(math.pi / float(2 ** (i - j)), qreg[i],",
"Copyright 2019, IBM. # # This source code is licensed under the Apache",
"the Apache License, Version 2.0 found in # the LICENSE.txt file in the",
"= QuantumRegister(number_qubits, name=\"myreg\") circuit = QuantumCircuit(qreg, name=\"qft\") for i in range(number_qubits): for j",
"i in range(number_qubits): for j in range(i): circuit.cu1(math.pi / float(2 ** (i -",
"range(i): circuit.cu1(math.pi / float(2 ** (i - j)), qreg[i], qreg[j]) circuit.h(qreg[i]) return circuit",
"circuit = QuantumCircuit(qreg, name=\"qft\") for i in range(number_qubits): for j in range(i): circuit.cu1(math.pi",
"<reponame>eddieschoute/circuit-benchmarks<filename>circuit_benchmarks/qft.py<gh_stars>1-10 # -*- coding: utf-8 -* # Copyright 2019, IBM. # # This",
"qiskit import QuantumRegister, QuantumCircuit def qft_circuit(number_qubits: int): \"\"\"Create quantum fourier transform circuit on",
"# the LICENSE.txt file in the root directory of this source tree. import",
"License, Version 2.0 found in # the LICENSE.txt file in the root directory",
"in the root directory of this source tree. import math from qiskit import",
"def qft_circuit(number_qubits: int): \"\"\"Create quantum fourier transform circuit on quantum register qreg.\"\"\" qreg",
"on quantum register qreg.\"\"\" qreg = QuantumRegister(number_qubits, name=\"myreg\") circuit = QuantumCircuit(qreg, name=\"qft\") for",
"quantum register qreg.\"\"\" qreg = QuantumRegister(number_qubits, name=\"myreg\") circuit = QuantumCircuit(qreg, name=\"qft\") for i",
"directory of this source tree. import math from qiskit import QuantumRegister, QuantumCircuit def",
"found in # the LICENSE.txt file in the root directory of this source",
"of this source tree. import math from qiskit import QuantumRegister, QuantumCircuit def qft_circuit(number_qubits:",
"utf-8 -* # Copyright 2019, IBM. # # This source code is licensed",
"2019, IBM. # # This source code is licensed under the Apache License,",
"# -*- coding: utf-8 -* # Copyright 2019, IBM. # # This source",
"quantum fourier transform circuit on quantum register qreg.\"\"\" qreg = QuantumRegister(number_qubits, name=\"myreg\") circuit",
"Version 2.0 found in # the LICENSE.txt file in the root directory of",
"coding: utf-8 -* # Copyright 2019, IBM. # # This source code is",
"file in the root directory of this source tree. import math from qiskit",
"the root directory of this source tree. import math from qiskit import QuantumRegister,",
"qreg.\"\"\" qreg = QuantumRegister(number_qubits, name=\"myreg\") circuit = QuantumCircuit(qreg, name=\"qft\") for i in range(number_qubits):",
"# This source code is licensed under the Apache License, Version 2.0 found",
"-*- coding: utf-8 -* # Copyright 2019, IBM. # # This source code",
"in range(i): circuit.cu1(math.pi / float(2 ** (i - j)), qreg[i], qreg[j]) circuit.h(qreg[i]) return",
"QuantumCircuit def qft_circuit(number_qubits: int): \"\"\"Create quantum fourier transform circuit on quantum register qreg.\"\"\"",
"from qiskit import QuantumRegister, QuantumCircuit def qft_circuit(number_qubits: int): \"\"\"Create quantum fourier transform circuit",
"QuantumRegister(number_qubits, name=\"myreg\") circuit = QuantumCircuit(qreg, name=\"qft\") for i in range(number_qubits): for j in",
"LICENSE.txt file in the root directory of this source tree. import math from",
"= QuantumCircuit(qreg, name=\"qft\") for i in range(number_qubits): for j in range(i): circuit.cu1(math.pi /",
"2.0 found in # the LICENSE.txt file in the root directory of this",
"name=\"myreg\") circuit = QuantumCircuit(qreg, name=\"qft\") for i in range(number_qubits): for j in range(i):",
"QuantumRegister, QuantumCircuit def qft_circuit(number_qubits: int): \"\"\"Create quantum fourier transform circuit on quantum register",
"math from qiskit import QuantumRegister, QuantumCircuit def qft_circuit(number_qubits: int): \"\"\"Create quantum fourier transform",
"Apache License, Version 2.0 found in # the LICENSE.txt file in the root",
"the LICENSE.txt file in the root directory of this source tree. import math",
"fourier transform circuit on quantum register qreg.\"\"\" qreg = QuantumRegister(number_qubits, name=\"myreg\") circuit =",
"transform circuit on quantum register qreg.\"\"\" qreg = QuantumRegister(number_qubits, name=\"myreg\") circuit = QuantumCircuit(qreg,",
"circuit on quantum register qreg.\"\"\" qreg = QuantumRegister(number_qubits, name=\"myreg\") circuit = QuantumCircuit(qreg, name=\"qft\")",
"IBM. # # This source code is licensed under the Apache License, Version",
"this source tree. import math from qiskit import QuantumRegister, QuantumCircuit def qft_circuit(number_qubits: int):",
"qft_circuit(number_qubits: int): \"\"\"Create quantum fourier transform circuit on quantum register qreg.\"\"\" qreg =",
"int): \"\"\"Create quantum fourier transform circuit on quantum register qreg.\"\"\" qreg = QuantumRegister(number_qubits,",
"\"\"\"Create quantum fourier transform circuit on quantum register qreg.\"\"\" qreg = QuantumRegister(number_qubits, name=\"myreg\")",
"# # This source code is licensed under the Apache License, Version 2.0",
"licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file",
"under the Apache License, Version 2.0 found in # the LICENSE.txt file in",
"import QuantumRegister, QuantumCircuit def qft_circuit(number_qubits: int): \"\"\"Create quantum fourier transform circuit on quantum",
"in range(number_qubits): for j in range(i): circuit.cu1(math.pi / float(2 ** (i - j)),",
"in # the LICENSE.txt file in the root directory of this source tree.",
"# Copyright 2019, IBM. # # This source code is licensed under the",
"import math from qiskit import QuantumRegister, QuantumCircuit def qft_circuit(number_qubits: int): \"\"\"Create quantum fourier",
"j in range(i): circuit.cu1(math.pi / float(2 ** (i - j)), qreg[i], qreg[j]) circuit.h(qreg[i])",
"tree. import math from qiskit import QuantumRegister, QuantumCircuit def qft_circuit(number_qubits: int): \"\"\"Create quantum",
"source code is licensed under the Apache License, Version 2.0 found in #",
"root directory of this source tree. import math from qiskit import QuantumRegister, QuantumCircuit",
"source tree. import math from qiskit import QuantumRegister, QuantumCircuit def qft_circuit(number_qubits: int): \"\"\"Create",
"register qreg.\"\"\" qreg = QuantumRegister(number_qubits, name=\"myreg\") circuit = QuantumCircuit(qreg, name=\"qft\") for i in",
"qreg = QuantumRegister(number_qubits, name=\"myreg\") circuit = QuantumCircuit(qreg, name=\"qft\") for i in range(number_qubits): for",
"name=\"qft\") for i in range(number_qubits): for j in range(i): circuit.cu1(math.pi / float(2 **",
"for i in range(number_qubits): for j in range(i): circuit.cu1(math.pi / float(2 ** (i",
"code is licensed under the Apache License, Version 2.0 found in # the",
"This source code is licensed under the Apache License, Version 2.0 found in",
"QuantumCircuit(qreg, name=\"qft\") for i in range(number_qubits): for j in range(i): circuit.cu1(math.pi / float(2",
"for j in range(i): circuit.cu1(math.pi / float(2 ** (i - j)), qreg[i], qreg[j])",
"is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt",
"-* # Copyright 2019, IBM. # # This source code is licensed under"
] |
[
"and Q signals together \"\"\" def __init__(self, totalTime, dt, dtIntegration, stokes, beta, signalToNoise=0.0,",
"= out.demodulateTrivial() # print \"Q/I_original={0} - Q/I_inferred={1} - Q/I_trivial={2} - diff={3}\".format(out.stokes[1] / out.stokes[0],",
"= [l for p in compression_pairs for l in p] ndarray = ndarray.reshape(flattened)",
"Q0 * np.sum(M2One * M4N) - V0 * U0 * np.sum(M3One * M4N)",
"noiseFFT self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing = myIFFT(self.seeingFFT) # Make sure that the total",
"parameters I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A = np.zeros((3,3))",
"self.sparseM[state].transpose(copy=True) self.factor = 2*np.ones(self.nSteps) self.factor[0] = 1.0 def forward(self, signal, beta, ray): return",
"= splinalg.eigsh(res, k=1, which='LM', return_eigenvectors=False) self.mu = 0.5 / (np.real(largestEigenvalue)) * 0.0002 t",
"= self.signalIntegrated[0] - (I0 * forwI + Q0 * forwQ + U0 *",
"# M1(t) * N(t) M2N = self.forwardPartial(signal, 1) # M2(t) * N(t) M3N",
"normL1 = [] normL2 = [] normL0 = [] for loop in range(niter):",
"Description seed : int, optional Description Returns ------- TYPE : Description \"\"\" self.totalTime",
"forwV) A[2,0] = A[0,2] A[1,2] = np.sum(forwU * forwV) A[2,1] = A[1,2] b",
"- diff={3}\".format(out.stokes[2] / out.stokes[0], stokes[2] / stokes[0], \\ # stU/stI, out.stokes[2] / out.stokes[0]-stokes[2]",
"ray): return self.sparseM[ray].dot(signal) def backward(self, z, ray): return self.factor * myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self,",
"betaU * self.backward(residual2, 2) + 2.0 * V0 * betaV * self.backward(residual2, 3)",
"time series Returns ------- float : Fourier coefficients of the real signal \"\"\"",
"* forwU + V0 * forwV) gradient1 = -2.0 * I0 * betaI",
"Fourier coefficients Returns ------- float : total power \"\"\" return f[0]**2 + 2.0*np.sum(f[1:]**2)",
"* forwQ - U0 * forwU - V0 * forwV) gradient2 = -2.0",
"= [] normL0 = [] for loop in range(niter): signal = myIFFT(x) forwI",
"V0 = np.linalg.solve(A,b) return I0, Q0, U0, V0 # totalTime = 1.0 #",
"U0, V0 # totalTime = 1.0 # s # dt = 0.001 #",
"self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 = 0.5",
"[] sparseRow = [] sparseCol = [] loop = 0 for i in",
"U0 * betaU * self.backward(residual2, 2) + 2.0 * V0 * betaV *",
"V0 * betaV * self.backward(residual1, 3) residual2 = self.signalIntegrated[1] - (I0 * forwI",
"self.totalTime = totalTime self.dt = dt self.dtIntegration = dtIntegration self.seed = seed self.signalToNoise",
"shape, by summing or averaging. Number of output dimensions must match number of",
"compression_pairs = [(d, c//d) for d, c in zip(new_shape, ndarray.shape)] flattened = [l",
"demodulateTrivial(self): forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0)",
"ax[1,1].plot(stokes[3] / stokes[0] * (1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21) # ax[2,1].semilogy(normL11)",
"2.0 * Q0 * betaQ * self.backward(residual1, 1) - \\ 2.0 * U0",
"0): I0 = 1.0 if (np.abs(Q0) > 1.0): Q0 = 1e-3 if (np.abs(U0)",
"- I={4:11.5f} - Q/I={5:11.5f} - U/I={6:11.5f} - V/I={7:11.5f} - bI={8:11.5f} - bQ={9:11.5f} -",
"import matplotlib.pyplot as pl import scipy.sparse as sp import scipy.sparse.linalg as splinalg import",
"3) # M4(t) * (1+betaV*N(t)) residual1 = self.signalIntegrated[0] - (I0 * forwI +",
"U0**2 * np.sum(M3One * M3N) - U0 * V0 * np.sum(M4One * M3N)",
"def __init__(self, totalTime, dt, dtIntegration, stokes, beta, signalToNoise=0.0, seed=0, modulationType=0): \"\"\"Summary Parameters ----------",
"V0 * np.sum(M4One * M3N) b[2] = 0.5 * V0 * np.sum(M4N *",
"np.copy(x) res = self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue = splinalg.eigsh(res, k=1, which='LM', return_eigenvectors=False) self.mu = 0.5",
"Nt /= np.sqrt(myTotalPower(coefFourier)) # stokesPar = ['I', 'Q', 'U', 'V'] # loop =",
"stokes[0], \\ # stQ/stI, out.stokes[1] / out.stokes[0]-stokes[1] / stokes[0]) # print \"U/I_original={0} -",
"for a real signal taking into account some normalization Parameters ---------- x :",
"['I', 'Q', 'U', 'V'] # loop = 0 # for loop in range(4):",
"np.copy(x) xPar[np.abs(x) < lambdaValue] = 0.0 return xPar def FISTA(self, initial=None, initialStokes=None, thresholdMethod='soft',",
"if (np.abs(U0) > 1.0): U0 = 1e-3 if (np.abs(V0) > 1.0): V0 =",
"real signal taking into account some normalization Parameters ---------- x : float Fourier",
"/ self.signalToNoise * np.random.randn(self.nSamples) self.tIntegrated = np.arange(self.nSamples) * self.dtIntegration # Generate modulation matrix",
"regularized problem using the FISTA algorithm, that solves the following problem: argmin_O ||y",
"= self.forwardPartial(np.ones(self.nSteps), 2) # M3(t) * 1(t) M4One = self.forwardPartial(np.ones(self.nSteps), 3) # M4(t)",
"0) - 2.0 * Q0 * betaQ * self.backward(residual1, 1) - \\ 2.0",
"N(t) M1One = self.forwardPartial(np.ones(self.nSteps), 0) # M1(t) * 1(t) M2One = self.forwardPartial(np.ones(self.nSteps), 1)",
"# stU/stI, out.stokes[2] / out.stokes[0]-stokes[2] / stokes[0]) # print \"V/I_original={0} - V/I_inferred={1} -",
"U0 * Q0 * np.sum(M2One * M3N) - U0**2 * np.sum(M3One * M3N)",
"= seed self.signalToNoise = signalToNoise self.modulationType = modulationType if (self.seed != 0): np.random.seed(self.seed)",
"\"U/I_original={0} - U/I_inferred={1} - U/I_trivial={2} - diff={3}\".format(out.stokes[2] / out.stokes[0], stokes[2] / stokes[0], \\",
"lambda/4 and lambda/2 polarimeter with random angles # self.modulation = [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0,",
"Returns ------- float : total power \"\"\" return f[0]**2 + 2.0*np.sum(f[1:]**2) class randomDemodulator(object):",
"* M3N) - U0 * V0 * np.sum(M4One * M3N) b[2] = 0.5",
"float Signal Fourier coefficients Returns ------- float : total power \"\"\" return f[0]**2",
"= 'soft', niter = 600, lambdaValue = 0.000000051) # stI, stQ, stU, stV",
"res = self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue = splinalg.eigsh(res, k=1, which='LM', return_eigenvectors=False) self.mu = 0.5 /",
"ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21) # ax[2,1].semilogy(normL11) # ax[3,0].plot(out.signalIntegrated[0]) # ax[3,0].plot(out.signalIntegrated[1]) # ax[3,1].plot(out.seeing) # ax[3,1].plot(Nt)",
"as sp import scipy.sparse.linalg as splinalg import scipy.fftpack as fft def bin_ndarray(ndarray, new_shape,",
"= 0.001 # s # dtIntegration = 0.01 #s # beta = np.asarray([15.0,",
"(np.abs(V0) > 1.0): V0 = 1e-3 # Seeing amplitude M1N = self.forwardPartial(signal, 0)",
"the IFFT for a real signal taking into account some normalization Parameters ----------",
"> 1.0): V0 = 1e-3 # Seeing amplitude M1N = self.forwardPartial(signal, 0) #",
"stokes # Generate Gaussian noise with unit variance and multiply by the square",
"temp = np.load('alphaBetaSamples.npz') self.alphaModulation = temp['arr_0'][0:self.nSteps] self.betaModulation = temp['arr_1'][0:self.nSteps] self.modulation = [np.ones(self.nSteps), \\",
"forwU) A[1,0] = A[0,1] A[0,2] = np.sum(forwQ * forwV) A[2,0] = A[0,2] A[1,2]",
"np.copy(x) y = np.copy(x) res = self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue = splinalg.eigsh(res, k=1, which='LM', return_eigenvectors=False)",
"betaV), normL2, normL1, normL0 def demodulateTrivial(self): forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU",
"betaI * self.backward(residual1, 0) - 2.0 * Q0 * betaQ * self.backward(residual1, 1)",
"* U0 * betaU * self.backward(residual1, 2) - 2.0 * V0 * betaV",
"\"\"\" Return the FFT of a real signal taking into account some normalization",
"import numpy as np import matplotlib.pyplot as pl import scipy.sparse as sp import",
"< 0): I0 = 1.0 if (np.abs(Q0) > 1.0): Q0 = 1e-3 if",
"0) + 2.0 * Q0 * betaQ * self.backward(residual2, 1) + \\ 2.0",
"||y - M*F^{-1}*alpha||_2 + \\lambda ||alpha||_1 Args: rank (int, optional): rank of the",
"self.sparseMStar = [None] * 4 for state in range(4): sparseData = [] sparseRow",
"= np.sum(forwV**2) A[0,1] = np.sum(forwQ * forwU) A[1,0] = A[0,1] A[0,2] = np.sum(forwQ",
"pl.close('all') # f, ax = pl.subplots(nrows=1, ncols=4, figsize=(18,6)) # coefFourier[0] = 0.0 #",
"* M2N) b[1] = 0.5 * U0 * np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\",
"self.nSteps = int(totalTime / dt) self.times = np.arange(self.nSteps) * self.dt # Frequency axis",
"unit variance and multiply by the square root of the power spectrum #",
"square root of the power spectrum # to generate the noise with the",
"(I0 < 0): I0 = 1.0 if (np.abs(Q0) > 1.0): Q0 = 1e-3",
"2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType == 0): self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps) else: temp",
"I0 * np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1])) - \\ I0**2 * np.sum(M1One * M1N)) /",
"normSolutionL1 = np.linalg.norm(x, 1) normSolutionL0 = np.linalg.norm(x, 0) if (loop % 10): #",
"numpy as np import matplotlib.pyplot as pl import scipy.sparse as sp import scipy.sparse.linalg",
"return f[0]**2 + 2.0*np.sum(f[1:]**2) class randomDemodulator(object): \"\"\"Summary Returns ------- TYPE : Demodulate I",
"using a lambda/4 and lambda/2 polarimeter with random angles # self.modulation = [np.ones(self.nSteps),",
"* np.real(gradient), lambdaValue) xNew[0] = 0.0 xNew /= np.sqrt(myTotalPower(xNew)) if (thresholdMethod == 'L2'):",
"V/I_trivial={2} - diff={3}\".format(out.stokes[3] / out.stokes[0], stokes[3] / stokes[0], \\ # stV/stI, out.stokes[3] /",
"solves the following problem: argmin_O ||y - M*F^{-1}*alpha||_2 + \\lambda ||alpha||_1 Args: rank",
"Generate Gaussian noise with unit variance and multiply by the square root of",
"operation='sum'): \"\"\" Bins an ndarray in all axes based on the target shape,",
"* N(t) M4N = self.forwardPartial(signal, 3) # M4(t) * N(t) M1One = self.forwardPartial(np.ones(self.nSteps),",
"len(z) def softThreshold(self, x, lambdaValue): return np.fmax(0,1.0 - lambdaValue / np.fmax(np.abs(x),1e-10)) * x",
"- self.mu * np.real(gradient), lambdaValue) xNew[0] = 0.0 xNew /= np.sqrt(myTotalPower(xNew)) if (thresholdMethod",
"forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 = 0.5 *",
"[] normL0 = [] for loop in range(niter): signal = myIFFT(x) forwI =",
"tNew * (xNew - x) t = tNew x = np.copy(xNew) normResidual =",
"Q0 * U0 * np.sum(M3N * M2N) A[1,0] = A[0,1] A[0,2] = Q0",
"in range(4): self.signal[i] = self.stokes[i]*(1.0 + self.beta[i] * self.seeing) # Generate modulation using",
"198 206 214] [262 270 278 286 294] [342 350 358 366 374]]",
"self.nSamples = int(self.dt / self.dtIntegration * self.nSteps) self.signalIntegrated = [None] * 2 for",
"dtIntegration self.seed = seed self.signalToNoise = signalToNoise self.modulationType = modulationType if (self.seed !=",
"'mean', 'average', 'avg']: raise ValueError(\"Operation {} not supported.\".format(operation)) if ndarray.ndim != len(new_shape): raise",
"residual1 = self.signalIntegrated[0] - (I0 * forwI + Q0 * forwQ + U0",
"* forwU) A[1,0] = A[0,1] A[0,2] = np.sum(forwQ * forwV) A[2,0] = A[0,2]",
"= self.forwardPartial(signal, 1) # M2(t) * N(t) M3N = self.forwardPartial(signal, 2) # M3(t)",
"self.signalToNoise * np.random.randn(self.nSamples) self.tIntegrated = np.arange(self.nSamples) * self.dtIntegration # Generate modulation matrix self.sparseM",
"out.signal[0]) # ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1] / stokes[0] *(1.0+beta[1]*Nt)) #",
"* 1(t) M3One = self.forwardPartial(np.ones(self.nSteps), 2) # M3(t) * 1(t) M4One = self.forwardPartial(np.ones(self.nSteps),",
"noiseFFT = myFFT(noise) self.powerSeeing = np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0] = 0.0 self.seeingFFT =",
"[\"mean\", \"average\", \"avg\"]: ndarray = ndarray.mean(-1*(i+1)) return ndarray def myFFT(x): \"\"\" Return the",
"(np.abs(Q0) > 1.0): Q0 = 1e-3 if (np.abs(U0) > 1.0): U0 = 1e-3",
"[np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType == 0): self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation =",
"out = fft.irfft(x) return out * np.sqrt(len(out)) def myTotalPower(f): \"\"\" Return the power",
"out.stokes[0]-stokes[3] / stokes[0]) # pl.close('all') # f, ax = pl.subplots(nrows=1, ncols=4, figsize=(18,6)) #",
"self.beta = beta self.stokes = stokes # Generate Gaussian noise with unit variance",
"stV = out.demodulateTrivial() # print \"Q/I_original={0} - Q/I_inferred={1} - Q/I_trivial={2} - diff={3}\".format(out.stokes[1] /",
"M3One = self.forwardPartial(np.ones(self.nSteps), 2) # M3(t) * 1(t) M4One = self.forwardPartial(np.ones(self.nSteps), 3) #",
"self.signal[0] * self.modulation[0] sign = (-1.0)**i for j in range(1,4): temp += sign",
"out.stokes[0], stokes[3] / stokes[0], \\ # stV/stI, out.stokes[3] / out.stokes[0]-stokes[3] / stokes[0]) #",
"np.sqrt(myTotalPower(xNew)) if (thresholdMethod == 'L2'): xNew = y - self.mu * np.real(gradient) tNew",
"0.0 self.seeingFFT = np.sqrt(self.powerSeeing) * noiseFFT self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing = myIFFT(self.seeingFFT) #",
"# M1(t) * (1+betaI*N(t)) forwQ = self.forward(signal, betaQ, 1) # M2(t) * (1+betaQ*N(t))",
"'Total variance = ', np.sum(self.seeing**2), myTotalPower(self.seeingFFT) # Compute the signal and its power",
"* (1+betaV*N(t)) residual1 = self.signalIntegrated[0] - (I0 * forwI + Q0 * forwQ",
"np.real(gradient), lambdaValue) if (thresholdMethod == 'hardPercentage'): xNew = self.hardThreshold(y - self.mu * np.real(gradient),",
"= [] sparseCol = [] loop = 0 for i in range(self.nSamples): for",
"= self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 =",
"np.sum(M3One * M3N) - U0 * V0 * np.sum(M4One * M3N) b[2] =",
"y = xNew + (t-1.0) / tNew * (xNew - x) t =",
"'U', 'V'] # loop = 0 # for loop in range(4): # ax[loop].plot(out.times,",
"and its power spectrum self.signal = [None] * 4 for i in range(4):",
"= np.zeros(3) b[0] = 0.5 * Q0 * np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\",
"ax[loop].annotate # pl.tight_layout() # ax[0,0].plot(out.times, out.signal[0]) # ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1]) #",
"forwI - Q0 * forwQ - U0 * forwU - V0 * forwV)",
"------- float : Fourier coefficients of the real signal \"\"\" out = fft.rfft(x)",
"= [] normL2 = [] normL0 = [] for loop in range(niter): signal",
"power spectrum self.powerLites = np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] = 10.0**self.powerLites[:,1] # Number of samples of",
"'L2'): xNew = y - self.mu * np.real(gradient) tNew = 0.5*(1+np.sqrt(1+4.0*t**2)) y =",
"signal, ray): return self.sparseM[ray].dot(signal) def backward(self, z, ray): return self.factor * myFFT(self.sparseMStar[ray].dot(z)) def",
"M2N) - Q0 * V0 * np.sum(M4One * M2N) b[1] = 0.5 *",
"* U0 * np.sum(M3One * M4N) - V0**2 * np.sum(M4One * M4N) betaI",
"ax[0,1].plot(stokes[1] / stokes[0] *(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2] / stokes[0] * (1.0+beta[2]*Nt)) #",
"total power is unity print 'Total variance = ', np.sum(self.seeing**2), myTotalPower(self.seeingFFT) # Compute",
"np.fmax(0,1.0 - lambdaValue / np.fmax(np.abs(x),1e-10)) * x def hardThreshold(self, x, lambdaValue): xPar =",
"= gradient1 + gradient2 if (thresholdMethod == 'hardLambda'): xNew = self.hardThreshold(y - self.mu",
"pl.tight_layout() # ax[0,0].plot(out.times, out.signal[0]) # ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1] /",
"with the appropriate power spectrum noise = np.random.randn(self.nSteps) noiseFFT = myFFT(noise) self.powerSeeing =",
"1) # M2(t) * (1+betaQ*N(t)) forwU = self.forward(signal, betaU, 2) # M3(t) *",
"self.backward(residual1, 3) residual2 = self.signalIntegrated[1] - (I0 * forwI - Q0 * forwQ",
"* (1.0 + beta[loop]*Nt)) # ax[loop].set_xlabel('Time [s]') # ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) # ax[loop].annotate #",
"ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1] / stokes[0] *(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2]) #",
"---------- totalTime : TYPE Description dt : TYPE Description dtIntegration : TYPE Description",
"Return the FFT of a real signal taking into account some normalization Parameters",
"matrix self.sparseM = [None] * 4 self.sparseMStar = [None] * 4 for state",
"the appropriate power spectrum noise = np.random.randn(self.nSteps) noiseFFT = myFFT(noise) self.powerSeeing = np.interp(np.abs(self.freq),",
"betaQ, betaU, betaV = np.abs(np.linalg.solve(A,b)) if (loop % 50 == 0): print \"It",
"* M2N) - Q0 * V0 * np.sum(M4One * M2N) b[1] = 0.5",
"# totalTime = 1.0 # s # dt = 0.001 # s #",
"Parameters ---------- totalTime : TYPE Description dt : TYPE Description dtIntegration : TYPE",
"xNew = y - self.mu * np.real(gradient) tNew = 0.5*(1+np.sqrt(1+4.0*t**2)) y = xNew",
"(1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3] / stokes[0] * (1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt)))",
"* (1+betaQ*N(t)) forwU = self.forward(signal, betaU, 2) # M3(t) * (1+betaU*N(t)) forwV =",
"dtIntegration, stokes, beta, signalToNoise=0.0, seed=0, modulationType=0): \"\"\"Summary Parameters ---------- totalTime : TYPE Description",
"a lambda/4 and lambda/2 polarimeter with random angles # self.modulation = [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0,",
"= 0.0 xNew /= np.sqrt(myTotalPower(xNew)) if (thresholdMethod == 'L2'): xNew = y -",
"* M2N) A[1,0] = A[0,1] A[0,2] = Q0 * V0 * np.sum(M4N *",
"by summing or averaging. Number of output dimensions must match number of input",
"[s]') # ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) # ax[loop].annotate # pl.tight_layout() # ax[0,0].plot(out.times, out.signal[0]) # ax[0,0].plot(out.times,",
"U0 * betaU * self.backward(residual1, 2) - 2.0 * V0 * betaV *",
"1.0 # s # dt = 0.001 # s # dtIntegration = 0.01",
"print \"Q/I_original={0} - Q/I_inferred={1} - Q/I_trivial={2} - diff={3}\".format(out.stokes[1] / out.stokes[0], stokes[1] / stokes[0],",
"np.arange(self.nSteps) * self.dt # Frequency axis self.freq = fft.rfftfreq(self.nSteps, d=dt) # Betas and",
"normalization Parameters ---------- x : float Fourier coefficients Returns ------- float : signal",
"\"\"\" Bins an ndarray in all axes based on the target shape, by",
"[] for loop in range(niter): signal = myIFFT(x) forwI = self.forward(signal, betaI, 0)",
"f[0]**2 + 2.0*np.sum(f[1:]**2) class randomDemodulator(object): \"\"\"Summary Returns ------- TYPE : Demodulate I and",
"A[0,1] = np.sum(forwQ * forwU) A[1,0] = A[0,1] A[0,2] = np.sum(forwQ * forwV)",
"= np.arange(0,100,1).reshape((10,10)) >>> n = bin_ndarray(m, new_shape=(5,5), operation='sum') >>> print(n) [[ 22 30",
"of a real signal taking into account some normalization Parameters ---------- x :",
"self.backward(residual2, 0) + 2.0 * Q0 * betaQ * self.backward(residual2, 1) + \\",
"+= 1 self.sparseM[state] = sp.coo_matrix((sparseData, (sparseRow, sparseCol)), shape=(self.nSamples, self.nSteps)) self.sparseMStar[state] = self.sparseM[state].transpose(copy=True) self.factor",
"np.copy(initial) I0, Q0, U0, V0 = initialStokes xNew = np.copy(x) y = np.copy(x)",
"= self.forwardPartial(np.ones(self.nSteps), 3) # M4(t) * 1(t) A = np.zeros((3,3)) A[0,0] = Q0**2",
"A[0,1] A[0,2] = np.sum(forwQ * forwV) A[2,0] = A[0,2] A[1,2] = np.sum(forwU *",
"= U0 * V0 * np.sum(M4N * M3N) A[2,1] = A[1,2] b =",
"np.zeros((3,3)) A[0,0] = np.sum(forwQ**2) A[1,1] = np.sum(forwU**2) A[2,2] = np.sum(forwV**2) A[0,1] = np.sum(forwQ",
"root of the power spectrum # to generate the noise with the appropriate",
"\"\"\" out = fft.irfft(x) return out * np.sqrt(len(out)) def myTotalPower(f): \"\"\" Return the",
"A[0,0] = np.sum(forwQ**2) A[1,1] = np.sum(forwU**2) A[2,2] = np.sum(forwV**2) A[0,1] = np.sum(forwQ *",
"V0 = 0.3 betaI = 10.0#self.beta[0] betaQ = 10.0#self.beta[1] betaU = 10.0#self.beta[2] betaV",
"as np import matplotlib.pyplot as pl import scipy.sparse as sp import scipy.sparse.linalg as",
">>> m = np.arange(0,100,1).reshape((10,10)) >>> n = bin_ndarray(m, new_shape=(5,5), operation='sum') >>> print(n) [[",
"= stokes # Generate Gaussian noise with unit variance and multiply by the",
"return self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self, signal, ray): return self.sparseM[ray].dot(signal) def backward(self, z, ray): return",
"+ V0 * forwV) gradient1 = -2.0 * I0 * betaI * self.backward(residual1,",
"beta, seed=123, signalToNoise=1e3) # coefFourier, stokes, beta, normL21, normL11 = out.FISTA(thresholdMethod = 'soft',",
"= 10.0#self.beta[2] betaV = 10.0#self.beta[3] else: x = np.copy(initial) I0, Q0, U0, V0",
"return x, (I0, Q0, U0, V0), (betaI, betaQ, betaU, betaV), normL2, normL1, normL0",
"{0:4d} - l2={1:10.3e} - l1={2:10.4f} - l0={3:5.1f}% - I={4:11.5f} - Q/I={5:11.5f} - U/I={6:11.5f}",
"\"\"\" if (initial == None): x = np.zeros(self.nSteps) I0 = 0.9 Q0 =",
"TYPE Description dtIntegration : TYPE Description seed : int, optional Description Returns -------",
"self.sparseM = [None] * 4 self.sparseMStar = [None] * 4 for state in",
"self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps) else: temp = np.load('alphaBetaSamples.npz') self.alphaModulation = temp['arr_0'][0:self.nSteps] self.betaModulation = temp['arr_1'][0:self.nSteps]",
"betaQ * self.backward(residual2, 1) + \\ 2.0 * U0 * betaU * self.backward(residual2,",
"U0 * V0 * np.sum(M4One * M3N) b[2] = 0.5 * V0 *",
"= A[0,2] A[1,2] = np.sum(forwU * forwV) A[2,1] = A[1,2] b = np.zeros(3)",
"U0 * np.sum(M3One * M4N) - V0**2 * np.sum(M4One * M4N) betaI =",
"* z[1:].conj())).real / len(z) def softThreshold(self, x, lambdaValue): return np.fmax(0,1.0 - lambdaValue /",
"!= len(new_shape): raise ValueError(\"Shape mismatch: {} -> {}\".format(ndarray.shape, new_shape)) compression_pairs = [(d, c//d)",
"0.2 V0 = 0.3 betaI = 10.0#self.beta[0] betaQ = 10.0#self.beta[1] betaU = 10.0#self.beta[2]",
"2 for i in range(2): temp = self.signal[0] * self.modulation[0] sign = (-1.0)**i",
"A[1,0] = A[0,1] A[0,2] = np.sum(forwQ * forwV) A[2,0] = A[0,2] A[1,2] =",
"V/I={7:11.5f} - bI={8:11.5f} - bQ={9:11.5f} - bU={10:11.5f} - bV={11:11.5f}\".format(loop, normResidual, normSolutionL1, 100.0*normSolutionL0 /",
"np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime = self.dtIntegration self.lengthSample = int(self.dtIntegration / self.dt) self.nSamples",
"== 'L2'): xNew = y - self.mu * np.real(gradient) tNew = 0.5*(1+np.sqrt(1+4.0*t**2)) y",
"ndarray in all axes based on the target shape, by summing or averaging.",
"int(self.dtIntegration / self.dt) self.nSamples = int(self.dt / self.dtIntegration * self.nSteps) self.signalIntegrated = [None]",
"(betaI, betaQ, betaU, betaV), normL2, normL1, normL0 def demodulateTrivial(self): forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ",
"pl import scipy.sparse as sp import scipy.sparse.linalg as splinalg import scipy.fftpack as fft",
"/ stokes[0], \\ # stV/stI, out.stokes[3] / out.stokes[0]-stokes[3] / stokes[0]) # pl.close('all') #",
"range(len(new_shape)): if operation.lower() == \"sum\": ndarray = ndarray.sum(-1*(i+1)) elif operation.lower() in [\"mean\", \"average\",",
"normL1, normL0 def demodulateTrivial(self): forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0)",
"__init__(self, totalTime, dt, dtIntegration, stokes, beta, signalToNoise=0.0, seed=0, modulationType=0): \"\"\"Summary Parameters ---------- totalTime",
"stokes, beta, signalToNoise=0.0, seed=0, modulationType=0): \"\"\"Summary Parameters ---------- totalTime : TYPE Description dt",
"- V0 * U0 * np.sum(M3One * M4N) - V0**2 * np.sum(M4One *",
"U0, V0 = np.linalg.solve(A,b) return I0, Q0, U0, V0 # totalTime = 1.0",
"# beta = np.asarray([15.0, 100.0, 100., 100.0]) # stokes = np.asarray([1.0, 1.2e-3, 5.e-3,",
"problem: argmin_O ||y - M*F^{-1}*alpha||_2 + \\lambda ||alpha||_1 Args: rank (int, optional): rank",
"# Seeing amplitude M1N = self.forwardPartial(signal, 0) # M1(t) * N(t) M2N =",
"gradient2 if (thresholdMethod == 'hardLambda'): xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue)",
"np.random.randn(self.nSamples) self.tIntegrated = np.arange(self.nSamples) * self.dtIntegration # Generate modulation matrix self.sparseM = [None]",
"= 0.0 # Nt = myIFFT(coefFourier) # Nt /= np.sqrt(myTotalPower(coefFourier)) # stokesPar =",
"new_shape)) compression_pairs = [(d, c//d) for d, c in zip(new_shape, ndarray.shape)] flattened =",
"gradient = gradient1 + gradient2 if (thresholdMethod == 'hardLambda'): xNew = self.hardThreshold(y -",
"30 38 46 54] [102 110 118 126 134] [182 190 198 206",
"Make sure that the total power is unity print 'Total variance = ',",
"Return the IFFT for a real signal taking into account some normalization Parameters",
"out.stokes[2] / out.stokes[0]-stokes[2] / stokes[0]) # print \"V/I_original={0} - V/I_inferred={1} - V/I_trivial={2} -",
"stokes[0]) # pl.close('all') # f, ax = pl.subplots(nrows=1, ncols=4, figsize=(18,6)) # coefFourier[0] =",
"normResidual = np.linalg.norm(residual1 + residual2) normSolutionL1 = np.linalg.norm(x, 1) normSolutionL0 = np.linalg.norm(x, 0)",
"ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21) # ax[2,1].semilogy(normL11) # ax[3,0].plot(out.signalIntegrated[0]) # ax[3,0].plot(out.signalIntegrated[1]) # ax[3,1].plot(out.seeing)",
"betaV, 3) # M4(t) * (1+betaV*N(t)) residual1 = self.signalIntegrated[0] - (I0 * forwI",
"beta, signalToNoise=0.0, seed=0, modulationType=0): \"\"\"Summary Parameters ---------- totalTime : TYPE Description dt :",
"Example ------- >>> m = np.arange(0,100,1).reshape((10,10)) >>> n = bin_ndarray(m, new_shape=(5,5), operation='sum') >>>",
"* self.modulation[0] sign = (-1.0)**i for j in range(1,4): temp += sign *",
"U0 = 0.2 V0 = 0.3 betaI = 10.0#self.beta[0] betaQ = 10.0#self.beta[1] betaU",
"2) # M3(t) * N(t) M4N = self.forwardPartial(signal, 3) # M4(t) * N(t)",
"0.5 * U0 * np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ U0 * Q0 *",
"normalization Parameters ---------- x : float Signal time series Returns ------- float :",
"+= sign * self.signal[j] * self.modulation[j] self.signalIntegrated[i] = bin_ndarray(temp, (self.nSamples,), operation='sum') self.signalIntegrated[i] +=",
"* np.sum(M2One * M2N) - Q0 * U0 * np.sum(M3One * M2N) -",
"= 10.0**self.powerLites[:,1] # Number of samples of the original sample self.nSteps = int(totalTime",
"in zip(new_shape, ndarray.shape)] flattened = [l for p in compression_pairs for l in",
"5.e-3, 0.001]) # out = randomDemodulator(totalTime, dt, dtIntegration, stokes, beta, seed=123, signalToNoise=1e3) #",
"= beta self.stokes = stokes # Generate Gaussian noise with unit variance and",
"* self.modulation[j] self.signalIntegrated[i] = bin_ndarray(temp, (self.nSamples,), operation='sum') self.signalIntegrated[i] += np.mean(self.signalIntegrated[i]) / self.signalToNoise *",
": TYPE Description dt : TYPE Description dtIntegration : TYPE Description seed :",
"* np.sum(M3One * M4N) - V0**2 * np.sum(M4One * M4N) betaI = np.abs((0.5",
"compression_pairs for l in p] ndarray = ndarray.reshape(flattened) for i in range(len(new_shape)): if",
"= 0 for i in range(self.nSamples): for j in range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop)",
"I0, Q0/I0, U0/I0, V0/I0, betaI, betaQ, betaU, betaV) normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0) return x,",
"ax[loop].set_xlabel('Time [s]') # ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) # ax[loop].annotate # pl.tight_layout() # ax[0,0].plot(out.times, out.signal[0]) #",
"in [\"mean\", \"average\", \"avg\"]: ndarray = ndarray.mean(-1*(i+1)) return ndarray def myFFT(x): \"\"\" Return",
"* Q0 * betaQ * self.backward(residual2, 1) + \\ 2.0 * U0 *",
"3) gradient = gradient1 + gradient2 if (thresholdMethod == 'hardLambda'): xNew = self.hardThreshold(y",
"0.5 * np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] = 0.5 * np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2]",
"M1(t) * (1+betaI*N(t)) forwQ = self.forward(signal, betaQ, 1) # M2(t) * (1+betaQ*N(t)) forwU",
"xNew = np.copy(x) y = np.copy(x) res = self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue = splinalg.eigsh(res, k=1,",
"stQ, stU, stV = out.demodulateTrivial() # print \"Q/I_original={0} - Q/I_inferred={1} - Q/I_trivial={2} -",
"\"avg\"]: ndarray = ndarray.mean(-1*(i+1)) return ndarray def myFFT(x): \"\"\" Return the FFT of",
"# ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1] / stokes[0] *(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2])",
": Fourier coefficients of the real signal \"\"\" out = fft.rfft(x) return out",
"# M2(t) * (1+betaQ*N(t)) forwU = self.forward(signal, betaU, 2) # M3(t) * (1+betaU*N(t))",
"U0 * V0 * np.sum(M4N * M3N) A[2,1] = A[1,2] b = np.zeros(3)",
"modulation matrix self.sparseM = [None] * 4 self.sparseMStar = [None] * 4 for",
"- self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'hardPercentage'): xNew = self.hardThreshold(y -",
"operation.lower() == \"sum\": ndarray = ndarray.sum(-1*(i+1)) elif operation.lower() in [\"mean\", \"average\", \"avg\"]: ndarray",
"the FFT of a real signal taking into account some normalization Parameters ----------",
"\"\"\" Return the IFFT for a real signal taking into account some normalization",
"M3N) b[2] = 0.5 * V0 * np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ V0",
"0): self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps) else: temp = np.load('alphaBetaSamples.npz') self.alphaModulation =",
"hardThreshold(self, x, lambdaValue): xPar = np.copy(x) xPar[np.abs(x) < lambdaValue] = 0.0 return xPar",
"xPar = np.copy(x) xPar[np.abs(x) < lambdaValue] = 0.0 return xPar def FISTA(self, initial=None,",
"self.backward(residual1, 0) - 2.0 * Q0 * betaQ * self.backward(residual1, 1) - \\",
"if (np.abs(Q0) > 1.0): Q0 = 1e-3 if (np.abs(U0) > 1.0): U0 =",
"number of input dimensions. Example ------- >>> m = np.arange(0,100,1).reshape((10,10)) >>> n =",
"A[0,2] = Q0 * V0 * np.sum(M4N * M2N) A[2,0] = A[0,2] A[1,2]",
"* betaV * self.backward(residual1, 3) residual2 = self.signalIntegrated[1] - (I0 * forwI -",
"U/I_trivial={2} - diff={3}\".format(out.stokes[2] / out.stokes[0], stokes[2] / stokes[0], \\ # stU/stI, out.stokes[2] /",
"I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A = np.zeros((3,3)) A[0,0]",
"= A[0,1] A[0,2] = np.sum(forwQ * forwV) A[2,0] = A[0,2] A[1,2] = np.sum(forwU",
"100.0]) # stokes = np.asarray([1.0, 1.2e-3, 5.e-3, 0.001]) # out = randomDemodulator(totalTime, dt,",
"stokes[0] *(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2] / stokes[0] * (1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3]) #",
"y - self.mu * np.real(gradient) tNew = 0.5*(1+np.sqrt(1+4.0*t**2)) y = xNew + (t-1.0)",
"betaU, betaV), normL2, normL1, normL0 def demodulateTrivial(self): forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0)",
"A[1,2] = np.sum(forwU * forwV) A[2,1] = A[1,2] b = np.zeros(3) b[0] =",
"spectrum self.signal = [None] * 4 for i in range(4): self.signal[i] = self.stokes[i]*(1.0",
"of iterations Returns: TYPE: Description \"\"\" if (initial == None): x = np.zeros(self.nSteps)",
"def myFFT(x): \"\"\" Return the FFT of a real signal taking into account",
"self.backward(residual1, 1) - \\ 2.0 * U0 * betaU * self.backward(residual1, 2) -",
"tNew = 0.5*(1+np.sqrt(1+4.0*t**2)) y = xNew + (t-1.0) / tNew * (xNew -",
"def myTotalPower(f): \"\"\" Return the power spectrum of a signal Parameters ---------- f",
"+ U0 * forwU + V0 * forwV) gradient1 = -2.0 * I0",
"# Generate modulation using a lambda/4 and lambda/2 polarimeter with random angles #",
"/ np.sum(forwI**2) A = np.zeros((3,3)) A[0,0] = np.sum(forwQ**2) A[1,1] = np.sum(forwU**2) A[2,2] =",
"M4N) - V0 * U0 * np.sum(M3One * M4N) - V0**2 * np.sum(M4One",
"= self.forward(signal, betaU, 2) # M3(t) * (1+betaU*N(t)) forwV = self.forward(signal, betaV, 3)",
"np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime = self.dtIntegration self.lengthSample = int(self.dtIntegration / self.dt) self.nSamples = int(self.dt /",
"def totalPower(self, z): return (z[0] * z[0].conj() + 2 * np.sum(z[1:] * z[1:].conj())).real",
"- \\ V0 * Q0 * np.sum(M2One * M4N) - V0 * U0",
"* np.sum(M4N * M2N) A[2,0] = A[0,2] A[1,2] = U0 * V0 *",
"self.forwardPartial(np.ones(self.nSteps), 0) # M1(t) * 1(t) M2One = self.forwardPartial(np.ones(self.nSteps), 1) # M2(t) *",
"of a signal Parameters ---------- f : float Signal Fourier coefficients Returns -------",
"= ndarray.reshape(flattened) for i in range(len(new_shape)): if operation.lower() == \"sum\": ndarray = ndarray.sum(-1*(i+1))",
"2.0 * V0 * betaV * self.backward(residual1, 3) residual2 = self.signalIntegrated[1] - (I0",
"M4N = self.forwardPartial(signal, 3) # M4(t) * N(t) M1One = self.forwardPartial(np.ones(self.nSteps), 0) #",
"= self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'soft'): xNew =",
"||alpha||_1 Args: rank (int, optional): rank of the solution niter (int, optional): number",
"* I0 * betaI * self.backward(residual1, 0) - 2.0 * Q0 * betaQ",
"Demodulate I and Q signals together \"\"\" def __init__(self, totalTime, dt, dtIntegration, stokes,",
"def forward(self, signal, beta, ray): return self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self, signal, ray): return self.sparseM[ray].dot(signal)",
"softThreshold(self, x, lambdaValue): return np.fmax(0,1.0 - lambdaValue / np.fmax(np.abs(x),1e-10)) * x def hardThreshold(self,",
"of the original sample self.nSteps = int(totalTime / dt) self.times = np.arange(self.nSteps) *",
"temp['arr_0'][0:self.nSteps] self.betaModulation = temp['arr_1'][0:self.nSteps] self.modulation = [np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) *",
"j in range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop) loop += 1 self.sparseM[state] = sp.coo_matrix((sparseData, (sparseRow,",
"/ out.stokes[0], stokes[1] / stokes[0], \\ # stQ/stI, out.stokes[1] / out.stokes[0]-stokes[1] / stokes[0])",
"np.linalg.norm(x, 1) normSolutionL0 = np.linalg.norm(x, 0) if (loop % 10): # Stokes parameters",
"[] normL2 = [] normL0 = [] for loop in range(niter): signal =",
"p in compression_pairs for l in p] ndarray = ndarray.reshape(flattened) for i in",
"spectrum # to generate the noise with the appropriate power spectrum noise =",
"* np.sum(M2One * M4N) - V0 * U0 * np.sum(M3One * M4N) -",
"A[0,1] = Q0 * U0 * np.sum(M3N * M2N) A[1,0] = A[0,1] A[0,2]",
"out.FISTA(thresholdMethod = 'soft', niter = 600, lambdaValue = 0.000000051) # stI, stQ, stU,",
"in range(len(new_shape)): if operation.lower() == \"sum\": ndarray = ndarray.sum(-1*(i+1)) elif operation.lower() in [\"mean\",",
"Signal Fourier coefficients Returns ------- float : total power \"\"\" return f[0]**2 +",
"M4(t) * N(t) M1One = self.forwardPartial(np.ones(self.nSteps), 0) # M1(t) * 1(t) M2One =",
"if (thresholdMethod == 'soft'): xNew = self.softThreshold(y - self.mu * np.real(gradient), lambdaValue) xNew[0]",
"* np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1])) - \\ I0**2 * np.sum(M1One * M1N)) / (I0**2",
"* np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) return I0, Q0, U0,",
"* (1+betaU*N(t)) forwV = self.forward(signal, betaV, 3) # M4(t) * (1+betaV*N(t)) residual1 =",
"= U0**2 * np.sum(M3N**2) A[2,2] = V0**2 * np.sum(M4N**2) A[0,1] = Q0 *",
"of samples of the original sample self.nSteps = int(totalTime / dt) self.times =",
"self.forwardPartial(signal, 0) # M1(t) * N(t) M2N = self.forwardPartial(signal, 1) # M2(t) *",
"= 0.5 * Q0 * np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ Q0**2 * np.sum(M2One",
"- U/I_inferred={1} - U/I_trivial={2} - diff={3}\".format(out.stokes[2] / out.stokes[0], stokes[2] / stokes[0], \\ #",
"0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps) else: temp = np.load('alphaBetaSamples.npz') self.alphaModulation = temp['arr_0'][0:self.nSteps] self.betaModulation =",
"V0 * betaV * self.backward(residual2, 3) gradient = gradient1 + gradient2 if (thresholdMethod",
"= ['I', 'Q', 'U', 'V'] # loop = 0 # for loop in",
"= 0.5 / (np.real(largestEigenvalue)) * 0.0002 t = 1.0 normL1 = [] normL2",
"if (thresholdMethod == 'L2'): xNew = y - self.mu * np.real(gradient) tNew =",
"xPar[np.abs(x) < lambdaValue] = 0.0 return xPar def FISTA(self, initial=None, initialStokes=None, thresholdMethod='soft', niter=10,",
"U0 * np.sum(M3One * M2N) - Q0 * V0 * np.sum(M4One * M2N)",
"38 46 54] [102 110 118 126 134] [182 190 198 206 214]",
"(1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21) # ax[2,1].semilogy(normL11) # ax[3,0].plot(out.signalIntegrated[0]) # ax[3,0].plot(out.signalIntegrated[1])",
"raise ValueError(\"Operation {} not supported.\".format(operation)) if ndarray.ndim != len(new_shape): raise ValueError(\"Shape mismatch: {}",
"2 * np.sum(z[1:] * z[1:].conj())).real / len(z) def softThreshold(self, x, lambdaValue): return np.fmax(0,1.0",
"seed=0, modulationType=0): \"\"\"Summary Parameters ---------- totalTime : TYPE Description dt : TYPE Description",
"f : float Signal Fourier coefficients Returns ------- float : total power \"\"\"",
"\"\"\" Return the power spectrum of a signal Parameters ---------- f : float",
"xNew + (t-1.0) / tNew * (xNew - x) t = tNew x",
"print \"It {0:4d} - l2={1:10.3e} - l1={2:10.4f} - l0={3:5.1f}% - I={4:11.5f} - Q/I={5:11.5f}",
"/ stokes[0]) # pl.close('all') # f, ax = pl.subplots(nrows=1, ncols=4, figsize=(18,6)) # coefFourier[0]",
"A[1,2] = U0 * V0 * np.sum(M4N * M3N) A[2,1] = A[1,2] b",
"'soft'): xNew = self.softThreshold(y - self.mu * np.real(gradient), lambdaValue) xNew[0] = 0.0 xNew",
"dtIntegration : TYPE Description seed : int, optional Description Returns ------- TYPE :",
"optional): number of iterations Returns: TYPE: Description \"\"\" if (initial == None): x",
"(-1.0)**i for j in range(1,4): temp += sign * self.signal[j] * self.modulation[j] self.signalIntegrated[i]",
"self.signal = [None] * 4 for i in range(4): self.signal[i] = self.stokes[i]*(1.0 +",
"'hardPercentage'): xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'soft'):",
"return I0, Q0, U0, V0 # totalTime = 1.0 # s # dt",
"/ out.stokes[0]-stokes[3] / stokes[0]) # pl.close('all') # f, ax = pl.subplots(nrows=1, ncols=4, figsize=(18,6))",
"# stQ/stI, out.stokes[1] / out.stokes[0]-stokes[1] / stokes[0]) # print \"U/I_original={0} - U/I_inferred={1} -",
"self.modulation[j] self.signalIntegrated[i] = bin_ndarray(temp, (self.nSamples,), operation='sum') self.signalIntegrated[i] += np.mean(self.signalIntegrated[i]) / self.signalToNoise * np.random.randn(self.nSamples)",
"self.stokes[i]*(1.0 + self.beta[i] * self.seeing) # Generate modulation using a lambda/4 and lambda/2",
"Q0 * V0 * np.sum(M4One * M2N) b[1] = 0.5 * U0 *",
"def bin_ndarray(ndarray, new_shape, operation='sum'): \"\"\" Bins an ndarray in all axes based on",
"* np.sum(M4N**2) A[0,1] = Q0 * U0 * np.sum(M3N * M2N) A[1,0] =",
"= self.signal[0] * self.modulation[0] sign = (-1.0)**i for j in range(1,4): temp +=",
"if (thresholdMethod == 'hardLambda'): xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if",
"account some normalization Parameters ---------- x : float Fourier coefficients Returns ------- float",
"'V'] # loop = 0 # for loop in range(4): # ax[loop].plot(out.times, out.signal[loop])",
"'soft', niter = 600, lambdaValue = 0.000000051) # stI, stQ, stU, stV =",
"# dtIntegration = 0.01 #s # beta = np.asarray([15.0, 100.0, 100., 100.0]) #",
"Description \"\"\" self.totalTime = totalTime self.dt = dt self.dtIntegration = dtIntegration self.seed =",
"# M4(t) * (1+betaV*N(t)) residual1 = self.signalIntegrated[0] - (I0 * forwI + Q0",
"on the target shape, by summing or averaging. Number of output dimensions must",
"forwQ = self.forward(signal, betaQ, 1) # M2(t) * (1+betaQ*N(t)) forwU = self.forward(signal, betaU,",
"M2N) b[1] = 0.5 * U0 * np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ U0",
"1) + \\ 2.0 * U0 * betaU * self.backward(residual2, 2) + 2.0",
"shape=(self.nSamples, self.nSteps)) self.sparseMStar[state] = self.sparseM[state].transpose(copy=True) self.factor = 2*np.ones(self.nSteps) self.factor[0] = 1.0 def forward(self,",
"out.stokes[3] / out.stokes[0]-stokes[3] / stokes[0]) # pl.close('all') # f, ax = pl.subplots(nrows=1, ncols=4,",
"some normalization Parameters ---------- x : float Signal time series Returns ------- float",
"betaI = 10.0#self.beta[0] betaQ = 10.0#self.beta[1] betaU = 10.0#self.beta[2] betaV = 10.0#self.beta[3] else:",
"(1+betaU*N(t)) forwV = self.forward(signal, betaV, 3) # M4(t) * (1+betaV*N(t)) residual1 = self.signalIntegrated[0]",
"stokes[0] * (1.0 + beta[loop]*Nt)) # ax[loop].set_xlabel('Time [s]') # ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) # ax[loop].annotate",
"190 198 206 214] [262 270 278 286 294] [342 350 358 366",
"ndarray def myFFT(x): \"\"\" Return the FFT of a real signal taking into",
"normSolutionL1, 100.0*normSolutionL0 / self.nSteps, I0, Q0/I0, U0/I0, V0/I0, betaI, betaQ, betaU, betaV) normL2.append(normResidual)",
"self.softThreshold(y - self.mu * np.real(gradient), lambdaValue) xNew[0] = 0.0 xNew /= np.sqrt(myTotalPower(xNew)) if",
"* forwV) gradient2 = -2.0 * I0 * betaI * self.backward(residual2, 0) +",
"- lambdaValue / np.fmax(np.abs(x),1e-10)) * x def hardThreshold(self, x, lambdaValue): xPar = np.copy(x)",
"', np.sum(self.seeing**2), myTotalPower(self.seeingFFT) # Compute the signal and its power spectrum self.signal =",
"self.modulation[0] sign = (-1.0)**i for j in range(1,4): temp += sign * self.signal[j]",
"0.000000051) # stI, stQ, stU, stV = out.demodulateTrivial() # print \"Q/I_original={0} - Q/I_inferred={1}",
"= np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0] = 0.0 self.seeingFFT = np.sqrt(self.powerSeeing) * noiseFFT self.seeingFFT",
"= 1.0 def forward(self, signal, beta, ray): return self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self, signal, ray):",
"------- float : signal \"\"\" out = fft.irfft(x) return out * np.sqrt(len(out)) def",
"Fourier coefficients of the real signal \"\"\" out = fft.rfft(x) return out /",
"np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ U0 * Q0 * np.sum(M2One * M3N) -",
"[102 110 118 126 134] [182 190 198 206 214] [262 270 278",
"0) # M1(t) * N(t) M2N = self.forwardPartial(signal, 1) # M2(t) * N(t)",
"* np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime = self.dtIntegration self.lengthSample = int(self.dtIntegration / self.dt) self.nSamples =",
"* 1(t) M2One = self.forwardPartial(np.ones(self.nSteps), 1) # M2(t) * 1(t) M3One = self.forwardPartial(np.ones(self.nSteps),",
"126 134] [182 190 198 206 214] [262 270 278 286 294] [342",
"[None] * 2 for i in range(2): temp = self.signal[0] * self.modulation[0] sign",
"target shape, by summing or averaging. Number of output dimensions must match number",
"Betas and Stokes parameters self.beta = beta self.stokes = stokes # Generate Gaussian",
"0.1 U0 = 0.2 V0 = 0.3 betaI = 10.0#self.beta[0] betaQ = 10.0#self.beta[1]",
"total power \"\"\" return f[0]**2 + 2.0*np.sum(f[1:]**2) class randomDemodulator(object): \"\"\"Summary Returns ------- TYPE",
"np.sum(forwI**2) A = np.zeros((3,3)) A[0,0] = np.sum(forwQ**2) A[1,1] = np.sum(forwU**2) A[2,2] = np.sum(forwV**2)",
"* U0 * np.sum(M3N * M2N) A[1,0] = A[0,1] A[0,2] = Q0 *",
"# s # dtIntegration = 0.01 #s # beta = np.asarray([15.0, 100.0, 100.,",
"betaI * self.backward(residual2, 0) + 2.0 * Q0 * betaQ * self.backward(residual2, 1)",
"out = randomDemodulator(totalTime, dt, dtIntegration, stokes, beta, seed=123, signalToNoise=1e3) # coefFourier, stokes, beta,",
"b[0] = 0.5 * Q0 * np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ Q0**2 *",
"normL21, normL11 = out.FISTA(thresholdMethod = 'soft', niter = 600, lambdaValue = 0.000000051) #",
"= 0.3 betaI = 10.0#self.beta[0] betaQ = 10.0#self.beta[1] betaU = 10.0#self.beta[2] betaV =",
"2.0 * V0 * betaV * self.backward(residual2, 3) gradient = gradient1 + gradient2",
"(I0 * forwI + Q0 * forwQ + U0 * forwU + V0",
"int, optional Description Returns ------- TYPE : Description \"\"\" self.totalTime = totalTime self.dt",
": TYPE Description dtIntegration : TYPE Description seed : int, optional Description Returns",
"3) # M4(t) * N(t) M1One = self.forwardPartial(np.ones(self.nSteps), 0) # M1(t) * 1(t)",
"= 600, lambdaValue = 0.000000051) # stI, stQ, stU, stV = out.demodulateTrivial() #",
"(1+betaQ*N(t)) forwU = self.forward(signal, betaU, 2) # M3(t) * (1+betaU*N(t)) forwV = self.forward(signal,",
"self.dt = dt self.dtIntegration = dtIntegration self.seed = seed self.signalToNoise = signalToNoise self.modulationType",
"(self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ U0 * Q0 * np.sum(M2One * M3N) - U0**2 *",
"ndarray.sum(-1*(i+1)) elif operation.lower() in [\"mean\", \"average\", \"avg\"]: ndarray = ndarray.mean(-1*(i+1)) return ndarray def",
"sp.coo_matrix((sparseData, (sparseRow, sparseCol)), shape=(self.nSamples, self.nSteps)) self.sparseMStar[state] = self.sparseM[state].transpose(copy=True) self.factor = 2*np.ones(self.nSteps) self.factor[0] =",
"spectrum self.powerLites = np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] = 10.0**self.powerLites[:,1] # Number of samples of the",
"= np.zeros(self.nSteps) I0 = 0.9 Q0 = 0.1 U0 = 0.2 V0 =",
"myFFT(x): \"\"\" Return the FFT of a real signal taking into account some",
"< lambdaValue] = 0.0 return xPar def FISTA(self, initial=None, initialStokes=None, thresholdMethod='soft', niter=10, lambdaValue=1.0):",
"xNew[0] = 0.0 xNew /= np.sqrt(myTotalPower(xNew)) if (thresholdMethod == 'L2'): xNew = y",
"100.0*normSolutionL0 / self.nSteps, I0, Q0/I0, U0/I0, V0/I0, betaI, betaQ, betaU, betaV) normL2.append(normResidual) normL1.append(normSolutionL1)",
"betaQ, betaU, betaV), normL2, normL1, normL0 def demodulateTrivial(self): forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ =",
"stokes[loop] / stokes[0] * (1.0 + beta[loop]*Nt)) # ax[loop].set_xlabel('Time [s]') # ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop]))",
"the power spectrum of a signal Parameters ---------- f : float Signal Fourier",
"= self.forwardPartial(np.ones(self.nSteps), 1) # M2(t) * 1(t) M3One = self.forwardPartial(np.ones(self.nSteps), 2) # M3(t)",
"ax[loop].plot(out.times, stokes[loop] / stokes[0] * (1.0 + beta[loop]*Nt)) # ax[loop].set_xlabel('Time [s]') # ax[loop].set_ylabel('Stokes",
"* V0 * betaV * self.backward(residual2, 3) gradient = gradient1 + gradient2 if",
"out * np.sqrt(len(out)) def myTotalPower(f): \"\"\" Return the power spectrum of a signal",
"ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3] / stokes[0] * (1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21)",
"in ['sum', 'mean', 'average', 'avg']: raise ValueError(\"Operation {} not supported.\".format(operation)) if ndarray.ndim !=",
"= temp['arr_0'][0:self.nSteps] self.betaModulation = temp['arr_1'][0:self.nSteps] self.modulation = [np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation)",
"= 1e-3 if (np.abs(U0) > 1.0): U0 = 1e-3 if (np.abs(V0) > 1.0):",
"np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) return I0, Q0, U0, V0",
"V/I_inferred={1} - V/I_trivial={2} - diff={3}\".format(out.stokes[3] / out.stokes[0], stokes[3] / stokes[0], \\ # stV/stI,",
"== 0): self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps) else: temp = np.load('alphaBetaSamples.npz') self.alphaModulation",
"signal taking into account some normalization Parameters ---------- x : float Fourier coefficients",
"286 294] [342 350 358 366 374]] \"\"\" if not operation.lower() in ['sum',",
"U/I_inferred={1} - U/I_trivial={2} - diff={3}\".format(out.stokes[2] / out.stokes[0], stokes[2] / stokes[0], \\ # stU/stI,",
"(self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] = 0.5 * np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] = 0.5 * np.sum(forwV",
"self.dt # Frequency axis self.freq = fft.rfftfreq(self.nSteps, d=dt) # Betas and Stokes parameters",
"signal Parameters ---------- f : float Signal Fourier coefficients Returns ------- float :",
"* 4 self.sparseMStar = [None] * 4 for state in range(4): sparseData =",
"forwV) gradient2 = -2.0 * I0 * betaI * self.backward(residual2, 0) + 2.0",
"U0 * np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ U0 * Q0 * np.sum(M2One *",
"= 0.5*np.pi*np.random.rand(self.nSteps) else: temp = np.load('alphaBetaSamples.npz') self.alphaModulation = temp['arr_0'][0:self.nSteps] self.betaModulation = temp['arr_1'][0:self.nSteps] self.modulation",
"Q0, U0, V0 = np.linalg.solve(A,b) return I0, Q0, U0, V0 # totalTime =",
"np.zeros(3) b[0] = 0.5 * Q0 * np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ Q0**2",
"ndarray.ndim != len(new_shape): raise ValueError(\"Shape mismatch: {} -> {}\".format(ndarray.shape, new_shape)) compression_pairs = [(d,",
"np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) if (I0 < 0): I0",
"= Q0**2 * np.sum(M2N**2) A[1,1] = U0**2 * np.sum(M3N**2) A[2,2] = V0**2 *",
"self.integrationTime = self.dtIntegration self.lengthSample = int(self.dtIntegration / self.dt) self.nSamples = int(self.dt / self.dtIntegration",
"* np.sum(M2One * M3N) - U0**2 * np.sum(M3One * M3N) - U0 *",
"= self.forwardPartial(signal, 3) # M4(t) * N(t) M1One = self.forwardPartial(np.ones(self.nSteps), 0) # M1(t)",
"= [] loop = 0 for i in range(self.nSamples): for j in range(self.lengthSample):",
"argmin_O ||y - M*F^{-1}*alpha||_2 + \\lambda ||alpha||_1 Args: rank (int, optional): rank of",
"in compression_pairs for l in p] ndarray = ndarray.reshape(flattened) for i in range(len(new_shape)):",
"= 10.0#self.beta[3] else: x = np.copy(initial) I0, Q0, U0, V0 = initialStokes xNew",
"# loop = 0 # for loop in range(4): # ax[loop].plot(out.times, out.signal[loop]) #",
"* Q0 * betaQ * self.backward(residual1, 1) - \\ 2.0 * U0 *",
"normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0) return x, (I0, Q0, U0, V0), (betaI, betaQ, betaU, betaV),",
"np.sum(M2One * M3N) - U0**2 * np.sum(M3One * M3N) - U0 * V0",
"(self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ Q0**2 * np.sum(M2One * M2N) - Q0 * U0 *",
"* self.backward(residual2, 3) gradient = gradient1 + gradient2 if (thresholdMethod == 'hardLambda'): xNew",
"# M4(t) * N(t) M1One = self.forwardPartial(np.ones(self.nSteps), 0) # M1(t) * 1(t) M2One",
"/ out.stokes[0]-stokes[1] / stokes[0]) # print \"U/I_original={0} - U/I_inferred={1} - U/I_trivial={2} - diff={3}\".format(out.stokes[2]",
"np.linalg.norm(x, 0) if (loop % 10): # Stokes parameters I0 = 0.5 *",
"A[1,0] = A[0,1] A[0,2] = Q0 * V0 * np.sum(M4N * M2N) A[2,0]",
"modulation using a lambda/4 and lambda/2 polarimeter with random angles # self.modulation =",
"* np.sum(M4One * M2N) b[1] = 0.5 * U0 * np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1]))",
"1.0): Q0 = 1e-3 if (np.abs(U0) > 1.0): U0 = 1e-3 if (np.abs(V0)",
"(loop % 50 == 0): print \"It {0:4d} - l2={1:10.3e} - l1={2:10.4f} -",
"- \\ U0 * Q0 * np.sum(M2One * M3N) - U0**2 * np.sum(M3One",
"power \"\"\" return f[0]**2 + 2.0*np.sum(f[1:]**2) class randomDemodulator(object): \"\"\"Summary Returns ------- TYPE :",
"dt) self.times = np.arange(self.nSteps) * self.dt # Frequency axis self.freq = fft.rfftfreq(self.nSteps, d=dt)",
"TYPE : Demodulate I and Q signals together \"\"\" def __init__(self, totalTime, dt,",
"0.5*(1+np.sqrt(1+4.0*t**2)) y = xNew + (t-1.0) / tNew * (xNew - x) t",
"M1(t) * N(t) M2N = self.forwardPartial(signal, 1) # M2(t) * N(t) M3N =",
"self.dt) self.nSamples = int(self.dt / self.dtIntegration * self.nSteps) self.signalIntegrated = [None] * 2",
"def hardThreshold(self, x, lambdaValue): xPar = np.copy(x) xPar[np.abs(x) < lambdaValue] = 0.0 return",
"out = fft.rfft(x) return out / np.sqrt(len(out)) def myIFFT(x): \"\"\" Return the IFFT",
"self.factor * myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self, z): return (z[0] * z[0].conj() + 2 *",
"# print \"Q/I_original={0} - Q/I_inferred={1} - Q/I_trivial={2} - diff={3}\".format(out.stokes[1] / out.stokes[0], stokes[1] /",
"self.signal[i] = self.stokes[i]*(1.0 + self.beta[i] * self.seeing) # Generate modulation using a lambda/4",
"seed self.signalToNoise = signalToNoise self.modulationType = modulationType if (self.seed != 0): np.random.seed(self.seed) #",
"* M4N) - V0**2 * np.sum(M4One * M4N) betaI = np.abs((0.5 * I0",
"I0, Q0, U0, V0 = initialStokes xNew = np.copy(x) y = np.copy(x) res",
"Returns ------- float : signal \"\"\" out = fft.irfft(x) return out * np.sqrt(len(out))",
"forward(self, signal, beta, ray): return self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self, signal, ray): return self.sparseM[ray].dot(signal) def",
"np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] = 0.5 * np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] = 0.5",
"= np.linalg.solve(A,b) if (I0 < 0): I0 = 1.0 if (np.abs(Q0) > 1.0):",
"for j in range(1,4): temp += sign * self.signal[j] * self.modulation[j] self.signalIntegrated[i] =",
"power is unity print 'Total variance = ', np.sum(self.seeing**2), myTotalPower(self.seeingFFT) # Compute the",
"range(4): self.signal[i] = self.stokes[i]*(1.0 + self.beta[i] * self.seeing) # Generate modulation using a",
"self.factor[0] = 1.0 def forward(self, signal, beta, ray): return self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self, signal,",
"Parameters ---------- x : float Signal time series Returns ------- float : Fourier",
"(self.nSamples,), operation='sum') self.signalIntegrated[i] += np.mean(self.signalIntegrated[i]) / self.signalToNoise * np.random.randn(self.nSamples) self.tIntegrated = np.arange(self.nSamples) *",
"Q0, U0, V0), (betaI, betaQ, betaU, betaV), normL2, normL1, normL0 def demodulateTrivial(self): forwI",
"series Returns ------- float : Fourier coefficients of the real signal \"\"\" out",
"randomDemodulator(object): \"\"\"Summary Returns ------- TYPE : Demodulate I and Q signals together \"\"\"",
"/ out.stokes[0], stokes[3] / stokes[0], \\ # stV/stI, out.stokes[3] / out.stokes[0]-stokes[3] / stokes[0])",
"* betaU * self.backward(residual2, 2) + 2.0 * V0 * betaV * self.backward(residual2,",
"V0 * forwV) gradient2 = -2.0 * I0 * betaI * self.backward(residual2, 0)",
"* betaI * self.backward(residual1, 0) - 2.0 * Q0 * betaQ * self.backward(residual1,",
"ax[1,0].plot(stokes[2] / stokes[0] * (1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3] / stokes[0] * (1.0+beta[3]*Nt))",
"the square root of the power spectrum # to generate the noise with",
"# ax[loop].set_xlabel('Time [s]') # ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) # ax[loop].annotate # pl.tight_layout() # ax[0,0].plot(out.times, out.signal[0])",
"1.0 normL1 = [] normL2 = [] normL0 = [] for loop in",
"amplitude M1N = self.forwardPartial(signal, 0) # M1(t) * N(t) M2N = self.forwardPartial(signal, 1)",
"---------- f : float Signal Fourier coefficients Returns ------- float : total power",
"V0 * Q0 * np.sum(M2One * M4N) - V0 * U0 * np.sum(M3One",
"if ndarray.ndim != len(new_shape): raise ValueError(\"Shape mismatch: {} -> {}\".format(ndarray.shape, new_shape)) compression_pairs =",
"46 54] [102 110 118 126 134] [182 190 198 206 214] [262",
"M1N)) / (I0**2 * np.sum(M1N**2))) betaQ, betaU, betaV = np.abs(np.linalg.solve(A,b)) if (loop %",
"signal taking into account some normalization Parameters ---------- x : float Signal time",
"+ 2.0*np.sum(f[1:]**2) class randomDemodulator(object): \"\"\"Summary Returns ------- TYPE : Demodulate I and Q",
"self.signalIntegrated[i] = bin_ndarray(temp, (self.nSamples,), operation='sum') self.signalIntegrated[i] += np.mean(self.signalIntegrated[i]) / self.signalToNoise * np.random.randn(self.nSamples) self.tIntegrated",
"[(d, c//d) for d, c in zip(new_shape, ndarray.shape)] flattened = [l for p",
"np.linalg.norm(residual1 + residual2) normSolutionL1 = np.linalg.norm(x, 1) normSolutionL0 = np.linalg.norm(x, 0) if (loop",
"noise with unit variance and multiply by the square root of the power",
"= 1.0 if (np.abs(Q0) > 1.0): Q0 = 1e-3 if (np.abs(U0) > 1.0):",
"betaQ * self.backward(residual1, 1) - \\ 2.0 * U0 * betaU * self.backward(residual1,",
"= pl.subplots(nrows=1, ncols=4, figsize=(18,6)) # coefFourier[0] = 0.0 # Nt = myIFFT(coefFourier) #",
"np.linalg.solve(A,b) if (I0 < 0): I0 = 1.0 if (np.abs(Q0) > 1.0): Q0",
"self.modulation = [np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime =",
"self.signal[j] * self.modulation[j] self.signalIntegrated[i] = bin_ndarray(temp, (self.nSamples,), operation='sum') self.signalIntegrated[i] += np.mean(self.signalIntegrated[i]) / self.signalToNoise",
"M3(t) * (1+betaU*N(t)) forwV = self.forward(signal, betaV, 3) # M4(t) * (1+betaV*N(t)) residual1",
"for i in range(self.nSamples): for j in range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop) loop +=",
"374]] \"\"\" if not operation.lower() in ['sum', 'mean', 'average', 'avg']: raise ValueError(\"Operation {}",
"I0 = 0.9 Q0 = 0.1 U0 = 0.2 V0 = 0.3 betaI",
"= bin_ndarray(temp, (self.nSamples,), operation='sum') self.signalIntegrated[i] += np.mean(self.signalIntegrated[i]) / self.signalToNoise * np.random.randn(self.nSamples) self.tIntegrated =",
"M1(t) * 1(t) M2One = self.forwardPartial(np.ones(self.nSteps), 1) # M2(t) * 1(t) M3One =",
"/ stokes[0]) # print \"U/I_original={0} - U/I_inferred={1} - U/I_trivial={2} - diff={3}\".format(out.stokes[2] / out.stokes[0],",
"axis self.freq = fft.rfftfreq(self.nSteps, d=dt) # Betas and Stokes parameters self.beta = beta",
"= np.linalg.solve(A,b) return I0, Q0, U0, V0 # totalTime = 1.0 # s",
"= ndarray.mean(-1*(i+1)) return ndarray def myFFT(x): \"\"\" Return the FFT of a real",
"- l2={1:10.3e} - l1={2:10.4f} - l0={3:5.1f}% - I={4:11.5f} - Q/I={5:11.5f} - U/I={6:11.5f} -",
"(int, optional): rank of the solution niter (int, optional): number of iterations Returns:",
"2.0 * Q0 * betaQ * self.backward(residual2, 1) + \\ 2.0 * U0",
"if not operation.lower() in ['sum', 'mean', 'average', 'avg']: raise ValueError(\"Operation {} not supported.\".format(operation))",
"int(totalTime / dt) self.times = np.arange(self.nSteps) * self.dt # Frequency axis self.freq =",
"- \\ 2.0 * U0 * betaU * self.backward(residual1, 2) - 2.0 *",
"self.seed = seed self.signalToNoise = signalToNoise self.modulationType = modulationType if (self.seed != 0):",
"np.arange(0,100,1).reshape((10,10)) >>> n = bin_ndarray(m, new_shape=(5,5), operation='sum') >>> print(n) [[ 22 30 38",
"/ stokes[0] * (1.0 + beta[loop]*Nt)) # ax[loop].set_xlabel('Time [s]') # ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) #",
"M3N) - U0**2 * np.sum(M3One * M3N) - U0 * V0 * np.sum(M4One",
"* np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ V0 * Q0 * np.sum(M2One * M4N)",
"np.fmax(np.abs(x),1e-10)) * x def hardThreshold(self, x, lambdaValue): xPar = np.copy(x) xPar[np.abs(x) < lambdaValue]",
"= ndarray.sum(-1*(i+1)) elif operation.lower() in [\"mean\", \"average\", \"avg\"]: ndarray = ndarray.mean(-1*(i+1)) return ndarray",
"forwU = self.forward(signal, betaU, 2) # M3(t) * (1+betaU*N(t)) forwV = self.forward(signal, betaV,",
"np.sum(M3N**2) A[2,2] = V0**2 * np.sum(M4N**2) A[0,1] = Q0 * U0 * np.sum(M3N",
"- 2.0 * V0 * betaV * self.backward(residual1, 3) residual2 = self.signalIntegrated[1] -",
"\\ # stQ/stI, out.stokes[1] / out.stokes[0]-stokes[1] / stokes[0]) # print \"U/I_original={0} - U/I_inferred={1}",
"self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'soft'): xNew = self.softThreshold(y",
"-2.0 * I0 * betaI * self.backward(residual1, 0) - 2.0 * Q0 *",
"[] sparseCol = [] loop = 0 for i in range(self.nSamples): for j",
"= np.zeros(3) b[0] = 0.5 * np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] = 0.5 *",
"* (self.signalIntegrated[0]+self.signalIntegrated[1])) - \\ I0**2 * np.sum(M1One * M1N)) / (I0**2 * np.sum(M1N**2)))",
"= self.signalIntegrated[1] - (I0 * forwI - Q0 * forwQ - U0 *",
"b[2] = 0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) if",
"self.forward(signal, betaQ, 1) # M2(t) * (1+betaQ*N(t)) forwU = self.forward(signal, betaU, 2) #",
"= [None] * 4 self.sparseMStar = [None] * 4 for state in range(4):",
"* V0 * np.sum(M4N * M2N) A[2,0] = A[0,2] A[1,2] = U0 *",
"np.zeros((3,3)) A[0,0] = Q0**2 * np.sum(M2N**2) A[1,1] = U0**2 * np.sum(M3N**2) A[2,2] =",
"print(n) [[ 22 30 38 46 54] [102 110 118 126 134] [182",
"/ stokes[0], \\ # stQ/stI, out.stokes[1] / out.stokes[0]-stokes[1] / stokes[0]) # print \"U/I_original={0}",
"== None): x = np.zeros(self.nSteps) I0 = 0.9 Q0 = 0.1 U0 =",
"= self.dtIntegration self.lengthSample = int(self.dtIntegration / self.dt) self.nSamples = int(self.dt / self.dtIntegration *",
"Q/I={5:11.5f} - U/I={6:11.5f} - V/I={7:11.5f} - bI={8:11.5f} - bQ={9:11.5f} - bU={10:11.5f} - bV={11:11.5f}\".format(loop,",
"= np.load('alphaBetaSamples.npz') self.alphaModulation = temp['arr_0'][0:self.nSteps] self.betaModulation = temp['arr_1'][0:self.nSteps] self.modulation = [np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation)",
"state in range(4): sparseData = [] sparseRow = [] sparseCol = [] loop",
"in range(4): # ax[loop].plot(out.times, out.signal[loop]) # ax[loop].plot(out.times, stokes[loop] / stokes[0] * (1.0 +",
"z, ray): return self.factor * myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self, z): return (z[0] * z[0].conj()",
"\\ U0 * Q0 * np.sum(M2One * M3N) - U0**2 * np.sum(M3One *",
"signalToNoise self.modulationType = modulationType if (self.seed != 0): np.random.seed(self.seed) # Read seeing power",
"[np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime = self.dtIntegration self.lengthSample",
"= myIFFT(coefFourier) # Nt /= np.sqrt(myTotalPower(coefFourier)) # stokesPar = ['I', 'Q', 'U', 'V']",
"dt, dtIntegration, stokes, beta, seed=123, signalToNoise=1e3) # coefFourier, stokes, beta, normL21, normL11 =",
"signal \"\"\" out = fft.rfft(x) return out / np.sqrt(len(out)) def myIFFT(x): \"\"\" Return",
"* I0 * np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1])) - \\ I0**2 * np.sum(M1One * M1N))",
"Q signals together \"\"\" def __init__(self, totalTime, dt, dtIntegration, stokes, beta, signalToNoise=0.0, seed=0,",
"np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ Q0**2 * np.sum(M2One * M2N) - Q0 *",
"for j in range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop) loop += 1 self.sparseM[state] = sp.coo_matrix((sparseData,",
"# coefFourier, stokes, beta, normL21, normL11 = out.FISTA(thresholdMethod = 'soft', niter = 600,",
"= xNew + (t-1.0) / tNew * (xNew - x) t = tNew",
"float : Fourier coefficients of the real signal \"\"\" out = fft.rfft(x) return",
"[262 270 278 286 294] [342 350 358 366 374]] \"\"\" if not",
"stQ/stI, out.stokes[1] / out.stokes[0]-stokes[1] / stokes[0]) # print \"U/I_original={0} - U/I_inferred={1} - U/I_trivial={2}",
"self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 = 0.5 * np.sum(forwI *",
"= randomDemodulator(totalTime, dt, dtIntegration, stokes, beta, seed=123, signalToNoise=1e3) # coefFourier, stokes, beta, normL21,",
"ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) # ax[loop].annotate # pl.tight_layout() # ax[0,0].plot(out.times, out.signal[0]) # ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt))",
"float Fourier coefficients Returns ------- float : signal \"\"\" out = fft.irfft(x) return",
"ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1] / stokes[0] *(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2] / stokes[0] *",
"> 1.0): Q0 = 1e-3 if (np.abs(U0) > 1.0): U0 = 1e-3 if",
"* 1(t) A = np.zeros((3,3)) A[0,0] = Q0**2 * np.sum(M2N**2) A[1,1] = U0**2",
"= np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] = 10.0**self.powerLites[:,1] # Number of samples of the original sample",
"of the power spectrum # to generate the noise with the appropriate power",
"(initial == None): x = np.zeros(self.nSteps) I0 = 0.9 Q0 = 0.1 U0",
"* np.sum(z[1:] * z[1:].conj())).real / len(z) def softThreshold(self, x, lambdaValue): return np.fmax(0,1.0 -",
"1(t) M2One = self.forwardPartial(np.ones(self.nSteps), 1) # M2(t) * 1(t) M3One = self.forwardPartial(np.ones(self.nSteps), 2)",
"= 10.0#self.beta[1] betaU = 10.0#self.beta[2] betaV = 10.0#self.beta[3] else: x = np.copy(initial) I0,",
"forwI + Q0 * forwQ + U0 * forwU + V0 * forwV)",
"* (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ U0 * Q0 * np.sum(M2One * M3N) - U0**2",
"\\ 2.0 * U0 * betaU * self.backward(residual2, 2) + 2.0 * V0",
"as pl import scipy.sparse as sp import scipy.sparse.linalg as splinalg import scipy.fftpack as",
"np import matplotlib.pyplot as pl import scipy.sparse as sp import scipy.sparse.linalg as splinalg",
"if (initial == None): x = np.zeros(self.nSteps) I0 = 0.9 Q0 = 0.1",
"# Generate Gaussian noise with unit variance and multiply by the square root",
"= 0.2 V0 = 0.3 betaI = 10.0#self.beta[0] betaQ = 10.0#self.beta[1] betaU =",
"= np.zeros((3,3)) A[0,0] = np.sum(forwQ**2) A[1,1] = np.sum(forwU**2) A[2,2] = np.sum(forwV**2) A[0,1] =",
"random angles # self.modulation = [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType == 0):",
"= np.arange(self.nSamples) * self.dtIntegration # Generate modulation matrix self.sparseM = [None] * 4",
"self.dtIntegration * self.nSteps) self.signalIntegrated = [None] * 2 for i in range(2): temp",
"Description dt : TYPE Description dtIntegration : TYPE Description seed : int, optional",
"10): # Stokes parameters I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2)",
"np.sum(M2One * M4N) - V0 * U0 * np.sum(M3One * M4N) - V0**2",
"for loop in range(niter): signal = myIFFT(x) forwI = self.forward(signal, betaI, 0) #",
"np.linalg.solve(A,b) return I0, Q0, U0, V0 # totalTime = 1.0 # s #",
"normL0 def demodulateTrivial(self): forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV",
"modulationType=0): \"\"\"Summary Parameters ---------- totalTime : TYPE Description dt : TYPE Description dtIntegration",
"/ len(z) def softThreshold(self, x, lambdaValue): return np.fmax(0,1.0 - lambdaValue / np.fmax(np.abs(x),1e-10)) *",
"Q/I_inferred={1} - Q/I_trivial={2} - diff={3}\".format(out.stokes[1] / out.stokes[0], stokes[1] / stokes[0], \\ # stQ/stI,",
"lambdaValue): return np.fmax(0,1.0 - lambdaValue / np.fmax(np.abs(x),1e-10)) * x def hardThreshold(self, x, lambdaValue):",
"A[2,1] = A[1,2] b = np.zeros(3) b[0] = 0.5 * np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1]))",
"self.powerLites[:,1]) self.powerSeeing[0] = 0.0 self.seeingFFT = np.sqrt(self.powerSeeing) * noiseFFT self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing",
"- diff={3}\".format(out.stokes[1] / out.stokes[0], stokes[1] / stokes[0], \\ # stQ/stI, out.stokes[1] / out.stokes[0]-stokes[1]",
"[l for p in compression_pairs for l in p] ndarray = ndarray.reshape(flattened) for",
"# ax[1,1].plot(stokes[3] / stokes[0] * (1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21) #",
"self.beta[i] * self.seeing) # Generate modulation using a lambda/4 and lambda/2 polarimeter with",
"% 50 == 0): print \"It {0:4d} - l2={1:10.3e} - l1={2:10.4f} - l0={3:5.1f}%",
"* M3N) A[2,1] = A[1,2] b = np.zeros(3) b[0] = 0.5 * Q0",
"loop = 0 # for loop in range(4): # ax[loop].plot(out.times, out.signal[loop]) # ax[loop].plot(out.times,",
"------- TYPE : Demodulate I and Q signals together \"\"\" def __init__(self, totalTime,",
"f, ax = pl.subplots(nrows=1, ncols=4, figsize=(18,6)) # coefFourier[0] = 0.0 # Nt =",
"[342 350 358 366 374]] \"\"\" if not operation.lower() in ['sum', 'mean', 'average',",
"myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self, z): return (z[0] * z[0].conj() + 2 * np.sum(z[1:] *",
"np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ V0 * Q0 * np.sum(M2One * M4N) -",
"out.signal[loop]) # ax[loop].plot(out.times, stokes[loop] / stokes[0] * (1.0 + beta[loop]*Nt)) # ax[loop].set_xlabel('Time [s]')",
"I and Q signals together \"\"\" def __init__(self, totalTime, dt, dtIntegration, stokes, beta,",
"Q0**2 * np.sum(M2One * M2N) - Q0 * U0 * np.sum(M3One * M2N)",
"and lambda/2 polarimeter with random angles # self.modulation = [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0]",
"0.5 / (np.real(largestEigenvalue)) * 0.0002 t = 1.0 normL1 = [] normL2 =",
"sp import scipy.sparse.linalg as splinalg import scipy.fftpack as fft def bin_ndarray(ndarray, new_shape, operation='sum'):",
"# coefFourier[0] = 0.0 # Nt = myIFFT(coefFourier) # Nt /= np.sqrt(myTotalPower(coefFourier)) #",
"normL2, normL1, normL0 def demodulateTrivial(self): forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU =",
"I0 * betaI * self.backward(residual1, 0) - 2.0 * Q0 * betaQ *",
"1.0 if (np.abs(Q0) > 1.0): Q0 = 1e-3 if (np.abs(U0) > 1.0): U0",
"/ dt) self.times = np.arange(self.nSteps) * self.dt # Frequency axis self.freq = fft.rfftfreq(self.nSteps,",
"(np.abs(U0) > 1.0): U0 = 1e-3 if (np.abs(V0) > 1.0): V0 = 1e-3",
"Nt = myIFFT(coefFourier) # Nt /= np.sqrt(myTotalPower(coefFourier)) # stokesPar = ['I', 'Q', 'U',",
"of input dimensions. Example ------- >>> m = np.arange(0,100,1).reshape((10,10)) >>> n = bin_ndarray(m,",
"Q0, U0, V0 # totalTime = 1.0 # s # dt = 0.001",
"ndarray = ndarray.sum(-1*(i+1)) elif operation.lower() in [\"mean\", \"average\", \"avg\"]: ndarray = ndarray.mean(-1*(i+1)) return",
"return xPar def FISTA(self, initial=None, initialStokes=None, thresholdMethod='soft', niter=10, lambdaValue=1.0): \"\"\" Solve the l1",
"0.5 * Q0 * np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ Q0**2 * np.sum(M2One *",
"diff={3}\".format(out.stokes[2] / out.stokes[0], stokes[2] / stokes[0], \\ # stU/stI, out.stokes[2] / out.stokes[0]-stokes[2] /",
"normL2 = [] normL0 = [] for loop in range(niter): signal = myIFFT(x)",
"sign = (-1.0)**i for j in range(1,4): temp += sign * self.signal[j] *",
"* M4N) betaI = np.abs((0.5 * I0 * np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1])) - \\",
"* (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] = 0.5 * np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] = 0.5 *",
"278 286 294] [342 350 358 366 374]] \"\"\" if not operation.lower() in",
"/ self.dtIntegration * self.nSteps) self.signalIntegrated = [None] * 2 for i in range(2):",
"(thresholdMethod == 'hardLambda'): xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod",
"np.sum(M4N**2) A[0,1] = Q0 * U0 * np.sum(M3N * M2N) A[1,0] = A[0,1]",
"a real signal taking into account some normalization Parameters ---------- x : float",
"np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1])) - \\ I0**2 * np.sum(M1One * M1N)) / (I0**2 *",
"np.real(gradient) tNew = 0.5*(1+np.sqrt(1+4.0*t**2)) y = xNew + (t-1.0) / tNew * (xNew",
"(thresholdMethod == 'hardPercentage'): xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod",
"(1+betaI*N(t)) forwQ = self.forward(signal, betaQ, 1) # M2(t) * (1+betaQ*N(t)) forwU = self.forward(signal,",
"np.asarray([15.0, 100.0, 100., 100.0]) # stokes = np.asarray([1.0, 1.2e-3, 5.e-3, 0.001]) # out",
"p] ndarray = ndarray.reshape(flattened) for i in range(len(new_shape)): if operation.lower() == \"sum\": ndarray",
"np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime = self.dtIntegration self.lengthSample = int(self.dtIntegration / self.dt) self.nSamples = int(self.dt",
"appropriate power spectrum noise = np.random.randn(self.nSteps) noiseFFT = myFFT(noise) self.powerSeeing = np.interp(np.abs(self.freq), self.powerLites[:,0],",
"* np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] = 0.5 * np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] =",
"206 214] [262 270 278 286 294] [342 350 358 366 374]] \"\"\"",
"loop += 1 self.sparseM[state] = sp.coo_matrix((sparseData, (sparseRow, sparseCol)), shape=(self.nSamples, self.nSteps)) self.sparseMStar[state] = self.sparseM[state].transpose(copy=True)",
": float Signal time series Returns ------- float : Fourier coefficients of the",
"np.load('alphaBetaSamples.npz') self.alphaModulation = temp['arr_0'][0:self.nSteps] self.betaModulation = temp['arr_1'][0:self.nSteps] self.modulation = [np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation) *",
"/ self.dt) self.nSamples = int(self.dt / self.dtIntegration * self.nSteps) self.signalIntegrated = [None] *",
"x = np.copy(initial) I0, Q0, U0, V0 = initialStokes xNew = np.copy(x) y",
"# for loop in range(4): # ax[loop].plot(out.times, out.signal[loop]) # ax[loop].plot(out.times, stokes[loop] / stokes[0]",
"U0 * forwU - V0 * forwV) gradient2 = -2.0 * I0 *",
"= self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue = splinalg.eigsh(res, k=1, which='LM', return_eigenvectors=False) self.mu = 0.5 / (np.real(largestEigenvalue))",
"range(4): sparseData = [] sparseRow = [] sparseCol = [] loop = 0",
"[] loop = 0 for i in range(self.nSamples): for j in range(self.lengthSample): sparseData.append(self.modulation[state][loop])",
"/ (I0**2 * np.sum(M1N**2))) betaQ, betaU, betaV = np.abs(np.linalg.solve(A,b)) if (loop % 50",
"bI={8:11.5f} - bQ={9:11.5f} - bU={10:11.5f} - bV={11:11.5f}\".format(loop, normResidual, normSolutionL1, 100.0*normSolutionL0 / self.nSteps, I0,",
"lambdaValue=1.0): \"\"\" Solve the l1 regularized problem using the FISTA algorithm, that solves",
"polarimeter with random angles # self.modulation = [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType",
"temp['arr_1'][0:self.nSteps] self.modulation = [np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime",
"np.sum(M4N * M3N) A[2,1] = A[1,2] b = np.zeros(3) b[0] = 0.5 *",
"for i in range(2): temp = self.signal[0] * self.modulation[0] sign = (-1.0)**i for",
"scipy.sparse as sp import scipy.sparse.linalg as splinalg import scipy.fftpack as fft def bin_ndarray(ndarray,",
"beta self.stokes = stokes # Generate Gaussian noise with unit variance and multiply",
"N(t) M4N = self.forwardPartial(signal, 3) # M4(t) * N(t) M1One = self.forwardPartial(np.ones(self.nSteps), 0)",
"self.stokes = stokes # Generate Gaussian noise with unit variance and multiply by",
"as splinalg import scipy.fftpack as fft def bin_ndarray(ndarray, new_shape, operation='sum'): \"\"\" Bins an",
"signal = myIFFT(x) forwI = self.forward(signal, betaI, 0) # M1(t) * (1+betaI*N(t)) forwQ",
"= np.sqrt(self.powerSeeing) * noiseFFT self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing = myIFFT(self.seeingFFT) # Make sure",
"= np.asarray([1.0, 1.2e-3, 5.e-3, 0.001]) # out = randomDemodulator(totalTime, dt, dtIntegration, stokes, beta,",
"# Betas and Stokes parameters self.beta = beta self.stokes = stokes # Generate",
"* (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ Q0**2 * np.sum(M2One * M2N) - Q0 * U0",
"self.sparseM[state] = sp.coo_matrix((sparseData, (sparseRow, sparseCol)), shape=(self.nSamples, self.nSteps)) self.sparseMStar[state] = self.sparseM[state].transpose(copy=True) self.factor = 2*np.ones(self.nSteps)",
"(self.seed != 0): np.random.seed(self.seed) # Read seeing power spectrum self.powerLites = np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1]",
"- \\ Q0**2 * np.sum(M2One * M2N) - Q0 * U0 * np.sum(M3One",
"lambdaValue = 0.000000051) # stI, stQ, stU, stV = out.demodulateTrivial() # print \"Q/I_original={0}",
"* self.backward(residual2, 1) + \\ 2.0 * U0 * betaU * self.backward(residual2, 2)",
"# stV/stI, out.stokes[3] / out.stokes[0]-stokes[3] / stokes[0]) # pl.close('all') # f, ax =",
"# pl.tight_layout() # ax[0,0].plot(out.times, out.signal[0]) # ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1]",
"t = 1.0 normL1 = [] normL2 = [] normL0 = [] for",
"# print \"U/I_original={0} - U/I_inferred={1} - U/I_trivial={2} - diff={3}\".format(out.stokes[2] / out.stokes[0], stokes[2] /",
"coefficients of the real signal \"\"\" out = fft.rfft(x) return out / np.sqrt(len(out))",
"A[0,0] = Q0**2 * np.sum(M2N**2) A[1,1] = U0**2 * np.sum(M3N**2) A[2,2] = V0**2",
"V0 * U0 * np.sum(M3One * M4N) - V0**2 * np.sum(M4One * M4N)",
"lambdaValue] = 0.0 return xPar def FISTA(self, initial=None, initialStokes=None, thresholdMethod='soft', niter=10, lambdaValue=1.0): \"\"\"",
"= np.sum(forwU**2) A[2,2] = np.sum(forwV**2) A[0,1] = np.sum(forwQ * forwU) A[1,0] = A[0,1]",
"j in range(1,4): temp += sign * self.signal[j] * self.modulation[j] self.signalIntegrated[i] = bin_ndarray(temp,",
"> 1.0): U0 = 1e-3 if (np.abs(V0) > 1.0): V0 = 1e-3 #",
"== 'soft'): xNew = self.softThreshold(y - self.mu * np.real(gradient), lambdaValue) xNew[0] = 0.0",
"* M3N) b[2] = 0.5 * V0 * np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\",
"* np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime = self.dtIntegration self.lengthSample = int(self.dtIntegration /",
"self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'hardPercentage'): xNew = self.hardThreshold(y",
"0.9 Q0 = 0.1 U0 = 0.2 V0 = 0.3 betaI = 10.0#self.beta[0]",
"noise = np.random.randn(self.nSteps) noiseFFT = myFFT(noise) self.powerSeeing = np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0] =",
"algorithm, that solves the following problem: argmin_O ||y - M*F^{-1}*alpha||_2 + \\lambda ||alpha||_1",
"= fft.irfft(x) return out * np.sqrt(len(out)) def myTotalPower(f): \"\"\" Return the power spectrum",
"beta = np.asarray([15.0, 100.0, 100., 100.0]) # stokes = np.asarray([1.0, 1.2e-3, 5.e-3, 0.001])",
"def FISTA(self, initial=None, initialStokes=None, thresholdMethod='soft', niter=10, lambdaValue=1.0): \"\"\" Solve the l1 regularized problem",
"1(t) M3One = self.forwardPartial(np.ones(self.nSteps), 2) # M3(t) * 1(t) M4One = self.forwardPartial(np.ones(self.nSteps), 3)",
"\"\"\" self.totalTime = totalTime self.dt = dt self.dtIntegration = dtIntegration self.seed = seed",
"= self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A =",
"into account some normalization Parameters ---------- x : float Fourier coefficients Returns -------",
"import scipy.fftpack as fft def bin_ndarray(ndarray, new_shape, operation='sum'): \"\"\" Bins an ndarray in",
"+ residual2) normSolutionL1 = np.linalg.norm(x, 1) normSolutionL0 = np.linalg.norm(x, 0) if (loop %",
"unity print 'Total variance = ', np.sum(self.seeing**2), myTotalPower(self.seeingFFT) # Compute the signal and",
"self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'hardPercentage'): xNew = self.hardThreshold(y - self.mu",
"FFT of a real signal taking into account some normalization Parameters ---------- x",
"= 0.0 self.seeingFFT = np.sqrt(self.powerSeeing) * noiseFFT self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing = myIFFT(self.seeingFFT)",
"in range(4): sparseData = [] sparseRow = [] sparseCol = [] loop =",
"A = np.zeros((3,3)) A[0,0] = np.sum(forwQ**2) A[1,1] = np.sum(forwU**2) A[2,2] = np.sum(forwV**2) A[0,1]",
"# ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21) # ax[2,1].semilogy(normL11) # ax[3,0].plot(out.signalIntegrated[0]) # ax[3,0].plot(out.signalIntegrated[1]) # ax[3,1].plot(out.seeing) #",
"betaV * self.backward(residual1, 3) residual2 = self.signalIntegrated[1] - (I0 * forwI - Q0",
"print \"V/I_original={0} - V/I_inferred={1} - V/I_trivial={2} - diff={3}\".format(out.stokes[3] / out.stokes[0], stokes[3] / stokes[0],",
"- V0 * forwV) gradient2 = -2.0 * I0 * betaI * self.backward(residual2,",
"M2N = self.forwardPartial(signal, 1) # M2(t) * N(t) M3N = self.forwardPartial(signal, 2) #",
"- V0**2 * np.sum(M4One * M4N) betaI = np.abs((0.5 * I0 * np.sum(M1N",
"self.signalToNoise = signalToNoise self.modulationType = modulationType if (self.seed != 0): np.random.seed(self.seed) # Read",
"d, c in zip(new_shape, ndarray.shape)] flattened = [l for p in compression_pairs for",
"lambdaValue / np.fmax(np.abs(x),1e-10)) * x def hardThreshold(self, x, lambdaValue): xPar = np.copy(x) xPar[np.abs(x)",
"'Q', 'U', 'V'] # loop = 0 # for loop in range(4): #",
": int, optional Description Returns ------- TYPE : Description \"\"\" self.totalTime = totalTime",
"(int, optional): number of iterations Returns: TYPE: Description \"\"\" if (initial == None):",
"V0 * forwV) gradient1 = -2.0 * I0 * betaI * self.backward(residual1, 0)",
"\\ # stV/stI, out.stokes[3] / out.stokes[0]-stokes[3] / stokes[0]) # pl.close('all') # f, ax",
"* z[0].conj() + 2 * np.sum(z[1:] * z[1:].conj())).real / len(z) def softThreshold(self, x,",
"stI, stQ, stU, stV = out.demodulateTrivial() # print \"Q/I_original={0} - Q/I_inferred={1} - Q/I_trivial={2}",
"'avg']: raise ValueError(\"Operation {} not supported.\".format(operation)) if ndarray.ndim != len(new_shape): raise ValueError(\"Shape mismatch:",
"3) residual2 = self.signalIntegrated[1] - (I0 * forwI - Q0 * forwQ -",
"- Q/I_inferred={1} - Q/I_trivial={2} - diff={3}\".format(out.stokes[1] / out.stokes[0], stokes[1] / stokes[0], \\ #",
"10.0#self.beta[1] betaU = 10.0#self.beta[2] betaV = 10.0#self.beta[3] else: x = np.copy(initial) I0, Q0,",
"in p] ndarray = ndarray.reshape(flattened) for i in range(len(new_shape)): if operation.lower() == \"sum\":",
"self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0] = 0.0 self.seeingFFT = np.sqrt(self.powerSeeing) * noiseFFT self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT))",
"A[0,2] = np.sum(forwQ * forwV) A[2,0] = A[0,2] A[1,2] = np.sum(forwU * forwV)",
"np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime = self.dtIntegration self.lengthSample = int(self.dtIntegration",
"M2(t) * N(t) M3N = self.forwardPartial(signal, 2) # M3(t) * N(t) M4N =",
"a signal Parameters ---------- f : float Signal Fourier coefficients Returns ------- float",
"totalTime : TYPE Description dt : TYPE Description dtIntegration : TYPE Description seed",
"* M2N) - Q0 * U0 * np.sum(M3One * M2N) - Q0 *",
"out.stokes[0]-stokes[1] / stokes[0]) # print \"U/I_original={0} - U/I_inferred={1} - U/I_trivial={2} - diff={3}\".format(out.stokes[2] /",
"np.sum(M2N**2) A[1,1] = U0**2 * np.sum(M3N**2) A[2,2] = V0**2 * np.sum(M4N**2) A[0,1] =",
"range(self.nSamples): for j in range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop) loop += 1 self.sparseM[state] =",
"self.sparseM[ray].dot(signal) def backward(self, z, ray): return self.factor * myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self, z): return",
"np.sqrt(myTotalPower(coefFourier)) # stokesPar = ['I', 'Q', 'U', 'V'] # loop = 0 #",
"noise with the appropriate power spectrum noise = np.random.randn(self.nSteps) noiseFFT = myFFT(noise) self.powerSeeing",
"= [None] * 4 for i in range(4): self.signal[i] = self.stokes[i]*(1.0 + self.beta[i]",
"ncols=4, figsize=(18,6)) # coefFourier[0] = 0.0 # Nt = myIFFT(coefFourier) # Nt /=",
"Solve the l1 regularized problem using the FISTA algorithm, that solves the following",
"* forwI - Q0 * forwQ - U0 * forwU - V0 *",
"betaV = 10.0#self.beta[3] else: x = np.copy(initial) I0, Q0, U0, V0 = initialStokes",
"# Nt /= np.sqrt(myTotalPower(coefFourier)) # stokesPar = ['I', 'Q', 'U', 'V'] # loop",
"= self.stokes[i]*(1.0 + self.beta[i] * self.seeing) # Generate modulation using a lambda/4 and",
"stU, stV = out.demodulateTrivial() # print \"Q/I_original={0} - Q/I_inferred={1} - Q/I_trivial={2} - diff={3}\".format(out.stokes[1]",
"- M*F^{-1}*alpha||_2 + \\lambda ||alpha||_1 Args: rank (int, optional): rank of the solution",
"= 0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) return I0,",
"self.backward(residual1, 2) - 2.0 * V0 * betaV * self.backward(residual1, 3) residual2 =",
"bin_ndarray(ndarray, new_shape, operation='sum'): \"\"\" Bins an ndarray in all axes based on the",
"summing or averaging. Number of output dimensions must match number of input dimensions.",
"initial=None, initialStokes=None, thresholdMethod='soft', niter=10, lambdaValue=1.0): \"\"\" Solve the l1 regularized problem using the",
"= Q0 * U0 * np.sum(M3N * M2N) A[1,0] = A[0,1] A[0,2] =",
"# ax[loop].plot(out.times, out.signal[loop]) # ax[loop].plot(out.times, stokes[loop] / stokes[0] * (1.0 + beta[loop]*Nt)) #",
"betaV * self.backward(residual2, 3) gradient = gradient1 + gradient2 if (thresholdMethod == 'hardLambda'):",
"= 0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) if (I0",
"self.powerLites[:,1] = 10.0**self.powerLites[:,1] # Number of samples of the original sample self.nSteps =",
"np.sum(M4One * M4N) betaI = np.abs((0.5 * I0 * np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1])) -",
"* betaQ * self.backward(residual2, 1) + \\ 2.0 * U0 * betaU *",
"n = bin_ndarray(m, new_shape=(5,5), operation='sum') >>> print(n) [[ 22 30 38 46 54]",
"Q0 * forwQ + U0 * forwU + V0 * forwV) gradient1 =",
": TYPE Description seed : int, optional Description Returns ------- TYPE : Description",
"/ stokes[0] *(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2] / stokes[0] * (1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3])",
"self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2)",
"m = np.arange(0,100,1).reshape((10,10)) >>> n = bin_ndarray(m, new_shape=(5,5), operation='sum') >>> print(n) [[ 22",
"[None] * 4 for i in range(4): self.signal[i] = self.stokes[i]*(1.0 + self.beta[i] *",
"2) + 2.0 * V0 * betaV * self.backward(residual2, 3) gradient = gradient1",
"output dimensions must match number of input dimensions. Example ------- >>> m =",
"sparseCol)), shape=(self.nSamples, self.nSteps)) self.sparseMStar[state] = self.sparseM[state].transpose(copy=True) self.factor = 2*np.ones(self.nSteps) self.factor[0] = 1.0 def",
"= sp.coo_matrix((sparseData, (sparseRow, sparseCol)), shape=(self.nSamples, self.nSteps)) self.sparseMStar[state] = self.sparseM[state].transpose(copy=True) self.factor = 2*np.ones(self.nSteps) self.factor[0]",
"= self.forwardPartial(signal, 2) # M3(t) * N(t) M4N = self.forwardPartial(signal, 3) # M4(t)",
"V0/I0, betaI, betaQ, betaU, betaV) normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0) return x, (I0, Q0, U0,",
": total power \"\"\" return f[0]**2 + 2.0*np.sum(f[1:]**2) class randomDemodulator(object): \"\"\"Summary Returns -------",
"U0 * np.sum(M3N * M2N) A[1,0] = A[0,1] A[0,2] = Q0 * V0",
"1.0 def forward(self, signal, beta, ray): return self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self, signal, ray): return",
"---------- x : float Fourier coefficients Returns ------- float : signal \"\"\" out",
"- bU={10:11.5f} - bV={11:11.5f}\".format(loop, normResidual, normSolutionL1, 100.0*normSolutionL0 / self.nSteps, I0, Q0/I0, U0/I0, V0/I0,",
"diff={3}\".format(out.stokes[3] / out.stokes[0], stokes[3] / stokes[0], \\ # stV/stI, out.stokes[3] / out.stokes[0]-stokes[3] /",
"new_shape, operation='sum'): \"\"\" Bins an ndarray in all axes based on the target",
"- U0 * forwU - V0 * forwV) gradient2 = -2.0 * I0",
"= dtIntegration self.seed = seed self.signalToNoise = signalToNoise self.modulationType = modulationType if (self.seed",
"myFFT(noise) self.powerSeeing = np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0] = 0.0 self.seeingFFT = np.sqrt(self.powerSeeing) *",
"* myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self, z): return (z[0] * z[0].conj() + 2 * np.sum(z[1:]",
"M2(t) * 1(t) M3One = self.forwardPartial(np.ones(self.nSteps), 2) # M3(t) * 1(t) M4One =",
"{}\".format(ndarray.shape, new_shape)) compression_pairs = [(d, c//d) for d, c in zip(new_shape, ndarray.shape)] flattened",
"spectrum of a signal Parameters ---------- f : float Signal Fourier coefficients Returns",
"* np.sum(M3One * M3N) - U0 * V0 * np.sum(M4One * M3N) b[2]",
"= fft.rfftfreq(self.nSteps, d=dt) # Betas and Stokes parameters self.beta = beta self.stokes =",
"* (xNew - x) t = tNew x = np.copy(xNew) normResidual = np.linalg.norm(residual1",
"[[ 22 30 38 46 54] [102 110 118 126 134] [182 190",
"= -2.0 * I0 * betaI * self.backward(residual2, 0) + 2.0 * Q0",
"- Q/I_trivial={2} - diff={3}\".format(out.stokes[1] / out.stokes[0], stokes[1] / stokes[0], \\ # stQ/stI, out.stokes[1]",
"= 0.5 * np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] = 0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1]))",
"2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType == 0): self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps)",
"0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) if (I0 <",
"+ gradient2 if (thresholdMethod == 'hardLambda'): xNew = self.hardThreshold(y - self.mu * np.real(gradient),",
"original sample self.nSteps = int(totalTime / dt) self.times = np.arange(self.nSteps) * self.dt #",
"for d, c in zip(new_shape, ndarray.shape)] flattened = [l for p in compression_pairs",
"float : total power \"\"\" return f[0]**2 + 2.0*np.sum(f[1:]**2) class randomDemodulator(object): \"\"\"Summary Returns",
"l1={2:10.4f} - l0={3:5.1f}% - I={4:11.5f} - Q/I={5:11.5f} - U/I={6:11.5f} - V/I={7:11.5f} - bI={8:11.5f}",
"= self.forwardPartial(signal, 0) # M1(t) * N(t) M2N = self.forwardPartial(signal, 1) # M2(t)",
"A[1,2] b = np.zeros(3) b[0] = 0.5 * np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] =",
"np.real(gradient), lambdaValue) if (thresholdMethod == 'soft'): xNew = self.softThreshold(y - self.mu * np.real(gradient),",
"lambdaValue): xPar = np.copy(x) xPar[np.abs(x) < lambdaValue] = 0.0 return xPar def FISTA(self,",
"U0/I0, V0/I0, betaI, betaQ, betaU, betaV) normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0) return x, (I0, Q0,",
"z[1:].conj())).real / len(z) def softThreshold(self, x, lambdaValue): return np.fmax(0,1.0 - lambdaValue / np.fmax(np.abs(x),1e-10))",
"- l0={3:5.1f}% - I={4:11.5f} - Q/I={5:11.5f} - U/I={6:11.5f} - V/I={7:11.5f} - bI={8:11.5f} -",
"* M1N)) / (I0**2 * np.sum(M1N**2))) betaQ, betaU, betaV = np.abs(np.linalg.solve(A,b)) if (loop",
"+ 2.0 * Q0 * betaQ * self.backward(residual2, 1) + \\ 2.0 *",
"dt self.dtIntegration = dtIntegration self.seed = seed self.signalToNoise = signalToNoise self.modulationType = modulationType",
"= y - self.mu * np.real(gradient) tNew = 0.5*(1+np.sqrt(1+4.0*t**2)) y = xNew +",
"elif operation.lower() in [\"mean\", \"average\", \"avg\"]: ndarray = ndarray.mean(-1*(i+1)) return ndarray def myFFT(x):",
"real signal \"\"\" out = fft.rfft(x) return out / np.sqrt(len(out)) def myIFFT(x): \"\"\"",
"loop = 0 for i in range(self.nSamples): for j in range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i)",
"out.stokes[1] / out.stokes[0]-stokes[1] / stokes[0]) # print \"U/I_original={0} - U/I_inferred={1} - U/I_trivial={2} -",
"niter (int, optional): number of iterations Returns: TYPE: Description \"\"\" if (initial ==",
"# M3(t) * 1(t) M4One = self.forwardPartial(np.ones(self.nSteps), 3) # M4(t) * 1(t) A",
"c in zip(new_shape, ndarray.shape)] flattened = [l for p in compression_pairs for l",
"= [None] * 2 for i in range(2): temp = self.signal[0] * self.modulation[0]",
"dt : TYPE Description dtIntegration : TYPE Description seed : int, optional Description",
"np.sum(M1N**2))) betaQ, betaU, betaV = np.abs(np.linalg.solve(A,b)) if (loop % 50 == 0): print",
"Q0 = 0.1 U0 = 0.2 V0 = 0.3 betaI = 10.0#self.beta[0] betaQ",
"- U/I={6:11.5f} - V/I={7:11.5f} - bI={8:11.5f} - bQ={9:11.5f} - bU={10:11.5f} - bV={11:11.5f}\".format(loop, normResidual,",
"self.dtIntegration # Generate modulation matrix self.sparseM = [None] * 4 self.sparseMStar = [None]",
"= [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType == 0): self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation",
"dt, dtIntegration, stokes, beta, signalToNoise=0.0, seed=0, modulationType=0): \"\"\"Summary Parameters ---------- totalTime : TYPE",
"np.abs(np.linalg.solve(A,b)) if (loop % 50 == 0): print \"It {0:4d} - l2={1:10.3e} -",
"\"average\", \"avg\"]: ndarray = ndarray.mean(-1*(i+1)) return ndarray def myFFT(x): \"\"\" Return the FFT",
"= 1e-3 if (np.abs(V0) > 1.0): V0 = 1e-3 # Seeing amplitude M1N",
"0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A = np.zeros((3,3)) A[0,0] = np.sum(forwQ**2)",
"power spectrum # to generate the noise with the appropriate power spectrum noise",
"the real signal \"\"\" out = fft.rfft(x) return out / np.sqrt(len(out)) def myIFFT(x):",
"np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A = np.zeros((3,3)) A[0,0] = np.sum(forwQ**2) A[1,1] =",
"print 'Total variance = ', np.sum(self.seeing**2), myTotalPower(self.seeingFFT) # Compute the signal and its",
"return (z[0] * z[0].conj() + 2 * np.sum(z[1:] * z[1:].conj())).real / len(z) def",
"lambdaValue) if (thresholdMethod == 'hardPercentage'): xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue)",
"number of iterations Returns: TYPE: Description \"\"\" if (initial == None): x =",
"power spectrum self.signal = [None] * 4 for i in range(4): self.signal[i] =",
"V0 = np.linalg.solve(A,b) if (I0 < 0): I0 = 1.0 if (np.abs(Q0) >",
"0.001]) # out = randomDemodulator(totalTime, dt, dtIntegration, stokes, beta, seed=123, signalToNoise=1e3) # coefFourier,",
"Read seeing power spectrum self.powerLites = np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] = 10.0**self.powerLites[:,1] # Number of",
"np.sqrt(self.powerSeeing) * noiseFFT self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing = myIFFT(self.seeingFFT) # Make sure that",
"of the solution niter (int, optional): number of iterations Returns: TYPE: Description \"\"\"",
"variance and multiply by the square root of the power spectrum # to",
"* betaQ * self.backward(residual1, 1) - \\ 2.0 * U0 * betaU *",
"* self.backward(residual2, 0) + 2.0 * Q0 * betaQ * self.backward(residual2, 1) +",
"1(t) M4One = self.forwardPartial(np.ones(self.nSteps), 3) # M4(t) * 1(t) A = np.zeros((3,3)) A[0,0]",
"signal \"\"\" out = fft.irfft(x) return out * np.sqrt(len(out)) def myTotalPower(f): \"\"\" Return",
"myIFFT(x): \"\"\" Return the IFFT for a real signal taking into account some",
"gradient1 + gradient2 if (thresholdMethod == 'hardLambda'): xNew = self.hardThreshold(y - self.mu *",
"an ndarray in all axes based on the target shape, by summing or",
"A[0,1] A[0,2] = Q0 * V0 * np.sum(M4N * M2N) A[2,0] = A[0,2]",
"# ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1] / stokes[0] *(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2] / stokes[0]",
"seeing power spectrum self.powerLites = np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] = 10.0**self.powerLites[:,1] # Number of samples",
"fft.rfftfreq(self.nSteps, d=dt) # Betas and Stokes parameters self.beta = beta self.stokes = stokes",
"np.sum(M4N * M2N) A[2,0] = A[0,2] A[1,2] = U0 * V0 * np.sum(M4N",
"(I0**2 * np.sum(M1N**2))) betaQ, betaU, betaV = np.abs(np.linalg.solve(A,b)) if (loop % 50 ==",
"Description Returns ------- TYPE : Description \"\"\" self.totalTime = totalTime self.dt = dt",
"return np.fmax(0,1.0 - lambdaValue / np.fmax(np.abs(x),1e-10)) * x def hardThreshold(self, x, lambdaValue): xPar",
"- bQ={9:11.5f} - bU={10:11.5f} - bV={11:11.5f}\".format(loop, normResidual, normSolutionL1, 100.0*normSolutionL0 / self.nSteps, I0, Q0/I0,",
"s # dt = 0.001 # s # dtIntegration = 0.01 #s #",
"Generate modulation using a lambda/4 and lambda/2 polarimeter with random angles # self.modulation",
"or averaging. Number of output dimensions must match number of input dimensions. Example",
"* N(t) M3N = self.forwardPartial(signal, 2) # M3(t) * N(t) M4N = self.forwardPartial(signal,",
"* np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) if (I0 < 0):",
"Frequency axis self.freq = fft.rfftfreq(self.nSteps, d=dt) # Betas and Stokes parameters self.beta =",
"# out = randomDemodulator(totalTime, dt, dtIntegration, stokes, beta, seed=123, signalToNoise=1e3) # coefFourier, stokes,",
"1e-3 if (np.abs(V0) > 1.0): V0 = 1e-3 # Seeing amplitude M1N =",
"= 0.01 #s # beta = np.asarray([15.0, 100.0, 100., 100.0]) # stokes =",
"not supported.\".format(operation)) if ndarray.ndim != len(new_shape): raise ValueError(\"Shape mismatch: {} -> {}\".format(ndarray.shape, new_shape))",
"operation.lower() in [\"mean\", \"average\", \"avg\"]: ndarray = ndarray.mean(-1*(i+1)) return ndarray def myFFT(x): \"\"\"",
"range(2): temp = self.signal[0] * self.modulation[0] sign = (-1.0)**i for j in range(1,4):",
"* 4 for state in range(4): sparseData = [] sparseRow = [] sparseCol",
"= signalToNoise self.modulationType = modulationType if (self.seed != 0): np.random.seed(self.seed) # Read seeing",
"A[0,2] A[1,2] = U0 * V0 * np.sum(M4N * M3N) A[2,1] = A[1,2]",
"normSolutionL0 = np.linalg.norm(x, 0) if (loop % 10): # Stokes parameters I0 =",
"x) t = tNew x = np.copy(xNew) normResidual = np.linalg.norm(residual1 + residual2) normSolutionL1",
"M2(t) * (1+betaQ*N(t)) forwU = self.forward(signal, betaU, 2) # M3(t) * (1+betaU*N(t)) forwV",
"- self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'soft'): xNew = self.softThreshold(y -",
"x def hardThreshold(self, x, lambdaValue): xPar = np.copy(x) xPar[np.abs(x) < lambdaValue] = 0.0",
"214] [262 270 278 286 294] [342 350 358 366 374]] \"\"\" if",
"ndarray.reshape(flattened) for i in range(len(new_shape)): if operation.lower() == \"sum\": ndarray = ndarray.sum(-1*(i+1)) elif",
"/ stokes[0] * (1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21) # ax[2,1].semilogy(normL11) #",
"Q0 * V0 * np.sum(M4N * M2N) A[2,0] = A[0,2] A[1,2] = U0",
"2) - 2.0 * V0 * betaV * self.backward(residual1, 3) residual2 = self.signalIntegrated[1]",
"np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] = 0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0",
"M3(t) * 1(t) M4One = self.forwardPartial(np.ones(self.nSteps), 3) # M4(t) * 1(t) A =",
"which='LM', return_eigenvectors=False) self.mu = 0.5 / (np.real(largestEigenvalue)) * 0.0002 t = 1.0 normL1",
"4 for i in range(4): self.signal[i] = self.stokes[i]*(1.0 + self.beta[i] * self.seeing) #",
"== 'hardLambda'): xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod ==",
"sparseCol = [] loop = 0 for i in range(self.nSamples): for j in",
"ndarray = ndarray.reshape(flattened) for i in range(len(new_shape)): if operation.lower() == \"sum\": ndarray =",
"- V/I_trivial={2} - diff={3}\".format(out.stokes[3] / out.stokes[0], stokes[3] / stokes[0], \\ # stV/stI, out.stokes[3]",
"normL0.append(normSolutionL0) return x, (I0, Q0, U0, V0), (betaI, betaQ, betaU, betaV), normL2, normL1,",
"coefFourier[0] = 0.0 # Nt = myIFFT(coefFourier) # Nt /= np.sqrt(myTotalPower(coefFourier)) # stokesPar",
"M4One = self.forwardPartial(np.ones(self.nSteps), 3) # M4(t) * 1(t) A = np.zeros((3,3)) A[0,0] =",
"* (1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21) # ax[2,1].semilogy(normL11) # ax[3,0].plot(out.signalIntegrated[0]) #",
"betaQ, betaU, betaV) normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0) return x, (I0, Q0, U0, V0), (betaI,",
"problem using the FISTA algorithm, that solves the following problem: argmin_O ||y -",
"forwQ - U0 * forwU - V0 * forwV) gradient2 = -2.0 *",
"return self.sparseM[ray].dot(signal) def backward(self, z, ray): return self.factor * myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self, z):",
"optional Description Returns ------- TYPE : Description \"\"\" self.totalTime = totalTime self.dt =",
"---------- x : float Signal time series Returns ------- float : Fourier coefficients",
"return out / np.sqrt(len(out)) def myIFFT(x): \"\"\" Return the IFFT for a real",
"self.seeing) # Generate modulation using a lambda/4 and lambda/2 polarimeter with random angles",
"self.signalIntegrated = [None] * 2 for i in range(2): temp = self.signal[0] *",
"TYPE Description dt : TYPE Description dtIntegration : TYPE Description seed : int,",
"scipy.sparse.linalg as splinalg import scipy.fftpack as fft def bin_ndarray(ndarray, new_shape, operation='sum'): \"\"\" Bins",
"myTotalPower(self.seeingFFT) # Compute the signal and its power spectrum self.signal = [None] *",
"return out * np.sqrt(len(out)) def myTotalPower(f): \"\"\" Return the power spectrum of a",
"out.stokes[0], stokes[2] / stokes[0], \\ # stU/stI, out.stokes[2] / out.stokes[0]-stokes[2] / stokes[0]) #",
"1(t) A = np.zeros((3,3)) A[0,0] = Q0**2 * np.sum(M2N**2) A[1,1] = U0**2 *",
"b[2] = 0.5 * V0 * np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ V0 *",
"self.sparseMStar[state] = self.sparseM[state].transpose(copy=True) self.factor = 2*np.ones(self.nSteps) self.factor[0] = 1.0 def forward(self, signal, beta,",
"float : signal \"\"\" out = fft.irfft(x) return out * np.sqrt(len(out)) def myTotalPower(f):",
"self.forwardPartial(signal, 3) # M4(t) * N(t) M1One = self.forwardPartial(np.ones(self.nSteps), 0) # M1(t) *",
"= 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps) else: temp = np.load('alphaBetaSamples.npz') self.alphaModulation = temp['arr_0'][0:self.nSteps] self.betaModulation",
"[None] * 4 self.sparseMStar = [None] * 4 for state in range(4): sparseData",
"splinalg.eigsh(res, k=1, which='LM', return_eigenvectors=False) self.mu = 0.5 / (np.real(largestEigenvalue)) * 0.0002 t =",
"* np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ Q0**2 * np.sum(M2One * M2N) - Q0",
"* np.random.randn(self.nSamples) self.tIntegrated = np.arange(self.nSamples) * self.dtIntegration # Generate modulation matrix self.sparseM =",
"gradient2 = -2.0 * I0 * betaI * self.backward(residual2, 0) + 2.0 *",
"= np.linalg.norm(x, 1) normSolutionL0 = np.linalg.norm(x, 0) if (loop % 10): # Stokes",
"Q0 * U0 * np.sum(M3One * M2N) - Q0 * V0 * np.sum(M4One",
"the power spectrum # to generate the noise with the appropriate power spectrum",
"np.sqrt(len(out)) def myTotalPower(f): \"\"\" Return the power spectrum of a signal Parameters ----------",
"1e-3 if (np.abs(U0) > 1.0): U0 = 1e-3 if (np.abs(V0) > 1.0): V0",
"self.forwardPartial(np.ones(self.nSteps), 1) # M2(t) * 1(t) M3One = self.forwardPartial(np.ones(self.nSteps), 2) # M3(t) *",
"FISTA(self, initial=None, initialStokes=None, thresholdMethod='soft', niter=10, lambdaValue=1.0): \"\"\" Solve the l1 regularized problem using",
"V0 * np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ V0 * Q0 * np.sum(M2One *",
"I0 = 1.0 if (np.abs(Q0) > 1.0): Q0 = 1e-3 if (np.abs(U0) >",
"totalTime, dt, dtIntegration, stokes, beta, signalToNoise=0.0, seed=0, modulationType=0): \"\"\"Summary Parameters ---------- totalTime :",
"bin_ndarray(temp, (self.nSamples,), operation='sum') self.signalIntegrated[i] += np.mean(self.signalIntegrated[i]) / self.signalToNoise * np.random.randn(self.nSamples) self.tIntegrated = np.arange(self.nSamples)",
"stokesPar = ['I', 'Q', 'U', 'V'] # loop = 0 # for loop",
"\\ Q0**2 * np.sum(M2One * M2N) - Q0 * U0 * np.sum(M3One *",
"# stokes = np.asarray([1.0, 1.2e-3, 5.e-3, 0.001]) # out = randomDemodulator(totalTime, dt, dtIntegration,",
"self.forward(signal, betaV, 3) # M4(t) * (1+betaV*N(t)) residual1 = self.signalIntegrated[0] - (I0 *",
"- Q0 * forwQ - U0 * forwU - V0 * forwV) gradient2",
"= 0.1 U0 = 0.2 V0 = 0.3 betaI = 10.0#self.beta[0] betaQ =",
"sparseData = [] sparseRow = [] sparseCol = [] loop = 0 for",
"betaI = np.abs((0.5 * I0 * np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1])) - \\ I0**2 *",
"= np.copy(xNew) normResidual = np.linalg.norm(residual1 + residual2) normSolutionL1 = np.linalg.norm(x, 1) normSolutionL0 =",
"coefFourier, stokes, beta, normL21, normL11 = out.FISTA(thresholdMethod = 'soft', niter = 600, lambdaValue",
"k=1, which='LM', return_eigenvectors=False) self.mu = 0.5 / (np.real(largestEigenvalue)) * 0.0002 t = 1.0",
"axes based on the target shape, by summing or averaging. Number of output",
"normL1.append(normSolutionL1) normL0.append(normSolutionL0) return x, (I0, Q0, U0, V0), (betaI, betaQ, betaU, betaV), normL2,",
"i in range(4): self.signal[i] = self.stokes[i]*(1.0 + self.beta[i] * self.seeing) # Generate modulation",
"(I0 * forwI - Q0 * forwQ - U0 * forwU - V0",
"signals together \"\"\" def __init__(self, totalTime, dt, dtIntegration, stokes, beta, signalToNoise=0.0, seed=0, modulationType=0):",
"* 4 for i in range(4): self.signal[i] = self.stokes[i]*(1.0 + self.beta[i] * self.seeing)",
"ndarray.shape)] flattened = [l for p in compression_pairs for l in p] ndarray",
"# ax[loop].annotate # pl.tight_layout() # ax[0,0].plot(out.times, out.signal[0]) # ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1])",
"M2N) - Q0 * U0 * np.sum(M3One * M2N) - Q0 * V0",
"= 0 # for loop in range(4): # ax[loop].plot(out.times, out.signal[loop]) # ax[loop].plot(out.times, stokes[loop]",
"the signal and its power spectrum self.signal = [None] * 4 for i",
"1 self.sparseM[state] = sp.coo_matrix((sparseData, (sparseRow, sparseCol)), shape=(self.nSamples, self.nSteps)) self.sparseMStar[state] = self.sparseM[state].transpose(copy=True) self.factor =",
"= V0**2 * np.sum(M4N**2) A[0,1] = Q0 * U0 * np.sum(M3N * M2N)",
"np.asarray([1.0, 1.2e-3, 5.e-3, 0.001]) # out = randomDemodulator(totalTime, dt, dtIntegration, stokes, beta, seed=123,",
"coefficients Returns ------- float : signal \"\"\" out = fft.irfft(x) return out *",
"None): x = np.zeros(self.nSteps) I0 = 0.9 Q0 = 0.1 U0 = 0.2",
"len(new_shape): raise ValueError(\"Shape mismatch: {} -> {}\".format(ndarray.shape, new_shape)) compression_pairs = [(d, c//d) for",
"np.zeros(3) b[0] = 0.5 * np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] = 0.5 * np.sum(forwU",
"# M3(t) * (1+betaU*N(t)) forwV = self.forward(signal, betaV, 3) # M4(t) * (1+betaV*N(t))",
"betaU, betaV) normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0) return x, (I0, Q0, U0, V0), (betaI, betaQ,",
"(np.real(largestEigenvalue)) * 0.0002 t = 1.0 normL1 = [] normL2 = [] normL0",
"Returns ------- TYPE : Description \"\"\" self.totalTime = totalTime self.dt = dt self.dtIntegration",
"= [(d, c//d) for d, c in zip(new_shape, ndarray.shape)] flattened = [l for",
"Returns: TYPE: Description \"\"\" if (initial == None): x = np.zeros(self.nSteps) I0 =",
"0.5*np.pi*np.random.rand(self.nSteps) else: temp = np.load('alphaBetaSamples.npz') self.alphaModulation = temp['arr_0'][0:self.nSteps] self.betaModulation = temp['arr_1'][0:self.nSteps] self.modulation =",
"/ (np.real(largestEigenvalue)) * 0.0002 t = 1.0 normL1 = [] normL2 = []",
"stokes[0], \\ # stV/stI, out.stokes[3] / out.stokes[0]-stokes[3] / stokes[0]) # pl.close('all') # f,",
"class randomDemodulator(object): \"\"\"Summary Returns ------- TYPE : Demodulate I and Q signals together",
"range(1,4): temp += sign * self.signal[j] * self.modulation[j] self.signalIntegrated[i] = bin_ndarray(temp, (self.nSamples,), operation='sum')",
"= self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) /",
"i in range(len(new_shape)): if operation.lower() == \"sum\": ndarray = ndarray.sum(-1*(i+1)) elif operation.lower() in",
"* M2N) A[2,0] = A[0,2] A[1,2] = U0 * V0 * np.sum(M4N *",
"* 0.0002 t = 1.0 normL1 = [] normL2 = [] normL0 =",
"4 self.sparseMStar = [None] * 4 for state in range(4): sparseData = []",
"[182 190 198 206 214] [262 270 278 286 294] [342 350 358",
"ray): return self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self, signal, ray): return self.sparseM[ray].dot(signal) def backward(self, z, ray):",
"Signal time series Returns ------- float : Fourier coefficients of the real signal",
"* np.sqrt(len(out)) def myTotalPower(f): \"\"\" Return the power spectrum of a signal Parameters",
"110 118 126 134] [182 190 198 206 214] [262 270 278 286",
"matplotlib.pyplot as pl import scipy.sparse as sp import scipy.sparse.linalg as splinalg import scipy.fftpack",
"/ tNew * (xNew - x) t = tNew x = np.copy(xNew) normResidual",
"bin_ndarray(m, new_shape=(5,5), operation='sum') >>> print(n) [[ 22 30 38 46 54] [102 110",
"def forwardPartial(self, signal, ray): return self.sparseM[ray].dot(signal) def backward(self, z, ray): return self.factor *",
"A[1,1] = U0**2 * np.sum(M3N**2) A[2,2] = V0**2 * np.sum(M4N**2) A[0,1] = Q0",
"self.modulationType = modulationType if (self.seed != 0): np.random.seed(self.seed) # Read seeing power spectrum",
"= 1.0 # s # dt = 0.001 # s # dtIntegration =",
"\\ np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime = self.dtIntegration self.lengthSample =",
"= np.asarray([15.0, 100.0, 100., 100.0]) # stokes = np.asarray([1.0, 1.2e-3, 5.e-3, 0.001]) #",
"Return the power spectrum of a signal Parameters ---------- f : float Signal",
"for l in p] ndarray = ndarray.reshape(flattened) for i in range(len(new_shape)): if operation.lower()",
"b = np.zeros(3) b[0] = 0.5 * Q0 * np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1])) -",
"bV={11:11.5f}\".format(loop, normResidual, normSolutionL1, 100.0*normSolutionL0 / self.nSteps, I0, Q0/I0, U0/I0, V0/I0, betaI, betaQ, betaU,",
"normL0 = [] for loop in range(niter): signal = myIFFT(x) forwI = self.forward(signal,",
"A[2,0] = A[0,2] A[1,2] = np.sum(forwU * forwV) A[2,1] = A[1,2] b =",
"10.0**self.powerLites[:,1] # Number of samples of the original sample self.nSteps = int(totalTime /",
"mismatch: {} -> {}\".format(ndarray.shape, new_shape)) compression_pairs = [(d, c//d) for d, c in",
"\"It {0:4d} - l2={1:10.3e} - l1={2:10.4f} - l0={3:5.1f}% - I={4:11.5f} - Q/I={5:11.5f} -",
"forwQ + U0 * forwU + V0 * forwV) gradient1 = -2.0 *",
"forwardPartial(self, signal, ray): return self.sparseM[ray].dot(signal) def backward(self, z, ray): return self.factor * myFFT(self.sparseMStar[ray].dot(z))",
"V0), (betaI, betaQ, betaU, betaV), normL2, normL1, normL0 def demodulateTrivial(self): forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0)",
"* (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) return I0, Q0, U0, V0 #",
"(1.0 + beta[loop]*Nt)) # ax[loop].set_xlabel('Time [s]') # ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) # ax[loop].annotate # pl.tight_layout()",
"new_shape=(5,5), operation='sum') >>> print(n) [[ 22 30 38 46 54] [102 110 118",
"rank (int, optional): rank of the solution niter (int, optional): number of iterations",
"* np.sum(M4N * M3N) A[2,1] = A[1,2] b = np.zeros(3) b[0] = 0.5",
"in all axes based on the target shape, by summing or averaging. Number",
": float Signal Fourier coefficients Returns ------- float : total power \"\"\" return",
"np.random.seed(self.seed) # Read seeing power spectrum self.powerLites = np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] = 10.0**self.powerLites[:,1] #",
"* (1+betaI*N(t)) forwQ = self.forward(signal, betaQ, 1) # M2(t) * (1+betaQ*N(t)) forwU =",
"0 for i in range(self.nSamples): for j in range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop) loop",
"118 126 134] [182 190 198 206 214] [262 270 278 286 294]",
"b = np.zeros(3) b[0] = 0.5 * np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] = 0.5",
"= np.random.randn(self.nSteps) noiseFFT = myFFT(noise) self.powerSeeing = np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0] = 0.0",
"Seeing amplitude M1N = self.forwardPartial(signal, 0) # M1(t) * N(t) M2N = self.forwardPartial(signal,",
"self.backward(residual2, 1) + \\ 2.0 * U0 * betaU * self.backward(residual2, 2) +",
"self.factor = 2*np.ones(self.nSteps) self.factor[0] = 1.0 def forward(self, signal, beta, ray): return self.sparseM[ray].dot(1.0+beta*signal)",
"* np.sum(M2N**2) A[1,1] = U0**2 * np.sum(M3N**2) A[2,2] = V0**2 * np.sum(M4N**2) A[0,1]",
"# ax[loop].plot(out.times, stokes[loop] / stokes[0] * (1.0 + beta[loop]*Nt)) # ax[loop].set_xlabel('Time [s]') #",
"spectrum noise = np.random.randn(self.nSteps) noiseFFT = myFFT(noise) self.powerSeeing = np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0]",
"temp = self.signal[0] * self.modulation[0] sign = (-1.0)**i for j in range(1,4): temp",
"forwV) A[2,1] = A[1,2] b = np.zeros(3) b[0] = 0.5 * np.sum(forwQ *",
"stokes[0]) # print \"U/I_original={0} - U/I_inferred={1} - U/I_trivial={2} - diff={3}\".format(out.stokes[2] / out.stokes[0], stokes[2]",
"thresholdMethod='soft', niter=10, lambdaValue=1.0): \"\"\" Solve the l1 regularized problem using the FISTA algorithm,",
"self.nSteps) self.signalIntegrated = [None] * 2 for i in range(2): temp = self.signal[0]",
"range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop) loop += 1 self.sparseM[state] = sp.coo_matrix((sparseData, (sparseRow, sparseCol)), shape=(self.nSamples,",
"multiply by the square root of the power spectrum # to generate the",
"self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A = np.zeros((3,3))",
"seed=123, signalToNoise=1e3) # coefFourier, stokes, beta, normL21, normL11 = out.FISTA(thresholdMethod = 'soft', niter",
"0) if (loop % 10): # Stokes parameters I0 = 0.5 * np.sum(forwI",
"M1One = self.forwardPartial(np.ones(self.nSteps), 0) # M1(t) * 1(t) M2One = self.forwardPartial(np.ones(self.nSteps), 1) #",
"averaging. Number of output dimensions must match number of input dimensions. Example -------",
"d=dt) # Betas and Stokes parameters self.beta = beta self.stokes = stokes #",
"l0={3:5.1f}% - I={4:11.5f} - Q/I={5:11.5f} - U/I={6:11.5f} - V/I={7:11.5f} - bI={8:11.5f} - bQ={9:11.5f}",
"some normalization Parameters ---------- x : float Fourier coefficients Returns ------- float :",
"# stI, stQ, stU, stV = out.demodulateTrivial() # print \"Q/I_original={0} - Q/I_inferred={1} -",
"(I0, Q0, U0, V0), (betaI, betaQ, betaU, betaV), normL2, normL1, normL0 def demodulateTrivial(self):",
"# s # dt = 0.001 # s # dtIntegration = 0.01 #s",
"Stokes parameters I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A =",
"= int(totalTime / dt) self.times = np.arange(self.nSteps) * self.dt # Frequency axis self.freq",
"np.sqrt(len(out)) def myIFFT(x): \"\"\" Return the IFFT for a real signal taking into",
"stokes, beta, normL21, normL11 = out.FISTA(thresholdMethod = 'soft', niter = 600, lambdaValue =",
"V0 * np.sum(M4One * M2N) b[1] = 0.5 * U0 * np.sum(M3N *",
"= (-1.0)**i for j in range(1,4): temp += sign * self.signal[j] * self.modulation[j]",
"= self.sparseM[state].transpose(copy=True) self.factor = 2*np.ones(self.nSteps) self.factor[0] = 1.0 def forward(self, signal, beta, ray):",
"A[1,1] = np.sum(forwU**2) A[2,2] = np.sum(forwV**2) A[0,1] = np.sum(forwQ * forwU) A[1,0] =",
"xPar def FISTA(self, initial=None, initialStokes=None, thresholdMethod='soft', niter=10, lambdaValue=1.0): \"\"\" Solve the l1 regularized",
"initialStokes xNew = np.copy(x) y = np.copy(x) res = self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue = splinalg.eigsh(res,",
"betaI, 0) # M1(t) * (1+betaI*N(t)) forwQ = self.forward(signal, betaQ, 1) # M2(t)",
"myIFFT(x) forwI = self.forward(signal, betaI, 0) # M1(t) * (1+betaI*N(t)) forwQ = self.forward(signal,",
"A[2,2] = V0**2 * np.sum(M4N**2) A[0,1] = Q0 * U0 * np.sum(M3N *",
"np.sum(M3One * M2N) - Q0 * V0 * np.sum(M4One * M2N) b[1] =",
"Gaussian noise with unit variance and multiply by the square root of the",
"self.mu * np.real(gradient) tNew = 0.5*(1+np.sqrt(1+4.0*t**2)) y = xNew + (t-1.0) / tNew",
"residual2 = self.signalIntegrated[1] - (I0 * forwI - Q0 * forwQ - U0",
"return ndarray def myFFT(x): \"\"\" Return the FFT of a real signal taking",
"- 2.0 * Q0 * betaQ * self.backward(residual1, 1) - \\ 2.0 *",
"= np.sum(forwQ * forwU) A[1,0] = A[0,1] A[0,2] = np.sum(forwQ * forwV) A[2,0]",
"myIFFT(self.seeingFFT) # Make sure that the total power is unity print 'Total variance",
"/ np.fmax(np.abs(x),1e-10)) * x def hardThreshold(self, x, lambdaValue): xPar = np.copy(x) xPar[np.abs(x) <",
"+ \\ 2.0 * U0 * betaU * self.backward(residual2, 2) + 2.0 *",
"= np.linalg.norm(x, 0) if (loop % 10): # Stokes parameters I0 = 0.5",
"in range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop) loop += 1 self.sparseM[state] = sp.coo_matrix((sparseData, (sparseRow, sparseCol)),",
"------- float : total power \"\"\" return f[0]**2 + 2.0*np.sum(f[1:]**2) class randomDemodulator(object): \"\"\"Summary",
"gradient1 = -2.0 * I0 * betaI * self.backward(residual1, 0) - 2.0 *",
"* self.dt # Frequency axis self.freq = fft.rfftfreq(self.nSteps, d=dt) # Betas and Stokes",
"l in p] ndarray = ndarray.reshape(flattened) for i in range(len(new_shape)): if operation.lower() ==",
"= A[1,2] b = np.zeros(3) b[0] = 0.5 * np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1]",
"0.0 return xPar def FISTA(self, initial=None, initialStokes=None, thresholdMethod='soft', niter=10, lambdaValue=1.0): \"\"\" Solve the",
"* self.dtIntegration # Generate modulation matrix self.sparseM = [None] * 4 self.sparseMStar =",
"== 0): print \"It {0:4d} - l2={1:10.3e} - l1={2:10.4f} - l0={3:5.1f}% - I={4:11.5f}",
"= 1e-3 # Seeing amplitude M1N = self.forwardPartial(signal, 0) # M1(t) * N(t)",
"the FISTA algorithm, that solves the following problem: argmin_O ||y - M*F^{-1}*alpha||_2 +",
"loop in range(niter): signal = myIFFT(x) forwI = self.forward(signal, betaI, 0) # M1(t)",
"2.0 * U0 * betaU * self.backward(residual1, 2) - 2.0 * V0 *",
"* x def hardThreshold(self, x, lambdaValue): xPar = np.copy(x) xPar[np.abs(x) < lambdaValue] =",
"I0 * betaI * self.backward(residual2, 0) + 2.0 * Q0 * betaQ *",
"* (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A = np.zeros((3,3)) A[0,0] = np.sum(forwQ**2) A[1,1] = np.sum(forwU**2)",
"/ out.stokes[0], stokes[2] / stokes[0], \\ # stU/stI, out.stokes[2] / out.stokes[0]-stokes[2] / stokes[0])",
"np.real(gradient), lambdaValue) xNew[0] = 0.0 xNew /= np.sqrt(myTotalPower(xNew)) if (thresholdMethod == 'L2'): xNew",
"import scipy.sparse as sp import scipy.sparse.linalg as splinalg import scipy.fftpack as fft def",
"# Compute the signal and its power spectrum self.signal = [None] * 4",
"M4N) betaI = np.abs((0.5 * I0 * np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1])) - \\ I0**2",
"0.5 * V0 * np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ V0 * Q0 *",
"fft def bin_ndarray(ndarray, new_shape, operation='sum'): \"\"\" Bins an ndarray in all axes based",
"x = np.zeros(self.nSteps) I0 = 0.9 Q0 = 0.1 U0 = 0.2 V0",
"s # dtIntegration = 0.01 #s # beta = np.asarray([15.0, 100.0, 100., 100.0])",
"* self.backward(residual1, 0) - 2.0 * Q0 * betaQ * self.backward(residual1, 1) -",
"self.nSteps)) self.sparseMStar[state] = self.sparseM[state].transpose(copy=True) self.factor = 2*np.ones(self.nSteps) self.factor[0] = 1.0 def forward(self, signal,",
"= bin_ndarray(m, new_shape=(5,5), operation='sum') >>> print(n) [[ 22 30 38 46 54] [102",
"self.forwardPartial(signal, 2) # M3(t) * N(t) M4N = self.forwardPartial(signal, 3) # M4(t) *",
"sparseCol.append(loop) loop += 1 self.sparseM[state] = sp.coo_matrix((sparseData, (sparseRow, sparseCol)), shape=(self.nSamples, self.nSteps)) self.sparseMStar[state] =",
"M4(t) * (1+betaV*N(t)) residual1 = self.signalIntegrated[0] - (I0 * forwI + Q0 *",
"- x) t = tNew x = np.copy(xNew) normResidual = np.linalg.norm(residual1 + residual2)",
"l1 regularized problem using the FISTA algorithm, that solves the following problem: argmin_O",
"normL11 = out.FISTA(thresholdMethod = 'soft', niter = 600, lambdaValue = 0.000000051) # stI,",
"seed : int, optional Description Returns ------- TYPE : Description \"\"\" self.totalTime =",
"stokes[2] / stokes[0], \\ # stU/stI, out.stokes[2] / out.stokes[0]-stokes[2] / stokes[0]) # print",
"lambdaValue) xNew[0] = 0.0 xNew /= np.sqrt(myTotalPower(xNew)) if (thresholdMethod == 'L2'): xNew =",
"np.sum(forwV**2) A[0,1] = np.sum(forwQ * forwU) A[1,0] = A[0,1] A[0,2] = np.sum(forwQ *",
"ax[0,0].plot(out.times, out.signal[0]) # ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1] / stokes[0] *(1.0+beta[1]*Nt))",
"* self.backward(residual1, 3) residual2 = self.signalIntegrated[1] - (I0 * forwI - Q0 *",
"stU/stI, out.stokes[2] / out.stokes[0]-stokes[2] / stokes[0]) # print \"V/I_original={0} - V/I_inferred={1} - V/I_trivial={2}",
"Generate modulation matrix self.sparseM = [None] * 4 self.sparseMStar = [None] * 4",
"solution niter (int, optional): number of iterations Returns: TYPE: Description \"\"\" if (initial",
"c//d) for d, c in zip(new_shape, ndarray.shape)] flattened = [l for p in",
"A[2,0] = A[0,2] A[1,2] = U0 * V0 * np.sum(M4N * M3N) A[2,1]",
"stokes[0] *(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1] / stokes[0] *(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2]",
"V0**2 * np.sum(M4One * M4N) betaI = np.abs((0.5 * I0 * np.sum(M1N *",
"coefficients Returns ------- float : total power \"\"\" return f[0]**2 + 2.0*np.sum(f[1:]**2) class",
"{0}'.format(stokesPar[loop])) # ax[loop].annotate # pl.tight_layout() # ax[0,0].plot(out.times, out.signal[0]) # ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt)) #",
"= 0.000000051) # stI, stQ, stU, stV = out.demodulateTrivial() # print \"Q/I_original={0} -",
"Fourier coefficients Returns ------- float : signal \"\"\" out = fft.irfft(x) return out",
"return self.factor * myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self, z): return (z[0] * z[0].conj() + 2",
"------- >>> m = np.arange(0,100,1).reshape((10,10)) >>> n = bin_ndarray(m, new_shape=(5,5), operation='sum') >>> print(n)",
"# Read seeing power spectrum self.powerLites = np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] = 10.0**self.powerLites[:,1] # Number",
"1) # M2(t) * 1(t) M3One = self.forwardPartial(np.ones(self.nSteps), 2) # M3(t) * 1(t)",
"= np.copy(x) xPar[np.abs(x) < lambdaValue] = 0.0 return xPar def FISTA(self, initial=None, initialStokes=None,",
"!= 0): np.random.seed(self.seed) # Read seeing power spectrum self.powerLites = np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] =",
"self.powerSeeing = np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0] = 0.0 self.seeingFFT = np.sqrt(self.powerSeeing) * noiseFFT",
"figsize=(18,6)) # coefFourier[0] = 0.0 # Nt = myIFFT(coefFourier) # Nt /= np.sqrt(myTotalPower(coefFourier))",
"np.sum(forwU * forwV) A[2,1] = A[1,2] b = np.zeros(3) b[0] = 0.5 *",
"self.forwardPartial(np.ones(self.nSteps), 3) # M4(t) * 1(t) A = np.zeros((3,3)) A[0,0] = Q0**2 *",
"\"\"\" Solve the l1 regularized problem using the FISTA algorithm, that solves the",
"following problem: argmin_O ||y - M*F^{-1}*alpha||_2 + \\lambda ||alpha||_1 Args: rank (int, optional):",
"x = np.copy(xNew) normResidual = np.linalg.norm(residual1 + residual2) normSolutionL1 = np.linalg.norm(x, 1) normSolutionL0",
"= self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'hardPercentage'): xNew =",
"Description \"\"\" if (initial == None): x = np.zeros(self.nSteps) I0 = 0.9 Q0",
"self.alphaModulation = temp['arr_0'][0:self.nSteps] self.betaModulation = temp['arr_1'][0:self.nSteps] self.modulation = [np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\",
"np.mean(self.signalIntegrated[i]) / self.signalToNoise * np.random.randn(self.nSamples) self.tIntegrated = np.arange(self.nSamples) * self.dtIntegration # Generate modulation",
"np.sum(forwU**2) A[2,2] = np.sum(forwV**2) A[0,1] = np.sum(forwQ * forwU) A[1,0] = A[0,1] A[0,2]",
"= A[1,2] b = np.zeros(3) b[0] = 0.5 * Q0 * np.sum(M2N *",
"/ stokes[0]) # print \"V/I_original={0} - V/I_inferred={1} - V/I_trivial={2} - diff={3}\".format(out.stokes[3] / out.stokes[0],",
"def myIFFT(x): \"\"\" Return the IFFT for a real signal taking into account",
"+ \\lambda ||alpha||_1 Args: rank (int, optional): rank of the solution niter (int,",
"V0 # totalTime = 1.0 # s # dt = 0.001 # s",
"temp += sign * self.signal[j] * self.modulation[j] self.signalIntegrated[i] = bin_ndarray(temp, (self.nSamples,), operation='sum') self.signalIntegrated[i]",
"(loop % 10): # Stokes parameters I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1]))",
"4 for state in range(4): sparseData = [] sparseRow = [] sparseCol =",
"Q0 * betaQ * self.backward(residual2, 1) + \\ 2.0 * U0 * betaU",
"if (self.seed != 0): np.random.seed(self.seed) # Read seeing power spectrum self.powerLites = np.loadtxt('powerSpectrumSeeing.dat')",
"int(self.dt / self.dtIntegration * self.nSteps) self.signalIntegrated = [None] * 2 for i in",
"angles # self.modulation = [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType == 0): self.alphaModulation",
"x, lambdaValue): xPar = np.copy(x) xPar[np.abs(x) < lambdaValue] = 0.0 return xPar def",
"U0 = 1e-3 if (np.abs(V0) > 1.0): V0 = 1e-3 # Seeing amplitude",
"# Generate modulation matrix self.sparseM = [None] * 4 self.sparseMStar = [None] *",
"/ np.sqrt(len(out)) def myIFFT(x): \"\"\" Return the IFFT for a real signal taking",
"rank of the solution niter (int, optional): number of iterations Returns: TYPE: Description",
"(1+betaV*N(t)) residual1 = self.signalIntegrated[0] - (I0 * forwI + Q0 * forwQ +",
"V0 * np.sum(M4N * M3N) A[2,1] = A[1,2] b = np.zeros(3) b[0] =",
"myIFFT(coefFourier) # Nt /= np.sqrt(myTotalPower(coefFourier)) # stokesPar = ['I', 'Q', 'U', 'V'] #",
"# self.modulation = [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType == 0): self.alphaModulation =",
"self.tIntegrated = np.arange(self.nSamples) * self.dtIntegration # Generate modulation matrix self.sparseM = [None] *",
"zip(new_shape, ndarray.shape)] flattened = [l for p in compression_pairs for l in p]",
"def demodulateTrivial(self): forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV =",
"samples of the original sample self.nSteps = int(totalTime / dt) self.times = np.arange(self.nSteps)",
"* np.sum(M4One * M3N) b[2] = 0.5 * V0 * np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1]))",
"M3N) - U0 * V0 * np.sum(M4One * M3N) b[2] = 0.5 *",
"forwU + V0 * forwV) gradient1 = -2.0 * I0 * betaI *",
"self.signalIntegrated[0] - (I0 * forwI + Q0 * forwQ + U0 * forwU",
"= totalTime self.dt = dt self.dtIntegration = dtIntegration self.seed = seed self.signalToNoise =",
"- Q0 * U0 * np.sum(M3One * M2N) - Q0 * V0 *",
"Q0 * forwQ - U0 * forwU - V0 * forwV) gradient2 =",
"366 374]] \"\"\" if not operation.lower() in ['sum', 'mean', 'average', 'avg']: raise ValueError(\"Operation",
"largestEigenvalue = splinalg.eigsh(res, k=1, which='LM', return_eigenvectors=False) self.mu = 0.5 / (np.real(largestEigenvalue)) * 0.0002",
"sparseRow.append(i) sparseCol.append(loop) loop += 1 self.sparseM[state] = sp.coo_matrix((sparseData, (sparseRow, sparseCol)), shape=(self.nSamples, self.nSteps)) self.sparseMStar[state]",
"stokes[0]) # print \"V/I_original={0} - V/I_inferred={1} - V/I_trivial={2} - diff={3}\".format(out.stokes[3] / out.stokes[0], stokes[3]",
"b[1] = 0.5 * U0 * np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ U0 *",
"(thresholdMethod == 'soft'): xNew = self.softThreshold(y - self.mu * np.real(gradient), lambdaValue) xNew[0] =",
"* U0 * betaU * self.backward(residual2, 2) + 2.0 * V0 * betaV",
"V0 = 1e-3 # Seeing amplitude M1N = self.forwardPartial(signal, 0) # M1(t) *",
"Number of samples of the original sample self.nSteps = int(totalTime / dt) self.times",
"betaQ = 10.0#self.beta[1] betaU = 10.0#self.beta[2] betaV = 10.0#self.beta[3] else: x = np.copy(initial)",
"IFFT for a real signal taking into account some normalization Parameters ---------- x",
"splinalg import scipy.fftpack as fft def bin_ndarray(ndarray, new_shape, operation='sum'): \"\"\" Bins an ndarray",
"def backward(self, z, ray): return self.factor * myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self, z): return (z[0]",
"the total power is unity print 'Total variance = ', np.sum(self.seeing**2), myTotalPower(self.seeingFFT) #",
"np.random.randn(self.nSteps) noiseFFT = myFFT(noise) self.powerSeeing = np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0] = 0.0 self.seeingFFT",
"= 0.0 return xPar def FISTA(self, initial=None, initialStokes=None, thresholdMethod='soft', niter=10, lambdaValue=1.0): \"\"\" Solve",
"- Q0 * V0 * np.sum(M4One * M2N) b[1] = 0.5 * U0",
"else: x = np.copy(initial) I0, Q0, U0, V0 = initialStokes xNew = np.copy(x)",
"all axes based on the target shape, by summing or averaging. Number of",
"* U0 * np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ U0 * Q0 * np.sum(M2One",
"the target shape, by summing or averaging. Number of output dimensions must match",
"FISTA algorithm, that solves the following problem: argmin_O ||y - M*F^{-1}*alpha||_2 + \\lambda",
"* betaV * self.backward(residual2, 3) gradient = gradient1 + gradient2 if (thresholdMethod ==",
"* betaI * self.backward(residual2, 0) + 2.0 * Q0 * betaQ * self.backward(residual2,",
"* 2 for i in range(2): temp = self.signal[0] * self.modulation[0] sign =",
"is unity print 'Total variance = ', np.sum(self.seeing**2), myTotalPower(self.seeingFFT) # Compute the signal",
"(self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) return I0, Q0, U0, V0 # totalTime",
"Compute the signal and its power spectrum self.signal = [None] * 4 for",
"operation='sum') self.signalIntegrated[i] += np.mean(self.signalIntegrated[i]) / self.signalToNoise * np.random.randn(self.nSamples) self.tIntegrated = np.arange(self.nSamples) * self.dtIntegration",
"M1N = self.forwardPartial(signal, 0) # M1(t) * N(t) M2N = self.forwardPartial(signal, 1) #",
"Parameters ---------- f : float Signal Fourier coefficients Returns ------- float : total",
"x, lambdaValue): return np.fmax(0,1.0 - lambdaValue / np.fmax(np.abs(x),1e-10)) * x def hardThreshold(self, x,",
"if (np.abs(V0) > 1.0): V0 = 1e-3 # Seeing amplitude M1N = self.forwardPartial(signal,",
"normResidual, normSolutionL1, 100.0*normSolutionL0 / self.nSteps, I0, Q0/I0, U0/I0, V0/I0, betaI, betaQ, betaU, betaV)",
"not operation.lower() in ['sum', 'mean', 'average', 'avg']: raise ValueError(\"Operation {} not supported.\".format(operation)) if",
"= ', np.sum(self.seeing**2), myTotalPower(self.seeingFFT) # Compute the signal and its power spectrum self.signal",
"# ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3] / stokes[0] * (1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt))) #",
"(xNew - x) t = tNew x = np.copy(xNew) normResidual = np.linalg.norm(residual1 +",
"# ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21) # ax[2,1].semilogy(normL11) # ax[3,0].plot(out.signalIntegrated[0]) # ax[3,0].plot(out.signalIntegrated[1]) #",
">>> print(n) [[ 22 30 38 46 54] [102 110 118 126 134]",
"Q0 * betaQ * self.backward(residual1, 1) - \\ 2.0 * U0 * betaU",
"M4N) - V0**2 * np.sum(M4One * M4N) betaI = np.abs((0.5 * I0 *",
"xNew /= np.sqrt(myTotalPower(xNew)) if (thresholdMethod == 'L2'): xNew = y - self.mu *",
"/= np.sqrt(myTotalPower(xNew)) if (thresholdMethod == 'L2'): xNew = y - self.mu * np.real(gradient)",
"= np.sum(forwQ**2) A[1,1] = np.sum(forwU**2) A[2,2] = np.sum(forwV**2) A[0,1] = np.sum(forwQ * forwU)",
"= int(self.dtIntegration / self.dt) self.nSamples = int(self.dt / self.dtIntegration * self.nSteps) self.signalIntegrated =",
"#s # beta = np.asarray([15.0, 100.0, 100., 100.0]) # stokes = np.asarray([1.0, 1.2e-3,",
"# Nt = myIFFT(coefFourier) # Nt /= np.sqrt(myTotalPower(coefFourier)) # stokesPar = ['I', 'Q',",
"* self.signal[j] * self.modulation[j] self.signalIntegrated[i] = bin_ndarray(temp, (self.nSamples,), operation='sum') self.signalIntegrated[i] += np.mean(self.signalIntegrated[i]) /",
"ax[loop].plot(out.times, out.signal[loop]) # ax[loop].plot(out.times, stokes[loop] / stokes[0] * (1.0 + beta[loop]*Nt)) # ax[loop].set_xlabel('Time",
"/ stokes[0] * (1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3] / stokes[0] * (1.0+beta[3]*Nt)) #",
"b[2] = 0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) return",
"= 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A = np.zeros((3,3)) A[0,0] =",
"M2N) A[2,0] = A[0,2] A[1,2] = U0 * V0 * np.sum(M4N * M3N)",
"# ax[0,1].plot(stokes[1] / stokes[0] *(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2] / stokes[0] * (1.0+beta[2]*Nt))",
"if operation.lower() == \"sum\": ndarray = ndarray.sum(-1*(i+1)) elif operation.lower() in [\"mean\", \"average\", \"avg\"]:",
"into account some normalization Parameters ---------- x : float Signal time series Returns",
"+ self.beta[i] * self.seeing) # Generate modulation using a lambda/4 and lambda/2 polarimeter",
"for i in range(len(new_shape)): if operation.lower() == \"sum\": ndarray = ndarray.sum(-1*(i+1)) elif operation.lower()",
"= 1.0 normL1 = [] normL2 = [] normL0 = [] for loop",
"- l1={2:10.4f} - l0={3:5.1f}% - I={4:11.5f} - Q/I={5:11.5f} - U/I={6:11.5f} - V/I={7:11.5f} -",
"# Number of samples of the original sample self.nSteps = int(totalTime / dt)",
"(self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) if (I0 < 0): I0 = 1.0",
"Q0, U0, V0 = initialStokes xNew = np.copy(x) y = np.copy(x) res =",
"- bV={11:11.5f}\".format(loop, normResidual, normSolutionL1, 100.0*normSolutionL0 / self.nSteps, I0, Q0/I0, U0/I0, V0/I0, betaI, betaQ,",
"niter = 600, lambdaValue = 0.000000051) # stI, stQ, stU, stV = out.demodulateTrivial()",
"294] [342 350 358 366 374]] \"\"\" if not operation.lower() in ['sum', 'mean',",
"= modulationType if (self.seed != 0): np.random.seed(self.seed) # Read seeing power spectrum self.powerLites",
"# f, ax = pl.subplots(nrows=1, ncols=4, figsize=(18,6)) # coefFourier[0] = 0.0 # Nt",
"TYPE Description seed : int, optional Description Returns ------- TYPE : Description \"\"\"",
"= self.forwardPartial(np.ones(self.nSteps), 0) # M1(t) * 1(t) M2One = self.forwardPartial(np.ones(self.nSteps), 1) # M2(t)",
"- \\ I0**2 * np.sum(M1One * M1N)) / (I0**2 * np.sum(M1N**2))) betaQ, betaU,",
"modulationType if (self.seed != 0): np.random.seed(self.seed) # Read seeing power spectrum self.powerLites =",
"# ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2] / stokes[0] * (1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3] /",
"* self.seeing) # Generate modulation using a lambda/4 and lambda/2 polarimeter with random",
"Q/I_trivial={2} - diff={3}\".format(out.stokes[1] / out.stokes[0], stokes[1] / stokes[0], \\ # stQ/stI, out.stokes[1] /",
"U0, V0 = np.linalg.solve(A,b) if (I0 < 0): I0 = 1.0 if (np.abs(Q0)",
"= np.arange(self.nSteps) * self.dt # Frequency axis self.freq = fft.rfftfreq(self.nSteps, d=dt) # Betas",
"* forwI + Q0 * forwQ + U0 * forwU + V0 *",
"* np.sum(M1N**2))) betaQ, betaU, betaV = np.abs(np.linalg.solve(A,b)) if (loop % 50 == 0):",
"variance = ', np.sum(self.seeing**2), myTotalPower(self.seeingFFT) # Compute the signal and its power spectrum",
"np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime = self.dtIntegration self.lengthSample = int(self.dtIntegration / self.dt)",
"# Make sure that the total power is unity print 'Total variance =",
"x : float Signal time series Returns ------- float : Fourier coefficients of",
"+ 2 * np.sum(z[1:] * z[1:].conj())).real / len(z) def softThreshold(self, x, lambdaValue): return",
"= [] sparseRow = [] sparseCol = [] loop = 0 for i",
"0.0 # Nt = myIFFT(coefFourier) # Nt /= np.sqrt(myTotalPower(coefFourier)) # stokesPar = ['I',",
"import scipy.sparse.linalg as splinalg import scipy.fftpack as fft def bin_ndarray(ndarray, new_shape, operation='sum'): \"\"\"",
"forwV) gradient1 = -2.0 * I0 * betaI * self.backward(residual1, 0) - 2.0",
"= np.zeros((3,3)) A[0,0] = Q0**2 * np.sum(M2N**2) A[1,1] = U0**2 * np.sum(M3N**2) A[2,2]",
"in range(1,4): temp += sign * self.signal[j] * self.modulation[j] self.signalIntegrated[i] = bin_ndarray(temp, (self.nSamples,),",
"I={4:11.5f} - Q/I={5:11.5f} - U/I={6:11.5f} - V/I={7:11.5f} - bI={8:11.5f} - bQ={9:11.5f} - bU={10:11.5f}",
"50 == 0): print \"It {0:4d} - l2={1:10.3e} - l1={2:10.4f} - l0={3:5.1f}% -",
"- bI={8:11.5f} - bQ={9:11.5f} - bU={10:11.5f} - bV={11:11.5f}\".format(loop, normResidual, normSolutionL1, 100.0*normSolutionL0 / self.nSteps,",
"- (I0 * forwI - Q0 * forwQ - U0 * forwU -",
"\"\"\" def __init__(self, totalTime, dt, dtIntegration, stokes, beta, signalToNoise=0.0, seed=0, modulationType=0): \"\"\"Summary Parameters",
"np.sum(M3N * M2N) A[1,0] = A[0,1] A[0,2] = Q0 * V0 * np.sum(M4N",
"together \"\"\" def __init__(self, totalTime, dt, dtIntegration, stokes, beta, signalToNoise=0.0, seed=0, modulationType=0): \"\"\"Summary",
"A = np.zeros((3,3)) A[0,0] = Q0**2 * np.sum(M2N**2) A[1,1] = U0**2 * np.sum(M3N**2)",
"lambda/2 polarimeter with random angles # self.modulation = [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if",
"0.01 #s # beta = np.asarray([15.0, 100.0, 100., 100.0]) # stokes = np.asarray([1.0,",
"1.0): U0 = 1e-3 if (np.abs(V0) > 1.0): V0 = 1e-3 # Seeing",
"= 2*np.ones(self.nSteps) self.factor[0] = 1.0 def forward(self, signal, beta, ray): return self.sparseM[ray].dot(1.0+beta*signal) def",
"Args: rank (int, optional): rank of the solution niter (int, optional): number of",
"sign * self.signal[j] * self.modulation[j] self.signalIntegrated[i] = bin_ndarray(temp, (self.nSamples,), operation='sum') self.signalIntegrated[i] += np.mean(self.signalIntegrated[i])",
"self.modulation = [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType == 0): self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps)",
"- self.mu * np.real(gradient) tNew = 0.5*(1+np.sqrt(1+4.0*t**2)) y = xNew + (t-1.0) /",
"- (I0 * forwI + Q0 * forwQ + U0 * forwU +",
"* U0 * np.sum(M3One * M2N) - Q0 * V0 * np.sum(M4One *",
"np.sum(forwQ**2) A[1,1] = np.sum(forwU**2) A[2,2] = np.sum(forwV**2) A[0,1] = np.sum(forwQ * forwU) A[1,0]",
"parameters self.beta = beta self.stokes = stokes # Generate Gaussian noise with unit",
"Number of output dimensions must match number of input dimensions. Example ------- >>>",
"270 278 286 294] [342 350 358 366 374]] \"\"\" if not operation.lower()",
"initialStokes=None, thresholdMethod='soft', niter=10, lambdaValue=1.0): \"\"\" Solve the l1 regularized problem using the FISTA",
"dtIntegration, stokes, beta, seed=123, signalToNoise=1e3) # coefFourier, stokes, beta, normL21, normL11 = out.FISTA(thresholdMethod",
"0.001 # s # dtIntegration = 0.01 #s # beta = np.asarray([15.0, 100.0,",
"residual2) normSolutionL1 = np.linalg.norm(x, 1) normSolutionL0 = np.linalg.norm(x, 0) if (loop % 10):",
"diff={3}\".format(out.stokes[1] / out.stokes[0], stokes[1] / stokes[0], \\ # stQ/stI, out.stokes[1] / out.stokes[0]-stokes[1] /",
"22 30 38 46 54] [102 110 118 126 134] [182 190 198",
"self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'soft'): xNew = self.softThreshold(y - self.mu",
"= -2.0 * I0 * betaI * self.backward(residual1, 0) - 2.0 * Q0",
"(self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] = 0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b)",
"['sum', 'mean', 'average', 'avg']: raise ValueError(\"Operation {} not supported.\".format(operation)) if ndarray.ndim != len(new_shape):",
">>> n = bin_ndarray(m, new_shape=(5,5), operation='sum') >>> print(n) [[ 22 30 38 46",
"xNew = self.softThreshold(y - self.mu * np.real(gradient), lambdaValue) xNew[0] = 0.0 xNew /=",
"self.nSteps, I0, Q0/I0, U0/I0, V0/I0, betaI, betaQ, betaU, betaV) normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0) return",
"* np.sum(M4One * M4N) betaI = np.abs((0.5 * I0 * np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1]))",
"= np.copy(initial) I0, Q0, U0, V0 = initialStokes xNew = np.copy(x) y =",
"= self.forward(signal, betaQ, 1) # M2(t) * (1+betaQ*N(t)) forwU = self.forward(signal, betaU, 2)",
"- V/I_inferred={1} - V/I_trivial={2} - diff={3}\".format(out.stokes[3] / out.stokes[0], stokes[3] / stokes[0], \\ #",
"(z[0] * z[0].conj() + 2 * np.sum(z[1:] * z[1:].conj())).real / len(z) def softThreshold(self,",
"= 10.0#self.beta[0] betaQ = 10.0#self.beta[1] betaU = 10.0#self.beta[2] betaV = 10.0#self.beta[3] else: x",
"* M3N) - U0**2 * np.sum(M3One * M3N) - U0 * V0 *",
"betaQ, 1) # M2(t) * (1+betaQ*N(t)) forwU = self.forward(signal, betaU, 2) # M3(t)",
"randomDemodulator(totalTime, dt, dtIntegration, stokes, beta, seed=123, signalToNoise=1e3) # coefFourier, stokes, beta, normL21, normL11",
"b[1] = 0.5 * np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] = 0.5 * np.sum(forwV *",
"self.freq = fft.rfftfreq(self.nSteps, d=dt) # Betas and Stokes parameters self.beta = beta self.stokes",
"sure that the total power is unity print 'Total variance = ', np.sum(self.seeing**2),",
"the solution niter (int, optional): number of iterations Returns: TYPE: Description \"\"\" if",
"V0 * np.sum(M4N * M2N) A[2,0] = A[0,2] A[1,2] = U0 * V0",
"# M1(t) * 1(t) M2One = self.forwardPartial(np.ones(self.nSteps), 1) # M2(t) * 1(t) M3One",
"* np.real(gradient), lambdaValue) if (thresholdMethod == 'soft'): xNew = self.softThreshold(y - self.mu *",
"U0 * forwU + V0 * forwV) gradient1 = -2.0 * I0 *",
"ray): return self.factor * myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self, z): return (z[0] * z[0].conj() +",
"self.lengthSample = int(self.dtIntegration / self.dt) self.nSamples = int(self.dt / self.dtIntegration * self.nSteps) self.signalIntegrated",
"beta, ray): return self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self, signal, ray): return self.sparseM[ray].dot(signal) def backward(self, z,",
"float Signal time series Returns ------- float : Fourier coefficients of the real",
"U0**2 * np.sum(M3N**2) A[2,2] = V0**2 * np.sum(M4N**2) A[0,1] = Q0 * U0",
"np.sum(M1One * M1N)) / (I0**2 * np.sum(M1N**2))) betaQ, betaU, betaV = np.abs(np.linalg.solve(A,b)) if",
"0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) return I0, Q0,",
"np.abs((0.5 * I0 * np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1])) - \\ I0**2 * np.sum(M1One *",
"* (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] = 0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 =",
"betaU * self.backward(residual1, 2) - 2.0 * V0 * betaV * self.backward(residual1, 3)",
"power spectrum noise = np.random.randn(self.nSteps) noiseFFT = myFFT(noise) self.powerSeeing = np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1])",
"self.dtIntegration = dtIntegration self.seed = seed self.signalToNoise = signalToNoise self.modulationType = modulationType if",
"350 358 366 374]] \"\"\" if not operation.lower() in ['sum', 'mean', 'average', 'avg']:",
"forwU - V0 * forwV) gradient2 = -2.0 * I0 * betaI *",
"/ out.stokes[0]-stokes[2] / stokes[0]) # print \"V/I_original={0} - V/I_inferred={1} - V/I_trivial={2} - diff={3}\".format(out.stokes[3]",
"dt = 0.001 # s # dtIntegration = 0.01 #s # beta =",
"if (I0 < 0): I0 = 1.0 if (np.abs(Q0) > 1.0): Q0 =",
"bU={10:11.5f} - bV={11:11.5f}\".format(loop, normResidual, normSolutionL1, 100.0*normSolutionL0 / self.nSteps, I0, Q0/I0, U0/I0, V0/I0, betaI,",
"# M2(t) * N(t) M3N = self.forwardPartial(signal, 2) # M3(t) * N(t) M4N",
"z[0].conj() + 2 * np.sum(z[1:] * z[1:].conj())).real / len(z) def softThreshold(self, x, lambdaValue):",
"taking into account some normalization Parameters ---------- x : float Signal time series",
"= temp['arr_1'][0:self.nSteps] self.modulation = [np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))]",
"0 # for loop in range(4): # ax[loop].plot(out.times, out.signal[loop]) # ax[loop].plot(out.times, stokes[loop] /",
"1) normSolutionL0 = np.linalg.norm(x, 0) if (loop % 10): # Stokes parameters I0",
"stokes, beta, seed=123, signalToNoise=1e3) # coefFourier, stokes, beta, normL21, normL11 = out.FISTA(thresholdMethod =",
"match number of input dimensions. Example ------- >>> m = np.arange(0,100,1).reshape((10,10)) >>> n",
"signal, beta, ray): return self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self, signal, ray): return self.sparseM[ray].dot(signal) def backward(self,",
"= np.abs(np.linalg.solve(A,b)) if (loop % 50 == 0): print \"It {0:4d} - l2={1:10.3e}",
"# M2(t) * 1(t) M3One = self.forwardPartial(np.ones(self.nSteps), 2) # M3(t) * 1(t) M4One",
": Demodulate I and Q signals together \"\"\" def __init__(self, totalTime, dt, dtIntegration,",
"= myIFFT(self.seeingFFT) # Make sure that the total power is unity print 'Total",
"in range(niter): signal = myIFFT(x) forwI = self.forward(signal, betaI, 0) # M1(t) *",
"sparseRow = [] sparseCol = [] loop = 0 for i in range(self.nSamples):",
"600, lambdaValue = 0.000000051) # stI, stQ, stU, stV = out.demodulateTrivial() # print",
"stV/stI, out.stokes[3] / out.stokes[0]-stokes[3] / stokes[0]) # pl.close('all') # f, ax = pl.subplots(nrows=1,",
"(self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ V0 * Q0 * np.sum(M2One * M4N) - V0 *",
"real signal taking into account some normalization Parameters ---------- x : float Signal",
"* np.sum(M3N * M2N) A[1,0] = A[0,1] A[0,2] = Q0 * V0 *",
"100.0, 100., 100.0]) # stokes = np.asarray([1.0, 1.2e-3, 5.e-3, 0.001]) # out =",
"np.arange(self.nSamples) * self.dtIntegration # Generate modulation matrix self.sparseM = [None] * 4 self.sparseMStar",
"134] [182 190 198 206 214] [262 270 278 286 294] [342 350",
"54] [102 110 118 126 134] [182 190 198 206 214] [262 270",
"ax = pl.subplots(nrows=1, ncols=4, figsize=(18,6)) # coefFourier[0] = 0.0 # Nt = myIFFT(coefFourier)",
"Returns ------- float : Fourier coefficients of the real signal \"\"\" out =",
"# M4(t) * 1(t) A = np.zeros((3,3)) A[0,0] = Q0**2 * np.sum(M2N**2) A[1,1]",
"by the square root of the power spectrum # to generate the noise",
"np.sum(M3One * M4N) - V0**2 * np.sum(M4One * M4N) betaI = np.abs((0.5 *",
"np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] = 10.0**self.powerLites[:,1] # Number of samples of the original sample self.nSteps",
"= np.linalg.norm(residual1 + residual2) normSolutionL1 = np.linalg.norm(x, 1) normSolutionL0 = np.linalg.norm(x, 0) if",
"TYPE : Description \"\"\" self.totalTime = totalTime self.dt = dt self.dtIntegration = dtIntegration",
"* np.sum(M3N**2) A[2,2] = V0**2 * np.sum(M4N**2) A[0,1] = Q0 * U0 *",
"betaU, 2) # M3(t) * (1+betaU*N(t)) forwV = self.forward(signal, betaV, 3) # M4(t)",
"U0, V0), (betaI, betaQ, betaU, betaV), normL2, normL1, normL0 def demodulateTrivial(self): forwI =",
"operation='sum') >>> print(n) [[ 22 30 38 46 54] [102 110 118 126",
"out.demodulateTrivial() # print \"Q/I_original={0} - Q/I_inferred={1} - Q/I_trivial={2} - diff={3}\".format(out.stokes[1] / out.stokes[0], stokes[1]",
"1.0): V0 = 1e-3 # Seeing amplitude M1N = self.forwardPartial(signal, 0) # M1(t)",
"self.powerSeeing[0] = 0.0 self.seeingFFT = np.sqrt(self.powerSeeing) * noiseFFT self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing =",
"M2N) A[1,0] = A[0,1] A[0,2] = Q0 * V0 * np.sum(M4N * M2N)",
"self.backward(residual2, 2) + 2.0 * V0 * betaV * self.backward(residual2, 3) gradient =",
"U0, V0 = initialStokes xNew = np.copy(x) y = np.copy(x) res = self.sparseMStar[0].dot(self.sparseM[0])",
"totalPower(self, z): return (z[0] * z[0].conj() + 2 * np.sum(z[1:] * z[1:].conj())).real /",
"Bins an ndarray in all axes based on the target shape, by summing",
"-> {}\".format(ndarray.shape, new_shape)) compression_pairs = [(d, c//d) for d, c in zip(new_shape, ndarray.shape)]",
"betaI, betaQ, betaU, betaV) normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0) return x, (I0, Q0, U0, V0),",
"0): np.random.seed(self.seed) # Read seeing power spectrum self.powerLites = np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] = 10.0**self.powerLites[:,1]",
"z): return (z[0] * z[0].conj() + 2 * np.sum(z[1:] * z[1:].conj())).real / len(z)",
"* noiseFFT self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing = myIFFT(self.seeingFFT) # Make sure that the",
"beta, normL21, normL11 = out.FISTA(thresholdMethod = 'soft', niter = 600, lambdaValue = 0.000000051)",
"if (thresholdMethod == 'hardPercentage'): xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if",
"V0 = initialStokes xNew = np.copy(x) y = np.copy(x) res = self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue",
"generate the noise with the appropriate power spectrum noise = np.random.randn(self.nSteps) noiseFFT =",
"V0**2 * np.sum(M4N**2) A[0,1] = Q0 * U0 * np.sum(M3N * M2N) A[1,0]",
"ndarray = ndarray.mean(-1*(i+1)) return ndarray def myFFT(x): \"\"\" Return the FFT of a",
"* N(t) M2N = self.forwardPartial(signal, 1) # M2(t) * N(t) M3N = self.forwardPartial(signal,",
"* (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ V0 * Q0 * np.sum(M2One * M4N) - V0",
"------- TYPE : Description \"\"\" self.totalTime = totalTime self.dt = dt self.dtIntegration =",
"self.forwardPartial(signal, 1) # M2(t) * N(t) M3N = self.forwardPartial(signal, 2) # M3(t) *",
"forwI = self.forward(signal, betaI, 0) # M1(t) * (1+betaI*N(t)) forwQ = self.forward(signal, betaQ,",
"358 366 374]] \"\"\" if not operation.lower() in ['sum', 'mean', 'average', 'avg']: raise",
"= [None] * 4 for state in range(4): sparseData = [] sparseRow =",
"supported.\".format(operation)) if ndarray.ndim != len(new_shape): raise ValueError(\"Shape mismatch: {} -> {}\".format(ndarray.shape, new_shape)) compression_pairs",
"# ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) # ax[loop].annotate # pl.tight_layout() # ax[0,0].plot(out.times, out.signal[0]) # ax[0,0].plot(out.times, stokes[0]",
"/= np.sqrt(myTotalPower(coefFourier)) # stokesPar = ['I', 'Q', 'U', 'V'] # loop = 0",
"# to generate the noise with the appropriate power spectrum noise = np.random.randn(self.nSteps)",
"(sparseRow, sparseCol)), shape=(self.nSamples, self.nSteps)) self.sparseMStar[state] = self.sparseM[state].transpose(copy=True) self.factor = 2*np.ones(self.nSteps) self.factor[0] = 1.0",
"0) # M1(t) * (1+betaI*N(t)) forwQ = self.forward(signal, betaQ, 1) # M2(t) *",
"\"Q/I_original={0} - Q/I_inferred={1} - Q/I_trivial={2} - diff={3}\".format(out.stokes[1] / out.stokes[0], stokes[1] / stokes[0], \\",
"np.sum(M4One * M2N) b[1] = 0.5 * U0 * np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1])) -",
"betaU, betaV = np.abs(np.linalg.solve(A,b)) if (loop % 50 == 0): print \"It {0:4d}",
"self.powerLites = np.loadtxt('powerSpectrumSeeing.dat') self.powerLites[:,1] = 10.0**self.powerLites[:,1] # Number of samples of the original",
"= int(self.dt / self.dtIntegration * self.nSteps) self.signalIntegrated = [None] * 2 for i",
"in range(self.nSamples): for j in range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop) loop += 1 self.sparseM[state]",
"Q0**2 * np.sum(M2N**2) A[1,1] = U0**2 * np.sum(M3N**2) A[2,2] = V0**2 * np.sum(M4N**2)",
"* Q0 * np.sum(M2One * M4N) - V0 * U0 * np.sum(M3One *",
"* np.real(gradient) tNew = 0.5*(1+np.sqrt(1+4.0*t**2)) y = xNew + (t-1.0) / tNew *",
"2.0*np.sum(f[1:]**2) class randomDemodulator(object): \"\"\"Summary Returns ------- TYPE : Demodulate I and Q signals",
": Description \"\"\" self.totalTime = totalTime self.dt = dt self.dtIntegration = dtIntegration self.seed",
"* 1(t) M4One = self.forwardPartial(np.ones(self.nSteps), 3) # M4(t) * 1(t) A = np.zeros((3,3))",
"for loop in range(4): # ax[loop].plot(out.times, out.signal[loop]) # ax[loop].plot(out.times, stokes[loop] / stokes[0] *",
"1) - \\ 2.0 * U0 * betaU * self.backward(residual1, 2) - 2.0",
"self.betaModulation = temp['arr_1'][0:self.nSteps] self.modulation = [np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\",
"operation.lower() in ['sum', 'mean', 'average', 'avg']: raise ValueError(\"Operation {} not supported.\".format(operation)) if ndarray.ndim",
"- Q/I={5:11.5f} - U/I={6:11.5f} - V/I={7:11.5f} - bI={8:11.5f} - bQ={9:11.5f} - bU={10:11.5f} -",
"np.sqrt(myTotalPower(self.seeingFFT)) self.seeing = myIFFT(self.seeingFFT) # Make sure that the total power is unity",
"# dt = 0.001 # s # dtIntegration = 0.01 #s # beta",
"= [] for loop in range(niter): signal = myIFFT(x) forwI = self.forward(signal, betaI,",
"* np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ U0 * Q0 * np.sum(M2One * M3N)",
"self.seeingFFT = np.sqrt(self.powerSeeing) * noiseFFT self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing = myIFFT(self.seeingFFT) # Make",
"* V0 * np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ V0 * Q0 * np.sum(M2One",
"out.stokes[0], stokes[1] / stokes[0], \\ # stQ/stI, out.stokes[1] / out.stokes[0]-stokes[1] / stokes[0]) #",
"Q0/I0, U0/I0, V0/I0, betaI, betaQ, betaU, betaV) normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0) return x, (I0,",
"loop in range(4): # ax[loop].plot(out.times, out.signal[loop]) # ax[loop].plot(out.times, stokes[loop] / stokes[0] * (1.0",
"- U0**2 * np.sum(M3One * M3N) - U0 * V0 * np.sum(M4One *",
"self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue = splinalg.eigsh(res, k=1, which='LM', return_eigenvectors=False) self.mu = 0.5 / (np.real(largestEigenvalue)) *",
"if (loop % 50 == 0): print \"It {0:4d} - l2={1:10.3e} - l1={2:10.4f}",
"signalToNoise=1e3) # coefFourier, stokes, beta, normL21, normL11 = out.FISTA(thresholdMethod = 'soft', niter =",
"totalTime self.dt = dt self.dtIntegration = dtIntegration self.seed = seed self.signalToNoise = signalToNoise",
"= self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 = 0.5 * np.sum(forwI",
"range(4): # ax[loop].plot(out.times, out.signal[loop]) # ax[loop].plot(out.times, stokes[loop] / stokes[0] * (1.0 + beta[loop]*Nt))",
"# ax[0,0].plot(out.times, out.signal[0]) # ax[0,0].plot(out.times, stokes[0] *(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1] / stokes[0]",
"lambdaValue) if (thresholdMethod == 'soft'): xNew = self.softThreshold(y - self.mu * np.real(gradient), lambdaValue)",
"must match number of input dimensions. Example ------- >>> m = np.arange(0,100,1).reshape((10,10)) >>>",
"* self.backward(residual2, 2) + 2.0 * V0 * betaV * self.backward(residual2, 3) gradient",
"0) # M1(t) * 1(t) M2One = self.forwardPartial(np.ones(self.nSteps), 1) # M2(t) * 1(t)",
"/= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing = myIFFT(self.seeingFFT) # Make sure that the total power is",
"* V0 * np.sum(M4One * M2N) b[1] = 0.5 * U0 * np.sum(M3N",
"for i in range(4): self.signal[i] = self.stokes[i]*(1.0 + self.beta[i] * self.seeing) # Generate",
"= 0.5 * np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] = 0.5 * np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1]))",
"power spectrum of a signal Parameters ---------- f : float Signal Fourier coefficients",
"else: temp = np.load('alphaBetaSamples.npz') self.alphaModulation = temp['arr_0'][0:self.nSteps] self.betaModulation = temp['arr_1'][0:self.nSteps] self.modulation = [np.ones(self.nSteps),",
"= 0.5 * U0 * np.sum(M3N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ U0 * Q0",
"self.forward(signal, betaU, 2) # M3(t) * (1+betaU*N(t)) forwV = self.forward(signal, betaV, 3) #",
"2) # M3(t) * 1(t) M4One = self.forwardPartial(np.ones(self.nSteps), 3) # M4(t) * 1(t)",
"out.stokes[0]-stokes[2] / stokes[0]) # print \"V/I_original={0} - V/I_inferred={1} - V/I_trivial={2} - diff={3}\".format(out.stokes[3] /",
"\"\"\"Summary Returns ------- TYPE : Demodulate I and Q signals together \"\"\" def",
"stokes[3] / stokes[0], \\ # stV/stI, out.stokes[3] / out.stokes[0]-stokes[3] / stokes[0]) # pl.close('all')",
"-2.0 * I0 * betaI * self.backward(residual2, 0) + 2.0 * Q0 *",
"1) # M2(t) * N(t) M3N = self.forwardPartial(signal, 2) # M3(t) * N(t)",
"= self.forward(signal, betaI, 0) # M1(t) * (1+betaI*N(t)) forwQ = self.forward(signal, betaQ, 1)",
"the original sample self.nSteps = int(totalTime / dt) self.times = np.arange(self.nSteps) * self.dt",
"np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0] = 0.0 self.seeingFFT = np.sqrt(self.powerSeeing) * noiseFFT self.seeingFFT /=",
"y = np.copy(x) res = self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue = splinalg.eigsh(res, k=1, which='LM', return_eigenvectors=False) self.mu",
"signal and its power spectrum self.signal = [None] * 4 for i in",
"self.mu = 0.5 / (np.real(largestEigenvalue)) * 0.0002 t = 1.0 normL1 = []",
"3) # M4(t) * 1(t) A = np.zeros((3,3)) A[0,0] = Q0**2 * np.sum(M2N**2)",
"\\lambda ||alpha||_1 Args: rank (int, optional): rank of the solution niter (int, optional):",
"self.times = np.arange(self.nSteps) * self.dt # Frequency axis self.freq = fft.rfftfreq(self.nSteps, d=dt) #",
"out / np.sqrt(len(out)) def myIFFT(x): \"\"\" Return the IFFT for a real signal",
"* np.sum(M1One * M1N)) / (I0**2 * np.sum(M1N**2))) betaQ, betaU, betaV = np.abs(np.linalg.solve(A,b))",
"ValueError(\"Operation {} not supported.\".format(operation)) if ndarray.ndim != len(new_shape): raise ValueError(\"Shape mismatch: {} ->",
"np.sum(self.seeing**2), myTotalPower(self.seeingFFT) # Compute the signal and its power spectrum self.signal = [None]",
"= myIFFT(x) forwI = self.forward(signal, betaI, 0) # M1(t) * (1+betaI*N(t)) forwQ =",
"+ 2.0 * V0 * betaV * self.backward(residual2, 3) gradient = gradient1 +",
"Q0, U0, V0 = np.linalg.solve(A,b) if (I0 < 0): I0 = 1.0 if",
"* V0 * np.sum(M4One * M3N) b[2] = 0.5 * V0 * np.sum(M4N",
"A[0,2] A[1,2] = np.sum(forwU * forwV) A[2,1] = A[1,2] b = np.zeros(3) b[0]",
"self.signalIntegrated[i] += np.mean(self.signalIntegrated[i]) / self.signalToNoise * np.random.randn(self.nSamples) self.tIntegrated = np.arange(self.nSamples) * self.dtIntegration #",
"if (loop % 10): # Stokes parameters I0 = 0.5 * np.sum(forwI *",
"its power spectrum self.signal = [None] * 4 for i in range(4): self.signal[i]",
"(self.signalIntegrated[0]+self.signalIntegrated[1])) - \\ I0**2 * np.sum(M1One * M1N)) / (I0**2 * np.sum(M1N**2))) betaQ,",
"* self.backward(residual1, 2) - 2.0 * V0 * betaV * self.backward(residual1, 3) residual2",
"* (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0, V0 = np.linalg.solve(A,b) if (I0 < 0): I0 =",
"2.0 * U0 * betaU * self.backward(residual2, 2) + 2.0 * V0 *",
"dimensions. Example ------- >>> m = np.arange(0,100,1).reshape((10,10)) >>> n = bin_ndarray(m, new_shape=(5,5), operation='sum')",
"* self.backward(residual1, 1) - \\ 2.0 * U0 * betaU * self.backward(residual1, 2)",
"- U/I_trivial={2} - diff={3}\".format(out.stokes[2] / out.stokes[0], stokes[2] / stokes[0], \\ # stU/stI, out.stokes[2]",
"\\ I0**2 * np.sum(M1One * M1N)) / (I0**2 * np.sum(M1N**2))) betaQ, betaU, betaV",
"signalToNoise=0.0, seed=0, modulationType=0): \"\"\"Summary Parameters ---------- totalTime : TYPE Description dt : TYPE",
"* V0 * np.sum(M4N * M3N) A[2,1] = A[1,2] b = np.zeros(3) b[0]",
"self.seeing = myIFFT(self.seeingFFT) # Make sure that the total power is unity print",
"0): print \"It {0:4d} - l2={1:10.3e} - l1={2:10.4f} - l0={3:5.1f}% - I={4:11.5f} -",
"0.0 xNew /= np.sqrt(myTotalPower(xNew)) if (thresholdMethod == 'L2'): xNew = y - self.mu",
"that the total power is unity print 'Total variance = ', np.sum(self.seeing**2), myTotalPower(self.seeingFFT)",
"self.backward(residual2, 3) gradient = gradient1 + gradient2 if (thresholdMethod == 'hardLambda'): xNew =",
"np.zeros(self.nSteps) I0 = 0.9 Q0 = 0.1 U0 = 0.2 V0 = 0.3",
"beta[loop]*Nt)) # ax[loop].set_xlabel('Time [s]') # ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) # ax[loop].annotate # pl.tight_layout() # ax[0,0].plot(out.times,",
"with unit variance and multiply by the square root of the power spectrum",
"N(t) M3N = self.forwardPartial(signal, 2) # M3(t) * N(t) M4N = self.forwardPartial(signal, 3)",
"for state in range(4): sparseData = [] sparseRow = [] sparseCol = []",
"\\ V0 * Q0 * np.sum(M2One * M4N) - V0 * U0 *",
"0.0002 t = 1.0 normL1 = [] normL2 = [] normL0 = []",
"niter=10, lambdaValue=1.0): \"\"\" Solve the l1 regularized problem using the FISTA algorithm, that",
"+ Q0 * forwQ + U0 * forwU + V0 * forwV) gradient1",
"\"sum\": ndarray = ndarray.sum(-1*(i+1)) elif operation.lower() in [\"mean\", \"average\", \"avg\"]: ndarray = ndarray.mean(-1*(i+1))",
"- V/I={7:11.5f} - bI={8:11.5f} - bQ={9:11.5f} - bU={10:11.5f} - bV={11:11.5f}\".format(loop, normResidual, normSolutionL1, 100.0*normSolutionL0",
"+= np.mean(self.signalIntegrated[i]) / self.signalToNoise * np.random.randn(self.nSamples) self.tIntegrated = np.arange(self.nSamples) * self.dtIntegration # Generate",
"- diff={3}\".format(out.stokes[3] / out.stokes[0], stokes[3] / stokes[0], \\ # stV/stI, out.stokes[3] / out.stokes[0]-stokes[3]",
"\\ # stU/stI, out.stokes[2] / out.stokes[0]-stokes[2] / stokes[0]) # print \"V/I_original={0} - V/I_inferred={1}",
"\"\"\" out = fft.rfft(x) return out / np.sqrt(len(out)) def myIFFT(x): \"\"\" Return the",
"sample self.nSteps = int(totalTime / dt) self.times = np.arange(self.nSteps) * self.dt # Frequency",
"* Q0 * np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ Q0**2 * np.sum(M2One * M2N)",
"= tNew x = np.copy(xNew) normResidual = np.linalg.norm(residual1 + residual2) normSolutionL1 = np.linalg.norm(x,",
"*(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2] / stokes[0] * (1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3]",
"= np.sum(forwQ * forwV) A[2,0] = A[0,2] A[1,2] = np.sum(forwU * forwV) A[2,1]",
"10.0#self.beta[3] else: x = np.copy(initial) I0, Q0, U0, V0 = initialStokes xNew =",
"= np.abs((0.5 * I0 * np.sum(M1N * (self.signalIntegrated[0]+self.signalIntegrated[1])) - \\ I0**2 * np.sum(M1One",
"# print \"V/I_original={0} - V/I_inferred={1} - V/I_trivial={2} - diff={3}\".format(out.stokes[3] / out.stokes[0], stokes[3] /",
"self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps) else: temp = np.load('alphaBetaSamples.npz') self.alphaModulation = temp['arr_0'][0:self.nSteps]",
"stokes[0], \\ # stU/stI, out.stokes[2] / out.stokes[0]-stokes[2] / stokes[0]) # print \"V/I_original={0} -",
"ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2] / stokes[0] * (1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3] / stokes[0]",
"np.sum(M2One * M2N) - Q0 * U0 * np.sum(M3One * M2N) - Q0",
"scipy.fftpack as fft def bin_ndarray(ndarray, new_shape, operation='sum'): \"\"\" Bins an ndarray in all",
"\"\"\"Summary Parameters ---------- totalTime : TYPE Description dt : TYPE Description dtIntegration :",
"\\ 2.0 * U0 * betaU * self.backward(residual1, 2) - 2.0 * V0",
"{} -> {}\".format(ndarray.shape, new_shape)) compression_pairs = [(d, c//d) for d, c in zip(new_shape,",
"* forwV) A[2,1] = A[1,2] b = np.zeros(3) b[0] = 0.5 * np.sum(forwQ",
"\"\"\" return f[0]**2 + 2.0*np.sum(f[1:]**2) class randomDemodulator(object): \"\"\"Summary Returns ------- TYPE : Demodulate",
"i in range(2): temp = self.signal[0] * self.modulation[0] sign = (-1.0)**i for j",
"= A[0,1] A[0,2] = Q0 * V0 * np.sum(M4N * M2N) A[2,0] =",
"stokes[0] * (1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3] / stokes[0] * (1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing)))",
"betaV = np.abs(np.linalg.solve(A,b)) if (loop % 50 == 0): print \"It {0:4d} -",
"+ beta[loop]*Nt)) # ax[loop].set_xlabel('Time [s]') # ax[loop].set_ylabel('Stokes {0}'.format(stokesPar[loop])) # ax[loop].annotate # pl.tight_layout() #",
"M4(t) * 1(t) A = np.zeros((3,3)) A[0,0] = Q0**2 * np.sum(M2N**2) A[1,1] =",
"stokes = np.asarray([1.0, 1.2e-3, 5.e-3, 0.001]) # out = randomDemodulator(totalTime, dt, dtIntegration, stokes,",
"np.sum(z[1:] * z[1:].conj())).real / len(z) def softThreshold(self, x, lambdaValue): return np.fmax(0,1.0 - lambdaValue",
"def softThreshold(self, x, lambdaValue): return np.fmax(0,1.0 - lambdaValue / np.fmax(np.abs(x),1e-10)) * x def",
"dtIntegration = 0.01 #s # beta = np.asarray([15.0, 100.0, 100., 100.0]) # stokes",
"2*np.ones(self.nSteps) self.factor[0] = 1.0 def forward(self, signal, beta, ray): return self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self,",
"Q0 * np.sum(M2One * M3N) - U0**2 * np.sum(M3One * M3N) - U0",
"pl.subplots(nrows=1, ncols=4, figsize=(18,6)) # coefFourier[0] = 0.0 # Nt = myIFFT(coefFourier) # Nt",
"= np.sum(forwU * forwV) A[2,1] = A[1,2] b = np.zeros(3) b[0] = 0.5",
"l2={1:10.3e} - l1={2:10.4f} - l0={3:5.1f}% - I={4:11.5f} - Q/I={5:11.5f} - U/I={6:11.5f} - V/I={7:11.5f}",
"self.forward(signal, betaI, 0) # M1(t) * (1+betaI*N(t)) forwQ = self.forward(signal, betaQ, 1) #",
"= np.copy(x) res = self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue = splinalg.eigsh(res, k=1, which='LM', return_eigenvectors=False) self.mu =",
"self.signalIntegrated[1] - (I0 * forwI - Q0 * forwQ - U0 * forwU",
"dimensions must match number of input dimensions. Example ------- >>> m = np.arange(0,100,1).reshape((10,10))",
"bQ={9:11.5f} - bU={10:11.5f} - bV={11:11.5f}\".format(loop, normResidual, normSolutionL1, 100.0*normSolutionL0 / self.nSteps, I0, Q0/I0, U0/I0,",
"the noise with the appropriate power spectrum noise = np.random.randn(self.nSteps) noiseFFT = myFFT(noise)",
"= 0.9 Q0 = 0.1 U0 = 0.2 V0 = 0.3 betaI =",
"forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A",
"of the real signal \"\"\" out = fft.rfft(x) return out / np.sqrt(len(out)) def",
"to generate the noise with the appropriate power spectrum noise = np.random.randn(self.nSteps) noiseFFT",
"* np.sum(M3One * M2N) - Q0 * V0 * np.sum(M4One * M2N) b[1]",
"{} not supported.\".format(operation)) if ndarray.ndim != len(new_shape): raise ValueError(\"Shape mismatch: {} -> {}\".format(ndarray.shape,",
": float Fourier coefficients Returns ------- float : signal \"\"\" out = fft.irfft(x)",
"== 'hardPercentage'): xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod ==",
"1.2e-3, 5.e-3, 0.001]) # out = randomDemodulator(totalTime, dt, dtIntegration, stokes, beta, seed=123, signalToNoise=1e3)",
"* forwV) A[2,0] = A[0,2] A[1,2] = np.sum(forwU * forwV) A[2,1] = A[1,2]",
"= self.forward(signal, betaV, 3) # M4(t) * (1+betaV*N(t)) residual1 = self.signalIntegrated[0] - (I0",
"optional): rank of the solution niter (int, optional): number of iterations Returns: TYPE:",
"M2One = self.forwardPartial(np.ones(self.nSteps), 1) # M2(t) * 1(t) M3One = self.forwardPartial(np.ones(self.nSteps), 2) #",
"* N(t) M1One = self.forwardPartial(np.ones(self.nSteps), 0) # M1(t) * 1(t) M2One = self.forwardPartial(np.ones(self.nSteps),",
"+ (t-1.0) / tNew * (xNew - x) t = tNew x =",
"myTotalPower(f): \"\"\" Return the power spectrum of a signal Parameters ---------- f :",
"fft.irfft(x) return out * np.sqrt(len(out)) def myTotalPower(f): \"\"\" Return the power spectrum of",
"* self.nSteps) self.signalIntegrated = [None] * 2 for i in range(2): temp =",
"forwI = self.sparseM[0].dot(np.zeros(self.nSteps)+1.0) forwQ = self.sparseM[1].dot(np.zeros(self.nSteps)+1.0) forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0",
"return_eigenvectors=False) self.mu = 0.5 / (np.real(largestEigenvalue)) * 0.0002 t = 1.0 normL1 =",
"* I0 * betaI * self.backward(residual2, 0) + 2.0 * Q0 * betaQ",
": signal \"\"\" out = fft.irfft(x) return out * np.sqrt(len(out)) def myTotalPower(f): \"\"\"",
"A[2,1] = A[1,2] b = np.zeros(3) b[0] = 0.5 * Q0 * np.sum(M2N",
"*(1.0+beta[0]*Nt)) # ax[0,1].plot(out.signal[1]) # ax[0,1].plot(stokes[1] / stokes[0] *(1.0+beta[1]*Nt)) # ax[1,0].plot(out.signal[2]) # ax[1,0].plot(stokes[2] /",
"Description dtIntegration : TYPE Description seed : int, optional Description Returns ------- TYPE",
"based on the target shape, by summing or averaging. Number of output dimensions",
"A[1,2] b = np.zeros(3) b[0] = 0.5 * Q0 * np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1]))",
"print \"U/I_original={0} - U/I_inferred={1} - U/I_trivial={2} - diff={3}\".format(out.stokes[2] / out.stokes[0], stokes[2] / stokes[0],",
"2) # M3(t) * (1+betaU*N(t)) forwV = self.forward(signal, betaV, 3) # M4(t) *",
"= [np.ones(self.nSteps), \\ np.cos(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*self.alphaModulation) * np.cos(2.0*(self.alphaModulation-2.0*self.betaModulation)),\\ np.sin(2.0*(2.0*self.betaModulation-self.alphaModulation))] self.integrationTime = self.dtIntegration",
"i in range(self.nSamples): for j in range(self.lengthSample): sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop) loop += 1",
"backward(self, z, ray): return self.factor * myFFT(self.sparseMStar[ray].dot(z)) def totalPower(self, z): return (z[0] *",
"x : float Fourier coefficients Returns ------- float : signal \"\"\" out =",
"Parameters ---------- x : float Fourier coefficients Returns ------- float : signal \"\"\"",
"M3N) A[2,1] = A[1,2] b = np.zeros(3) b[0] = 0.5 * Q0 *",
"1e-3 # Seeing amplitude M1N = self.forwardPartial(signal, 0) # M1(t) * N(t) M2N",
"for p in compression_pairs for l in p] ndarray = ndarray.reshape(flattened) for i",
"0.3 betaI = 10.0#self.beta[0] betaQ = 10.0#self.beta[1] betaU = 10.0#self.beta[2] betaV = 10.0#self.beta[3]",
"I0, Q0, U0, V0 # totalTime = 1.0 # s # dt =",
"np.sum(forwQ * forwU) A[1,0] = A[0,1] A[0,2] = np.sum(forwQ * forwV) A[2,0] =",
"self.forwardPartial(np.ones(self.nSteps), 2) # M3(t) * 1(t) M4One = self.forwardPartial(np.ones(self.nSteps), 3) # M4(t) *",
"0.5 * np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] = 0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0,",
"stokes[0] * (1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing))) # ax[2,0].semilogy(np.abs(myFFT(Nt))) # ax[2,1].semilogy(normL21) # ax[2,1].semilogy(normL11) # ax[3,0].plot(out.signalIntegrated[0])",
"taking into account some normalization Parameters ---------- x : float Fourier coefficients Returns",
"# ax[1,0].plot(stokes[2] / stokes[0] * (1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3] / stokes[0] *",
"Returns ------- TYPE : Demodulate I and Q signals together \"\"\" def __init__(self,",
"# Frequency axis self.freq = fft.rfftfreq(self.nSteps, d=dt) # Betas and Stokes parameters self.beta",
"* np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A = np.zeros((3,3)) A[0,0] = np.sum(forwQ**2) A[1,1]",
"* V0 * betaV * self.backward(residual1, 3) residual2 = self.signalIntegrated[1] - (I0 *",
"# Stokes parameters I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A",
"M3N = self.forwardPartial(signal, 2) # M3(t) * N(t) M4N = self.forwardPartial(signal, 3) #",
"np.sum(M4One * M3N) b[2] = 0.5 * V0 * np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1])) -",
"= A[0,2] A[1,2] = U0 * V0 * np.sum(M4N * M3N) A[2,1] =",
"that solves the following problem: argmin_O ||y - M*F^{-1}*alpha||_2 + \\lambda ||alpha||_1 Args:",
"fft.rfft(x) return out / np.sqrt(len(out)) def myIFFT(x): \"\"\" Return the IFFT for a",
"betaU = 10.0#self.beta[2] betaV = 10.0#self.beta[3] else: x = np.copy(initial) I0, Q0, U0,",
"and Stokes parameters self.beta = beta self.stokes = stokes # Generate Gaussian noise",
"(self.modulationType == 0): self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps) else: temp = np.load('alphaBetaSamples.npz')",
"* forwU - V0 * forwV) gradient2 = -2.0 * I0 * betaI",
"Q0 * np.sum(M2N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ Q0**2 * np.sum(M2One * M2N) -",
"M3(t) * N(t) M4N = self.forwardPartial(signal, 3) # M4(t) * N(t) M1One =",
"= 0.5 * V0 * np.sum(M4N * (self.signalIntegrated[0]-self.signalIntegrated[1])) - \\ V0 * Q0",
"(self.signalIntegrated[0]+self.signalIntegrated[1])) / np.sum(forwI**2) A = np.zeros((3,3)) A[0,0] = np.sum(forwQ**2) A[1,1] = np.sum(forwU**2) A[2,2]",
"as fft def bin_ndarray(ndarray, new_shape, operation='sum'): \"\"\" Bins an ndarray in all axes",
"= myFFT(noise) self.powerSeeing = np.interp(np.abs(self.freq), self.powerLites[:,0], self.powerLites[:,1]) self.powerSeeing[0] = 0.0 self.seeingFFT = np.sqrt(self.powerSeeing)",
"the l1 regularized problem using the FISTA algorithm, that solves the following problem:",
"of output dimensions must match number of input dimensions. Example ------- >>> m",
"x, (I0, Q0, U0, V0), (betaI, betaQ, betaU, betaV), normL2, normL1, normL0 def",
"/ stokes[0], \\ # stU/stI, out.stokes[2] / out.stokes[0]-stokes[2] / stokes[0]) # print \"V/I_original={0}",
"using the FISTA algorithm, that solves the following problem: argmin_O ||y - M*F^{-1}*alpha||_2",
"betaV) normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0) return x, (I0, Q0, U0, V0), (betaI, betaQ, betaU,",
"in range(2): temp = self.signal[0] * self.modulation[0] sign = (-1.0)**i for j in",
"* forwV) gradient1 = -2.0 * I0 * betaI * self.backward(residual1, 0) -",
"Stokes parameters self.beta = beta self.stokes = stokes # Generate Gaussian noise with",
"self.sparseM[ray].dot(1.0+beta*signal) def forwardPartial(self, signal, ray): return self.sparseM[ray].dot(signal) def backward(self, z, ray): return self.factor",
"the following problem: argmin_O ||y - M*F^{-1}*alpha||_2 + \\lambda ||alpha||_1 Args: rank (int,",
"(thresholdMethod == 'L2'): xNew = y - self.mu * np.real(gradient) tNew = 0.5*(1+np.sqrt(1+4.0*t**2))",
"2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType == 0): self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps) else:",
"ValueError(\"Shape mismatch: {} -> {}\".format(ndarray.shape, new_shape)) compression_pairs = [(d, c//d) for d, c",
"100., 100.0]) # stokes = np.asarray([1.0, 1.2e-3, 5.e-3, 0.001]) # out = randomDemodulator(totalTime,",
"Q0 = 1e-3 if (np.abs(U0) > 1.0): U0 = 1e-3 if (np.abs(V0) >",
"xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'soft'): xNew",
"iterations Returns: TYPE: Description \"\"\" if (initial == None): x = np.zeros(self.nSteps) I0",
"'average', 'avg']: raise ValueError(\"Operation {} not supported.\".format(operation)) if ndarray.ndim != len(new_shape): raise ValueError(\"Shape",
"\"V/I_original={0} - V/I_inferred={1} - V/I_trivial={2} - diff={3}\".format(out.stokes[3] / out.stokes[0], stokes[3] / stokes[0], \\",
"xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'hardPercentage'): xNew",
"tNew x = np.copy(xNew) normResidual = np.linalg.norm(residual1 + residual2) normSolutionL1 = np.linalg.norm(x, 1)",
"N(t) M2N = self.forwardPartial(signal, 1) # M2(t) * N(t) M3N = self.forwardPartial(signal, 2)",
"# M3(t) * N(t) M4N = self.forwardPartial(signal, 3) # M4(t) * N(t) M1One",
"and multiply by the square root of the power spectrum # to generate",
"10.0#self.beta[2] betaV = 10.0#self.beta[3] else: x = np.copy(initial) I0, Q0, U0, V0 =",
"/ self.nSteps, I0, Q0/I0, U0/I0, V0/I0, betaI, betaQ, betaU, betaV) normL2.append(normResidual) normL1.append(normSolutionL1) normL0.append(normSolutionL0)",
"self.mu * np.real(gradient), lambdaValue) xNew[0] = 0.0 xNew /= np.sqrt(myTotalPower(xNew)) if (thresholdMethod ==",
"* M4N) - V0 * U0 * np.sum(M3One * M4N) - V0**2 *",
"forwV = self.forward(signal, betaV, 3) # M4(t) * (1+betaV*N(t)) residual1 = self.signalIntegrated[0] -",
"M*F^{-1}*alpha||_2 + \\lambda ||alpha||_1 Args: rank (int, optional): rank of the solution niter",
"A[2,2] = np.sum(forwV**2) A[0,1] = np.sum(forwQ * forwU) A[1,0] = A[0,1] A[0,2] =",
"input dimensions. Example ------- >>> m = np.arange(0,100,1).reshape((10,10)) >>> n = bin_ndarray(m, new_shape=(5,5),",
"= dt self.dtIntegration = dtIntegration self.seed = seed self.signalToNoise = signalToNoise self.modulationType =",
"np.sum(forwQ * forwV) A[2,0] = A[0,2] A[1,2] = np.sum(forwU * forwV) A[2,1] =",
"flattened = [l for p in compression_pairs for l in p] ndarray =",
"with random angles # self.modulation = [np.ones(self.nSteps), 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0, 2.0*np.random.rand(self.nSteps)-1.0] if (self.modulationType ==",
"b[0] = 0.5 * np.sum(forwQ * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[1] = 0.5 * np.sum(forwU *",
"== \"sum\": ndarray = ndarray.sum(-1*(i+1)) elif operation.lower() in [\"mean\", \"average\", \"avg\"]: ndarray =",
"= initialStokes xNew = np.copy(x) y = np.copy(x) res = self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue =",
"= Q0 * V0 * np.sum(M4N * M2N) A[2,0] = A[0,2] A[1,2] =",
"totalTime = 1.0 # s # dt = 0.001 # s # dtIntegration",
"account some normalization Parameters ---------- x : float Signal time series Returns -------",
"(t-1.0) / tNew * (xNew - x) t = tNew x = np.copy(xNew)",
"- U0 * V0 * np.sum(M4One * M3N) b[2] = 0.5 * V0",
"t = tNew x = np.copy(xNew) normResidual = np.linalg.norm(residual1 + residual2) normSolutionL1 =",
"* betaU * self.backward(residual1, 2) - 2.0 * V0 * betaV * self.backward(residual1,",
"self.dtIntegration self.lengthSample = int(self.dtIntegration / self.dt) self.nSamples = int(self.dt / self.dtIntegration * self.nSteps)",
"raise ValueError(\"Shape mismatch: {} -> {}\".format(ndarray.shape, new_shape)) compression_pairs = [(d, c//d) for d,",
"= self.softThreshold(y - self.mu * np.real(gradient), lambdaValue) xNew[0] = 0.0 xNew /= np.sqrt(myTotalPower(xNew))",
"U/I={6:11.5f} - V/I={7:11.5f} - bI={8:11.5f} - bQ={9:11.5f} - bU={10:11.5f} - bV={11:11.5f}\".format(loop, normResidual, normSolutionL1,",
"if (self.modulationType == 0): self.alphaModulation = 0.5*np.pi*np.random.rand(self.nSteps) self.betaModulation = 0.5*np.pi*np.random.rand(self.nSteps) else: temp =",
"% 10): # Stokes parameters I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1])) /",
"= np.copy(x) y = np.copy(x) res = self.sparseMStar[0].dot(self.sparseM[0]) largestEigenvalue = splinalg.eigsh(res, k=1, which='LM',",
"* Q0 * np.sum(M2One * M3N) - U0**2 * np.sum(M3One * M3N) -",
"= fft.rfft(x) return out / np.sqrt(len(out)) def myIFFT(x): \"\"\" Return the IFFT for",
"range(niter): signal = myIFFT(x) forwI = self.forward(signal, betaI, 0) # M1(t) * (1+betaI*N(t))",
"# pl.close('all') # f, ax = pl.subplots(nrows=1, ncols=4, figsize=(18,6)) # coefFourier[0] = 0.0",
"forwU = self.sparseM[2].dot(np.zeros(self.nSteps)+1.0) forwV = self.sparseM[3].dot(np.zeros(self.nSteps)+1.0) I0 = 0.5 * np.sum(forwI * (self.signalIntegrated[0]+self.signalIntegrated[1]))",
"= out.FISTA(thresholdMethod = 'soft', niter = 600, lambdaValue = 0.000000051) # stI, stQ,",
"ndarray.mean(-1*(i+1)) return ndarray def myFFT(x): \"\"\" Return the FFT of a real signal",
"sparseData.append(self.modulation[state][loop]) sparseRow.append(i) sparseCol.append(loop) loop += 1 self.sparseM[state] = sp.coo_matrix((sparseData, (sparseRow, sparseCol)), shape=(self.nSamples, self.nSteps))",
"self.seeingFFT /= np.sqrt(myTotalPower(self.seeingFFT)) self.seeing = myIFFT(self.seeingFFT) # Make sure that the total power",
"* (1.0+beta[2]*Nt)) # ax[1,1].plot(out.signal[3]) # ax[1,1].plot(stokes[3] / stokes[0] * (1.0+beta[3]*Nt)) # ax[2,0].semilogy(np.abs(myFFT(out.seeing))) #",
"stokes[1] / stokes[0], \\ # stQ/stI, out.stokes[1] / out.stokes[0]-stokes[1] / stokes[0]) # print",
"* np.real(gradient), lambdaValue) if (thresholdMethod == 'hardPercentage'): xNew = self.hardThreshold(y - self.mu *",
"# stokesPar = ['I', 'Q', 'U', 'V'] # loop = 0 # for",
"= 0.5*(1+np.sqrt(1+4.0*t**2)) y = xNew + (t-1.0) / tNew * (xNew - x)",
"np.copy(xNew) normResidual = np.linalg.norm(residual1 + residual2) normSolutionL1 = np.linalg.norm(x, 1) normSolutionL0 = np.linalg.norm(x,",
"I0**2 * np.sum(M1One * M1N)) / (I0**2 * np.sum(M1N**2))) betaQ, betaU, betaV =",
"[None] * 4 for state in range(4): sparseData = [] sparseRow = []",
"* np.sum(forwU * (self.signalIntegrated[0]-self.signalIntegrated[1])) b[2] = 0.5 * np.sum(forwV * (self.signalIntegrated[0]-self.signalIntegrated[1])) Q0, U0,",
"TYPE: Description \"\"\" if (initial == None): x = np.zeros(self.nSteps) I0 = 0.9",
"'hardLambda'): xNew = self.hardThreshold(y - self.mu * np.real(gradient), lambdaValue) if (thresholdMethod == 'hardPercentage'):",
"10.0#self.beta[0] betaQ = 10.0#self.beta[1] betaU = 10.0#self.beta[2] betaV = 10.0#self.beta[3] else: x =",
"* forwQ + U0 * forwU + V0 * forwV) gradient1 = -2.0",
"\"\"\" if not operation.lower() in ['sum', 'mean', 'average', 'avg']: raise ValueError(\"Operation {} not"
] |
[
"scene where the LMS device is installed.\") } class ConfigurationForm(forms.ModelForm): class Meta: model",
"fields = ('plant', 'capacity', 'unit', 'image') help_texts = { 'plant': _('The plant, this",
"'height', 'major_diameter', 'minor_diameter', 'diameter', 'unit', 'alignment') labels = { 'major_diameter': _('Major Diameter'), 'minor_diameter':",
"Tank, Configuration class TankForm(forms.ModelForm): plant = forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...') class Meta: model =",
"Meta: model = Tank fields = ('plant', 'capacity', 'unit', 'image') help_texts = {",
"forms from django.utils.translation import gettext_lazy as _ from plant.models import Plant from .models",
"<reponame>oteejay/lms from django import forms from django.utils.translation import gettext_lazy as _ from plant.models",
"for its capacity.'), 'image': _(\"A picture of the scene where the LMS device",
"help_texts = { 'unit': _('The unit of measurement utilized for this configuration.') }",
"is installed.\") } class ConfigurationForm(forms.ModelForm): class Meta: model = Configuration fields = ('shape',",
"import Plant from .models import Tank, Configuration class TankForm(forms.ModelForm): plant = forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select",
"of measurement utilized for this configuration.') } widgets = { 'shape': forms.Select(), 'alignment':",
"_ from plant.models import Plant from .models import Tank, Configuration class TankForm(forms.ModelForm): plant",
"import gettext_lazy as _ from plant.models import Plant from .models import Tank, Configuration",
"_('Major Diameter'), 'minor_diameter': _('Minor Diameter') } help_texts = { 'unit': _('The unit of",
"fields = ('shape', 'width', 'length', 'height', 'major_diameter', 'minor_diameter', 'diameter', 'unit', 'alignment') labels =",
"from django import forms from django.utils.translation import gettext_lazy as _ from plant.models import",
"tank is located in.'), 'unit': _('The unit of measurement for its capacity.'), 'image':",
"picture of the scene where the LMS device is installed.\") } class ConfigurationForm(forms.ModelForm):",
"LMS device is installed.\") } class ConfigurationForm(forms.ModelForm): class Meta: model = Configuration fields",
"= { 'unit': _('The unit of measurement utilized for this configuration.') } widgets",
"class Meta: model = Tank fields = ('plant', 'capacity', 'unit', 'image') help_texts =",
"'unit', 'image') help_texts = { 'plant': _('The plant, this tank is located in.'),",
"django import forms from django.utils.translation import gettext_lazy as _ from plant.models import Plant",
"device is installed.\") } class ConfigurationForm(forms.ModelForm): class Meta: model = Configuration fields =",
"= forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...') class Meta: model = Tank fields = ('plant', 'capacity',",
"is located in.'), 'unit': _('The unit of measurement for its capacity.'), 'image': _(\"A",
"import forms from django.utils.translation import gettext_lazy as _ from plant.models import Plant from",
"class TankForm(forms.ModelForm): plant = forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...') class Meta: model = Tank fields",
"_(\"A picture of the scene where the LMS device is installed.\") } class",
"{ 'major_diameter': _('Major Diameter'), 'minor_diameter': _('Minor Diameter') } help_texts = { 'unit': _('The",
"_('The unit of measurement for its capacity.'), 'image': _(\"A picture of the scene",
"this tank is located in.'), 'unit': _('The unit of measurement for its capacity.'),",
"} class ConfigurationForm(forms.ModelForm): class Meta: model = Configuration fields = ('shape', 'width', 'length',",
"model = Configuration fields = ('shape', 'width', 'length', 'height', 'major_diameter', 'minor_diameter', 'diameter', 'unit',",
"'major_diameter', 'minor_diameter', 'diameter', 'unit', 'alignment') labels = { 'major_diameter': _('Major Diameter'), 'minor_diameter': _('Minor",
"Plant from .models import Tank, Configuration class TankForm(forms.ModelForm): plant = forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...')",
"from plant.models import Plant from .models import Tank, Configuration class TankForm(forms.ModelForm): plant =",
"capacity.'), 'image': _(\"A picture of the scene where the LMS device is installed.\")",
"} help_texts = { 'unit': _('The unit of measurement utilized for this configuration.')",
"{ 'plant': _('The plant, this tank is located in.'), 'unit': _('The unit of",
"measurement utilized for this configuration.') } widgets = { 'shape': forms.Select(), 'alignment': forms.Select()",
"Diameter'), 'minor_diameter': _('Minor Diameter') } help_texts = { 'unit': _('The unit of measurement",
"'diameter', 'unit', 'alignment') labels = { 'major_diameter': _('Major Diameter'), 'minor_diameter': _('Minor Diameter') }",
"{ 'unit': _('The unit of measurement utilized for this configuration.') } widgets =",
"model = Tank fields = ('plant', 'capacity', 'unit', 'image') help_texts = { 'plant':",
"plant.models import Plant from .models import Tank, Configuration class TankForm(forms.ModelForm): plant = forms.ModelChoiceField(queryset=Plant.objects.all(),",
"'unit': _('The unit of measurement for its capacity.'), 'image': _(\"A picture of the",
"Meta: model = Configuration fields = ('shape', 'width', 'length', 'height', 'major_diameter', 'minor_diameter', 'diameter',",
"as _ from plant.models import Plant from .models import Tank, Configuration class TankForm(forms.ModelForm):",
"Tank fields = ('plant', 'capacity', 'unit', 'image') help_texts = { 'plant': _('The plant,",
"_('Minor Diameter') } help_texts = { 'unit': _('The unit of measurement utilized for",
"= Configuration fields = ('shape', 'width', 'length', 'height', 'major_diameter', 'minor_diameter', 'diameter', 'unit', 'alignment')",
"utilized for this configuration.') } widgets = { 'shape': forms.Select(), 'alignment': forms.Select() }",
"of the scene where the LMS device is installed.\") } class ConfigurationForm(forms.ModelForm): class",
"'unit', 'alignment') labels = { 'major_diameter': _('Major Diameter'), 'minor_diameter': _('Minor Diameter') } help_texts",
"= Tank fields = ('plant', 'capacity', 'unit', 'image') help_texts = { 'plant': _('The",
"empty_label='...select plant...') class Meta: model = Tank fields = ('plant', 'capacity', 'unit', 'image')",
"class Meta: model = Configuration fields = ('shape', 'width', 'length', 'height', 'major_diameter', 'minor_diameter',",
"help_texts = { 'plant': _('The plant, this tank is located in.'), 'unit': _('The",
"Diameter') } help_texts = { 'unit': _('The unit of measurement utilized for this",
"plant, this tank is located in.'), 'unit': _('The unit of measurement for its",
"import Tank, Configuration class TankForm(forms.ModelForm): plant = forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...') class Meta: model",
"= { 'major_diameter': _('Major Diameter'), 'minor_diameter': _('Minor Diameter') } help_texts = { 'unit':",
"= { 'plant': _('The plant, this tank is located in.'), 'unit': _('The unit",
".models import Tank, Configuration class TankForm(forms.ModelForm): plant = forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...') class Meta:",
"TankForm(forms.ModelForm): plant = forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...') class Meta: model = Tank fields =",
"_('The unit of measurement utilized for this configuration.') } widgets = { 'shape':",
"= ('plant', 'capacity', 'unit', 'image') help_texts = { 'plant': _('The plant, this tank",
"from .models import Tank, Configuration class TankForm(forms.ModelForm): plant = forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...') class",
"its capacity.'), 'image': _(\"A picture of the scene where the LMS device is",
"where the LMS device is installed.\") } class ConfigurationForm(forms.ModelForm): class Meta: model =",
"'capacity', 'unit', 'image') help_texts = { 'plant': _('The plant, this tank is located",
"'image': _(\"A picture of the scene where the LMS device is installed.\") }",
"unit of measurement utilized for this configuration.') } widgets = { 'shape': forms.Select(),",
"installed.\") } class ConfigurationForm(forms.ModelForm): class Meta: model = Configuration fields = ('shape', 'width',",
"= ('shape', 'width', 'length', 'height', 'major_diameter', 'minor_diameter', 'diameter', 'unit', 'alignment') labels = {",
"'length', 'height', 'major_diameter', 'minor_diameter', 'diameter', 'unit', 'alignment') labels = { 'major_diameter': _('Major Diameter'),",
"the scene where the LMS device is installed.\") } class ConfigurationForm(forms.ModelForm): class Meta:",
"'alignment') labels = { 'major_diameter': _('Major Diameter'), 'minor_diameter': _('Minor Diameter') } help_texts =",
"'width', 'length', 'height', 'major_diameter', 'minor_diameter', 'diameter', 'unit', 'alignment') labels = { 'major_diameter': _('Major",
"'minor_diameter', 'diameter', 'unit', 'alignment') labels = { 'major_diameter': _('Major Diameter'), 'minor_diameter': _('Minor Diameter')",
"located in.'), 'unit': _('The unit of measurement for its capacity.'), 'image': _(\"A picture",
"gettext_lazy as _ from plant.models import Plant from .models import Tank, Configuration class",
"from django.utils.translation import gettext_lazy as _ from plant.models import Plant from .models import",
"unit of measurement for its capacity.'), 'image': _(\"A picture of the scene where",
"forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...') class Meta: model = Tank fields = ('plant', 'capacity', 'unit',",
"'image') help_texts = { 'plant': _('The plant, this tank is located in.'), 'unit':",
"Configuration class TankForm(forms.ModelForm): plant = forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...') class Meta: model = Tank",
"'major_diameter': _('Major Diameter'), 'minor_diameter': _('Minor Diameter') } help_texts = { 'unit': _('The unit",
"'plant': _('The plant, this tank is located in.'), 'unit': _('The unit of measurement",
"of measurement for its capacity.'), 'image': _(\"A picture of the scene where the",
"plant...') class Meta: model = Tank fields = ('plant', 'capacity', 'unit', 'image') help_texts",
"('plant', 'capacity', 'unit', 'image') help_texts = { 'plant': _('The plant, this tank is",
"Configuration fields = ('shape', 'width', 'length', 'height', 'major_diameter', 'minor_diameter', 'diameter', 'unit', 'alignment') labels",
"'unit': _('The unit of measurement utilized for this configuration.') } widgets = {",
"'minor_diameter': _('Minor Diameter') } help_texts = { 'unit': _('The unit of measurement utilized",
"measurement for its capacity.'), 'image': _(\"A picture of the scene where the LMS",
"class ConfigurationForm(forms.ModelForm): class Meta: model = Configuration fields = ('shape', 'width', 'length', 'height',",
"ConfigurationForm(forms.ModelForm): class Meta: model = Configuration fields = ('shape', 'width', 'length', 'height', 'major_diameter',",
"django.utils.translation import gettext_lazy as _ from plant.models import Plant from .models import Tank,",
"_('The plant, this tank is located in.'), 'unit': _('The unit of measurement for",
"plant = forms.ModelChoiceField(queryset=Plant.objects.all(), empty_label='...select plant...') class Meta: model = Tank fields = ('plant',",
"in.'), 'unit': _('The unit of measurement for its capacity.'), 'image': _(\"A picture of",
"labels = { 'major_diameter': _('Major Diameter'), 'minor_diameter': _('Minor Diameter') } help_texts = {",
"('shape', 'width', 'length', 'height', 'major_diameter', 'minor_diameter', 'diameter', 'unit', 'alignment') labels = { 'major_diameter':",
"the LMS device is installed.\") } class ConfigurationForm(forms.ModelForm): class Meta: model = Configuration"
] |
[
"and py < res[1]: diff = torch.Tensor([hm[py - 1][px] - hm[py - 1][px",
"scores.dim() == 4, 'Score maps should be 4-dim' maxval, idx = torch.max(scores.view(scores.size(0), scores.size(1),",
"* num_samples) #take top N images with smallesr error. sorted_list = np.argsort(max_error_list) for",
"below threshold while ignoring values with a -1 ''' if dists.ne(-1).sum() > 0:",
"get predictions from score maps in torch Tensor return type: torch.LongTensor ''' assert",
"threshold while ignoring values with a -1 ''' if dists.ne(-1).sum() > 0: return",
"0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy() else: return -1 def accuracy(output, target, idxs, thr=0.5):",
"return acc def final_preds_bbox(output, bbox, res): preds = get_preds(output) # float typ preds",
"= 0 cnt = 0 for i in range(len(idxs)): acc[i+1] = dist_acc(dists[idxs[i]-1], thr=thr)",
"maxval.gt(0).repeat(1, 1, 2).float() preds *= pred_mask return preds def calc_dists(preds, target, normalize): preds",
"import math import numpy as np import matplotlib.pyplot as plt from random import",
"= torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else: dists[c, n] = -1 return dists def dist_acc(dists, thr=0.5):",
"preds = preds.view(1, preds.size()) return preds def d3_acc(preds, gts, percent = .5): num_samples",
"max_error_list.append(np.max(res[0:4])) res_list.append(res) # if not np.any(res[0:4]>10): #false prediction # acc += res #",
"<reponame>ReEn-Neom/ReEn.Neom-source-code- from __future__ import absolute_import import math import numpy as np import matplotlib.pyplot",
"for i in range(len(idxs)): acc[i+1] = dist_acc(dists[idxs[i]-1], thr=thr) if acc[i+1] >= 0: avg_acc",
"from .transforms import transform, transform_preds __all__ = ['accuracy', 'AverageMeter'] def get_preds(scores): ''' get",
"hit = 0 # miss_list = [] max_error_list = [] #max angle error",
"import * from .transforms import transform, transform_preds __all__ = ['accuracy', 'AverageMeter'] def get_preds(scores):",
"PCK, but uses ground truth heatmap rather than x,y locations First value to",
"preds[i, j, :] / res * np.array([width, height]) + np.array([bbox[0][i], bbox[0][i]]) return torch.from_numpy(preds)",
"average accuracy across 'idxs', followed by individual accuracies ''' preds = get_preds(output) gts",
"dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy() else: return -1 def accuracy(output, target, idxs, thr=0.5): ''' Calculate",
"res): preds = get_preds(output) # float typ preds = preds.numpy() for i in",
"dists = calc_dists(preds, gts, norm) acc = torch.zeros(len(idxs)+1) avg_acc = 0 cnt =",
"2], hm[py][px - 1]-hm[py - 2][px - 1]]) coords[n][p] += diff.sign() * .25",
"range(top_n): acc += res_list[sorted_list[i]] return (acc/top_n)[:4] class AverageMeter(object): \"\"\"Computes and stores the average",
"get_preds(output) # float type # pose-processing for n in range(coords.size(0)): for p in",
"in range(num_samples): pred = np.array(preds[i]) gt = np.array(gts[i]) res = np.abs(pred - gt)",
"self.val = val self.sum += val * n self.count += n self.avg =",
"as plt from random import randint import torch from .misc import * from",
"= torch.floor((preds[:,:,1] - 1) / scores.size(3)) + 1 pred_mask = maxval.gt(0).repeat(1, 1, 2).float()",
"= idx.repeat(1, 1, 2).float() preds[:,:,0] = (preds[:,:,0] - 1) % scores.size(3) + 1",
"idx.view(scores.size(0), scores.size(1), 1) + 1 preds = idx.repeat(1, 1, 2).float() preds[:,:,0] = (preds[:,:,0]",
"range(preds.shape[0]): width = bbox[2][i] - bbox[0][i] height = bbox[3][i] - bbox[1][i] for j",
"is average accuracy across 'idxs', followed by individual accuracies ''' preds = get_preds(output)",
"1]-hm[py - 2][px - 1]]) coords[n][p] += diff.sign() * .25 coords[:, :, 0]",
"py = int(math.floor(coords[n][p][1])) if px > 1 and px < res[0] and py",
"but uses ground truth heatmap rather than x,y locations First value to be",
"bbox[3][i] - bbox[1][i] for j in range(preds.shape[1]): preds[i, j, :] = preds[i, j,",
"= preds[i, j, :] / res * np.array([width, height]) + np.array([bbox[0][i], bbox[0][i]]) return",
"* np.array([width, height]) + np.array([bbox[0][i], bbox[0][i]]) return torch.from_numpy(preds) def final_preds(output, center, scale, res):",
"0 self.count = 0 def update(self, val, n=1): self.val = val self.sum +=",
"\"\"\"Computes and stores the average and current value\"\"\" def __init__(self): self.reset() def reset(self):",
"1][px] - hm[py - 1][px - 2], hm[py][px - 1]-hm[py - 2][px -",
"return (acc/top_n)[:4] class AverageMeter(object): \"\"\"Computes and stores the average and current value\"\"\" def",
"torch.zeros(len(idxs)+1) avg_acc = 0 cnt = 0 for i in range(len(idxs)): acc[i+1] =",
"= avg_acc / cnt return acc def final_preds_bbox(output, bbox, res): preds = get_preds(output)",
"target[n,c,:])/normalize[n] else: dists[c, n] = -1 return dists def dist_acc(dists, thr=0.5): ''' Return",
"% scores.size(3) + 1 preds[:,:,1] = torch.floor((preds[:,:,1] - 1) / scores.size(3)) + 1",
"num_samples) #take top N images with smallesr error. sorted_list = np.argsort(max_error_list) for i",
":] = preds[i, j, :] / res * np.array([width, height]) + np.array([bbox[0][i], bbox[0][i]])",
"preds[:,:,1] = torch.floor((preds[:,:,1] - 1) / scores.size(3)) + 1 pred_mask = maxval.gt(0).repeat(1, 1,",
"1 preds[:,:,1] = torch.floor((preds[:,:,1] - 1) / scores.size(3)) + 1 pred_mask = maxval.gt(0).repeat(1,",
"by individual accuracies ''' preds = get_preds(output) gts = get_preds(target) norm = torch.ones(preds.size(0))*output.size(3)/4.0",
"0: avg_acc = avg_acc + acc[i+1] cnt += 1 if cnt != 0:",
"bbox[2][i] - bbox[0][i] height = bbox[3][i] - bbox[1][i] for j in range(preds.shape[1]): preds[i,",
"returned is average accuracy across 'idxs', followed by individual accuracies ''' preds =",
"ground truth heatmap rather than x,y locations First value to be returned is",
"> 0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy() else: return -1 def accuracy(output, target, idxs,",
"dists[c, n] = -1 return dists def dist_acc(dists, thr=0.5): ''' Return percentage below",
"get_preds(output) gts = get_preds(target) norm = torch.ones(preds.size(0))*output.size(3)/4.0 dists = calc_dists(preds, gts, norm) acc",
"scores.size(3)) + 1 pred_mask = maxval.gt(0).repeat(1, 1, 2).float() preds *= pred_mask return preds",
"if preds.dim() < 3: preds = preds.view(1, preds.size()) return preds def d3_acc(preds, gts,",
"in range(len(idxs)): acc[i+1] = dist_acc(dists[idxs[i]-1], thr=thr) if acc[i+1] >= 0: avg_acc = avg_acc",
"hit + 1 # else: # miss_list.append(i) top_n = int(percent * num_samples) #take",
"= -1 return dists def dist_acc(dists, thr=0.5): ''' Return percentage below threshold while",
"diff = torch.Tensor([hm[py - 1][px] - hm[py - 1][px - 2], hm[py][px -",
"np.array(gts[i]) res = np.abs(pred - gt) res[0:7] = np.abs((res[0:7] + 180.0) % 360.0",
"'AverageMeter'] def get_preds(scores): ''' get predictions from score maps in torch Tensor return",
"= 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum",
"across 'idxs', followed by individual accuracies ''' preds = get_preds(output) gts = get_preds(target)",
"= int(math.floor(coords[n][p][0])) py = int(math.floor(coords[n][p][1])) if px > 1 and px < res[0]",
"- gt) res[0:7] = np.abs((res[0:7] + 180.0) % 360.0 - 180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res)",
"width = bbox[2][i] - bbox[0][i] height = bbox[3][i] - bbox[1][i] for j in",
"math import numpy as np import matplotlib.pyplot as plt from random import randint",
"def final_preds(output, center, scale, res): coords = get_preds(output) # float type # pose-processing",
"1) idx = idx.view(scores.size(0), scores.size(1), 1) + 1 preds = idx.repeat(1, 1, 2).float()",
"to be returned is average accuracy across 'idxs', followed by individual accuracies '''",
"target, idxs, thr=0.5): ''' Calculate accuracy according to PCK, but uses ground truth",
"= val self.sum += val * n self.count += n self.avg = self.sum",
"!= 0: acc[0] = avg_acc / cnt return acc def final_preds_bbox(output, bbox, res):",
"= np.zeros_like(preds[0]) hit = 0 # miss_list = [] max_error_list = [] #max",
"acc = np.zeros_like(preds[0]) hit = 0 # miss_list = [] max_error_list = []",
"gts, norm) acc = torch.zeros(len(idxs)+1) avg_acc = 0 cnt = 0 for i",
"2).float() preds *= pred_mask return preds def calc_dists(preds, target, normalize): preds = preds.float()",
"- 1) % scores.size(3) + 1 preds[:,:,1] = torch.floor((preds[:,:,1] - 1) / scores.size(3))",
"import absolute_import import math import numpy as np import matplotlib.pyplot as plt from",
"1 and target[n, c, 1] > 1: dists[c, n] = torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else:",
"< 3: preds = preds.view(1, preds.size()) return preds def d3_acc(preds, gts, percent =",
"idx.repeat(1, 1, 2).float() preds[:,:,0] = (preds[:,:,0] - 1) % scores.size(3) + 1 preds[:,:,1]",
"target, normalize): preds = preds.float() target = target.float() dists = torch.zeros(preds.size(1), preds.size(0)) for",
"(preds[:,:,0] - 1) % scores.size(3) + 1 preds[:,:,1] = torch.floor((preds[:,:,1] - 1) /",
"1 if cnt != 0: acc[0] = avg_acc / cnt return acc def",
"def dist_acc(dists, thr=0.5): ''' Return percentage below threshold while ignoring values with a",
"res[0] and py > 1 and py < res[1]: diff = torch.Tensor([hm[py -",
"target[n, c, 1] > 1: dists[c, n] = torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else: dists[c, n]",
"sorted_list = np.argsort(max_error_list) for i in range(top_n): acc += res_list[sorted_list[i]] return (acc/top_n)[:4] class",
"max_error_list = [] #max angle error for each image res_list = [] for",
"len(preds) acc = np.zeros_like(preds[0]) hit = 0 # miss_list = [] max_error_list =",
"- 180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res) # if not np.any(res[0:4]>10): #false prediction # acc +=",
"preds.view(1, preds.size()) return preds def d3_acc(preds, gts, percent = .5): num_samples = len(preds)",
"acc[0] = avg_acc / cnt return acc def final_preds_bbox(output, bbox, res): preds =",
"scale, res): coords = get_preds(output) # float type # pose-processing for n in",
"0.5 coords[:, :, 1] -= 0.5 preds = coords.clone() # Transform back for",
"range(num_samples): pred = np.array(preds[i]) gt = np.array(gts[i]) res = np.abs(pred - gt) res[0:7]",
"torch.max(scores.view(scores.size(0), scores.size(1), -1), 2) maxval = maxval.view(scores.size(0), scores.size(1), 1) idx = idx.view(scores.size(0), scores.size(1),",
"= np.abs((res[0:7] + 180.0) % 360.0 - 180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res) # if not",
"prediction # acc += res # hit = hit + 1 # else:",
"res): coords = get_preds(output) # float type # pose-processing for n in range(coords.size(0)):",
"accuracy according to PCK, but uses ground truth heatmap rather than x,y locations",
"2) maxval = maxval.view(scores.size(0), scores.size(1), 1) idx = idx.view(scores.size(0), scores.size(1), 1) + 1",
"dists def dist_acc(dists, thr=0.5): ''' Return percentage below threshold while ignoring values with",
"pred_mask = maxval.gt(0).repeat(1, 1, 2).float() preds *= pred_mask return preds def calc_dists(preds, target,",
"- 2], hm[py][px - 1]-hm[py - 2][px - 1]]) coords[n][p] += diff.sign() *",
"= idx.view(scores.size(0), scores.size(1), 1) + 1 preds = idx.repeat(1, 1, 2).float() preds[:,:,0] =",
"coords = get_preds(output) # float type # pose-processing for n in range(coords.size(0)): for",
"N images with smallesr error. sorted_list = np.argsort(max_error_list) for i in range(top_n): acc",
"= dist_acc(dists[idxs[i]-1], thr=thr) if acc[i+1] >= 0: avg_acc = avg_acc + acc[i+1] cnt",
"reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0",
"scores.size(1), 1) idx = idx.view(scores.size(0), scores.size(1), 1) + 1 preds = idx.repeat(1, 1,",
"in range(coords.size(0)): preds[i] = transform_preds(coords[i], center[i], scale[i], res) if preds.dim() < 3: preds",
"not np.any(res[0:4]>10): #false prediction # acc += res # hit = hit +",
"+ np.array([bbox[0][i], bbox[0][i]]) return torch.from_numpy(preds) def final_preds(output, center, scale, res): coords = get_preds(output)",
"+ 1 # else: # miss_list.append(i) top_n = int(percent * num_samples) #take top",
"hit = hit + 1 # else: # miss_list.append(i) top_n = int(percent *",
"float type # pose-processing for n in range(coords.size(0)): for p in range(coords.size(1)): hm",
"+= res_list[sorted_list[i]] return (acc/top_n)[:4] class AverageMeter(object): \"\"\"Computes and stores the average and current",
"= 0 # miss_list = [] max_error_list = [] #max angle error for",
"1 and py < res[1]: diff = torch.Tensor([hm[py - 1][px] - hm[py -",
"Tensor return type: torch.LongTensor ''' assert scores.dim() == 4, 'Score maps should be",
"from __future__ import absolute_import import math import numpy as np import matplotlib.pyplot as",
"dists.ne(-1).sum() > 0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy() else: return -1 def accuracy(output, target,",
"class AverageMeter(object): \"\"\"Computes and stores the average and current value\"\"\" def __init__(self): self.reset()",
"diff.sign() * .25 coords[:, :, 0] += 0.5 coords[:, :, 1] -= 0.5",
"average and current value\"\"\" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg",
"- 1][px] - hm[py - 1][px - 2], hm[py][px - 1]-hm[py - 2][px",
"type # pose-processing for n in range(coords.size(0)): for p in range(coords.size(1)): hm =",
"['accuracy', 'AverageMeter'] def get_preds(scores): ''' get predictions from score maps in torch Tensor",
"Return percentage below threshold while ignoring values with a -1 ''' if dists.ne(-1).sum()",
"1) % scores.size(3) + 1 preds[:,:,1] = torch.floor((preds[:,:,1] - 1) / scores.size(3)) +",
"+ 1 pred_mask = maxval.gt(0).repeat(1, 1, 2).float() preds *= pred_mask return preds def",
"preds def calc_dists(preds, target, normalize): preds = preds.float() target = target.float() dists =",
".transforms import transform, transform_preds __all__ = ['accuracy', 'AverageMeter'] def get_preds(scores): ''' get predictions",
"# miss_list = [] max_error_list = [] #max angle error for each image",
"res_list.append(res) # if not np.any(res[0:4]>10): #false prediction # acc += res # hit",
"2).float() preds[:,:,0] = (preds[:,:,0] - 1) % scores.size(3) + 1 preds[:,:,1] = torch.floor((preds[:,:,1]",
"= torch.max(scores.view(scores.size(0), scores.size(1), -1), 2) maxval = maxval.view(scores.size(0), scores.size(1), 1) idx = idx.view(scores.size(0),",
"preds[:,:,0] = (preds[:,:,0] - 1) % scores.size(3) + 1 preds[:,:,1] = torch.floor((preds[:,:,1] -",
"preds = get_preds(output) gts = get_preds(target) norm = torch.ones(preds.size(0))*output.size(3)/4.0 dists = calc_dists(preds, gts,",
"for each image res_list = [] for i in range(num_samples): pred = np.array(preds[i])",
"= preds.numpy() for i in range(preds.shape[0]): width = bbox[2][i] - bbox[0][i] height =",
"acc[i+1] cnt += 1 if cnt != 0: acc[0] = avg_acc / cnt",
"avg_acc = avg_acc + acc[i+1] cnt += 1 if cnt != 0: acc[0]",
"= get_preds(output) # float type # pose-processing for n in range(coords.size(0)): for p",
"import randint import torch from .misc import * from .transforms import transform, transform_preds",
"np.any(res[0:4]>10): #false prediction # acc += res # hit = hit + 1",
"= np.array(gts[i]) res = np.abs(pred - gt) res[0:7] = np.abs((res[0:7] + 180.0) %",
"# miss_list.append(i) top_n = int(percent * num_samples) #take top N images with smallesr",
"- hm[py - 1][px - 2], hm[py][px - 1]-hm[py - 2][px - 1]])",
"3: preds = preds.view(1, preds.size()) return preds def d3_acc(preds, gts, percent = .5):",
"target.float() dists = torch.zeros(preds.size(1), preds.size(0)) for n in range(preds.size(0)): for c in range(preds.size(1)):",
"pred = np.array(preds[i]) gt = np.array(gts[i]) res = np.abs(pred - gt) res[0:7] =",
"1, 2).float() preds *= pred_mask return preds def calc_dists(preds, target, normalize): preds =",
"preds[i, j, :] = preds[i, j, :] / res * np.array([width, height]) +",
"acc += res # hit = hit + 1 # else: # miss_list.append(i)",
"gt) res[0:7] = np.abs((res[0:7] + 180.0) % 360.0 - 180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res) #",
"= calc_dists(preds, gts, norm) acc = torch.zeros(len(idxs)+1) avg_acc = 0 cnt = 0",
"for n in range(preds.size(0)): for c in range(preds.size(1)): if target[n,c,0] > 1 and",
"= preds.view(1, preds.size()) return preds def d3_acc(preds, gts, percent = .5): num_samples =",
"preds.numpy() for i in range(preds.shape[0]): width = bbox[2][i] - bbox[0][i] height = bbox[3][i]",
"+ 180.0) % 360.0 - 180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res) # if not np.any(res[0:4]>10): #false",
"norm = torch.ones(preds.size(0))*output.size(3)/4.0 dists = calc_dists(preds, gts, norm) acc = torch.zeros(len(idxs)+1) avg_acc =",
"cnt != 0: acc[0] = avg_acc / cnt return acc def final_preds_bbox(output, bbox,",
"0 # miss_list = [] max_error_list = [] #max angle error for each",
"transform_preds(coords[i], center[i], scale[i], res) if preds.dim() < 3: preds = preds.view(1, preds.size()) return",
"* from .transforms import transform, transform_preds __all__ = ['accuracy', 'AverageMeter'] def get_preds(scores): '''",
"= 0 for i in range(len(idxs)): acc[i+1] = dist_acc(dists[idxs[i]-1], thr=thr) if acc[i+1] >=",
"res = np.abs(pred - gt) res[0:7] = np.abs((res[0:7] + 180.0) % 360.0 -",
"1]]) coords[n][p] += diff.sign() * .25 coords[:, :, 0] += 0.5 coords[:, :,",
"should be 4-dim' maxval, idx = torch.max(scores.view(scores.size(0), scores.size(1), -1), 2) maxval = maxval.view(scores.size(0),",
"individual accuracies ''' preds = get_preds(output) gts = get_preds(target) norm = torch.ones(preds.size(0))*output.size(3)/4.0 dists",
"avg_acc / cnt return acc def final_preds_bbox(output, bbox, res): preds = get_preds(output) #",
"random import randint import torch from .misc import * from .transforms import transform,",
"np.abs((res[0:7] + 180.0) % 360.0 - 180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res) # if not np.any(res[0:4]>10):",
"d3_acc(preds, gts, percent = .5): num_samples = len(preds) acc = np.zeros_like(preds[0]) hit =",
"px < res[0] and py > 1 and py < res[1]: diff =",
":, 0] += 0.5 coords[:, :, 1] -= 0.5 preds = coords.clone() #",
"matplotlib.pyplot as plt from random import randint import torch from .misc import *",
"i in range(top_n): acc += res_list[sorted_list[i]] return (acc/top_n)[:4] class AverageMeter(object): \"\"\"Computes and stores",
"randint import torch from .misc import * from .transforms import transform, transform_preds __all__",
"center, scale, res): coords = get_preds(output) # float type # pose-processing for n",
"1 pred_mask = maxval.gt(0).repeat(1, 1, 2).float() preds *= pred_mask return preds def calc_dists(preds,",
"torch.floor((preds[:,:,1] - 1) / scores.size(3)) + 1 pred_mask = maxval.gt(0).repeat(1, 1, 2).float() preds",
"preds = coords.clone() # Transform back for i in range(coords.size(0)): preds[i] = transform_preds(coords[i],",
"preds = get_preds(output) # float typ preds = preds.numpy() for i in range(preds.shape[0]):",
"assert scores.dim() == 4, 'Score maps should be 4-dim' maxval, idx = torch.max(scores.view(scores.size(0),",
"in range(preds.size(1)): if target[n,c,0] > 1 and target[n, c, 1] > 1: dists[c,",
"hm = output[n][p] px = int(math.floor(coords[n][p][0])) py = int(math.floor(coords[n][p][1])) if px > 1",
"val, n=1): self.val = val self.sum += val * n self.count += n",
"return preds def calc_dists(preds, target, normalize): preds = preds.float() target = target.float() dists",
"np.zeros_like(preds[0]) hit = 0 # miss_list = [] max_error_list = [] #max angle",
"to PCK, but uses ground truth heatmap rather than x,y locations First value",
"ignoring values with a -1 ''' if dists.ne(-1).sum() > 0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy() /",
"= np.argsort(max_error_list) for i in range(top_n): acc += res_list[sorted_list[i]] return (acc/top_n)[:4] class AverageMeter(object):",
"for i in range(top_n): acc += res_list[sorted_list[i]] return (acc/top_n)[:4] class AverageMeter(object): \"\"\"Computes and",
"current value\"\"\" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0",
"dists[c, n] = torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else: dists[c, n] = -1 return dists def",
"360.0 - 180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res) # if not np.any(res[0:4]>10): #false prediction # acc",
"> 1: dists[c, n] = torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else: dists[c, n] = -1 return",
">= 0: avg_acc = avg_acc + acc[i+1] cnt += 1 if cnt !=",
"return torch.from_numpy(preds) def final_preds(output, center, scale, res): coords = get_preds(output) # float type",
"self.count = 0 def update(self, val, n=1): self.val = val self.sum += val",
"= transform_preds(coords[i], center[i], scale[i], res) if preds.dim() < 3: preds = preds.view(1, preds.size())",
"int(math.floor(coords[n][p][0])) py = int(math.floor(coords[n][p][1])) if px > 1 and px < res[0] and",
"[] for i in range(num_samples): pred = np.array(preds[i]) gt = np.array(gts[i]) res =",
"with smallesr error. sorted_list = np.argsort(max_error_list) for i in range(top_n): acc += res_list[sorted_list[i]]",
"get_preds(target) norm = torch.ones(preds.size(0))*output.size(3)/4.0 dists = calc_dists(preds, gts, norm) acc = torch.zeros(len(idxs)+1) avg_acc",
"according to PCK, but uses ground truth heatmap rather than x,y locations First",
"import numpy as np import matplotlib.pyplot as plt from random import randint import",
"idx = torch.max(scores.view(scores.size(0), scores.size(1), -1), 2) maxval = maxval.view(scores.size(0), scores.size(1), 1) idx =",
"thr=0.5): ''' Return percentage below threshold while ignoring values with a -1 '''",
"in range(preds.shape[1]): preds[i, j, :] = preds[i, j, :] / res * np.array([width,",
"< res[0] and py > 1 and py < res[1]: diff = torch.Tensor([hm[py",
"followed by individual accuracies ''' preds = get_preds(output) gts = get_preds(target) norm =",
"= avg_acc + acc[i+1] cnt += 1 if cnt != 0: acc[0] =",
"preds[i] = transform_preds(coords[i], center[i], scale[i], res) if preds.dim() < 3: preds = preds.view(1,",
"torch.zeros(preds.size(1), preds.size(0)) for n in range(preds.size(0)): for c in range(preds.size(1)): if target[n,c,0] >",
"/ res * np.array([width, height]) + np.array([bbox[0][i], bbox[0][i]]) return torch.from_numpy(preds) def final_preds(output, center,",
"image res_list = [] for i in range(num_samples): pred = np.array(preds[i]) gt =",
"preds *= pred_mask return preds def calc_dists(preds, target, normalize): preds = preds.float() target",
"-= 0.5 preds = coords.clone() # Transform back for i in range(coords.size(0)): preds[i]",
"and py > 1 and py < res[1]: diff = torch.Tensor([hm[py - 1][px]",
"# Transform back for i in range(coords.size(0)): preds[i] = transform_preds(coords[i], center[i], scale[i], res)",
"rather than x,y locations First value to be returned is average accuracy across",
"else: # miss_list.append(i) top_n = int(percent * num_samples) #take top N images with",
"range(coords.size(0)): preds[i] = transform_preds(coords[i], center[i], scale[i], res) if preds.dim() < 3: preds =",
"percentage below threshold while ignoring values with a -1 ''' if dists.ne(-1).sum() >",
"with a -1 ''' if dists.ne(-1).sum() > 0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy() else:",
"thr=0.5): ''' Calculate accuracy according to PCK, but uses ground truth heatmap rather",
"res) if preds.dim() < 3: preds = preds.view(1, preds.size()) return preds def d3_acc(preds,",
"-1 return dists def dist_acc(dists, thr=0.5): ''' Return percentage below threshold while ignoring",
"acc def final_preds_bbox(output, bbox, res): preds = get_preds(output) # float typ preds =",
"top N images with smallesr error. sorted_list = np.argsort(max_error_list) for i in range(top_n):",
"target = target.float() dists = torch.zeros(preds.size(1), preds.size(0)) for n in range(preds.size(0)): for c",
"= [] max_error_list = [] #max angle error for each image res_list =",
"hm[py][px - 1]-hm[py - 2][px - 1]]) coords[n][p] += diff.sign() * .25 coords[:,",
"stores the average and current value\"\"\" def __init__(self): self.reset() def reset(self): self.val =",
"*= pred_mask return preds def calc_dists(preds, target, normalize): preds = preds.float() target =",
"scores.size(1), 1) + 1 preds = idx.repeat(1, 1, 2).float() preds[:,:,0] = (preds[:,:,0] -",
"acc += res_list[sorted_list[i]] return (acc/top_n)[:4] class AverageMeter(object): \"\"\"Computes and stores the average and",
"torch.ones(preds.size(0))*output.size(3)/4.0 dists = calc_dists(preds, gts, norm) acc = torch.zeros(len(idxs)+1) avg_acc = 0 cnt",
"= 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val",
"num_samples = len(preds) acc = np.zeros_like(preds[0]) hit = 0 # miss_list = []",
"i in range(preds.shape[0]): width = bbox[2][i] - bbox[0][i] height = bbox[3][i] - bbox[1][i]",
"= [] for i in range(num_samples): pred = np.array(preds[i]) gt = np.array(gts[i]) res",
"#false prediction # acc += res # hit = hit + 1 #",
"preds.size()) return preds def d3_acc(preds, gts, percent = .5): num_samples = len(preds) acc",
"range(preds.size(0)): for c in range(preds.size(1)): if target[n,c,0] > 1 and target[n, c, 1]",
"error for each image res_list = [] for i in range(num_samples): pred =",
"= hit + 1 # else: # miss_list.append(i) top_n = int(percent * num_samples)",
"4-dim' maxval, idx = torch.max(scores.view(scores.size(0), scores.size(1), -1), 2) maxval = maxval.view(scores.size(0), scores.size(1), 1)",
"+ acc[i+1] cnt += 1 if cnt != 0: acc[0] = avg_acc /",
"for c in range(preds.size(1)): if target[n,c,0] > 1 and target[n, c, 1] >",
"''' if dists.ne(-1).sum() > 0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy() else: return -1 def",
"1, 2).float() preds[:,:,0] = (preds[:,:,0] - 1) % scores.size(3) + 1 preds[:,:,1] =",
"4, 'Score maps should be 4-dim' maxval, idx = torch.max(scores.view(scores.size(0), scores.size(1), -1), 2)",
"truth heatmap rather than x,y locations First value to be returned is average",
"val self.sum += val * n self.count += n self.avg = self.sum /",
"px > 1 and px < res[0] and py > 1 and py",
"the average and current value\"\"\" def __init__(self): self.reset() def reset(self): self.val = 0",
"+= diff.sign() * .25 coords[:, :, 0] += 0.5 coords[:, :, 1] -=",
"and current value\"\"\" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg =",
"/ cnt return acc def final_preds_bbox(output, bbox, res): preds = get_preds(output) # float",
"res_list[sorted_list[i]] return (acc/top_n)[:4] class AverageMeter(object): \"\"\"Computes and stores the average and current value\"\"\"",
"py < res[1]: diff = torch.Tensor([hm[py - 1][px] - hm[py - 1][px -",
"in range(preds.shape[0]): width = bbox[2][i] - bbox[0][i] height = bbox[3][i] - bbox[1][i] for",
"torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else: dists[c, n] = -1 return dists def dist_acc(dists, thr=0.5): '''",
"pose-processing for n in range(coords.size(0)): for p in range(coords.size(1)): hm = output[n][p] px",
"for p in range(coords.size(1)): hm = output[n][p] px = int(math.floor(coords[n][p][0])) py = int(math.floor(coords[n][p][1]))",
"def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum =",
"preds = preds.float() target = target.float() dists = torch.zeros(preds.size(1), preds.size(0)) for n in",
"float typ preds = preds.numpy() for i in range(preds.shape[0]): width = bbox[2][i] -",
"1) / scores.size(3)) + 1 pred_mask = maxval.gt(0).repeat(1, 1, 2).float() preds *= pred_mask",
"x,y locations First value to be returned is average accuracy across 'idxs', followed",
"0: acc[0] = avg_acc / cnt return acc def final_preds_bbox(output, bbox, res): preds",
"= get_preds(output) gts = get_preds(target) norm = torch.ones(preds.size(0))*output.size(3)/4.0 dists = calc_dists(preds, gts, norm)",
"1 and px < res[0] and py > 1 and py < res[1]:",
"0.5 preds = coords.clone() # Transform back for i in range(coords.size(0)): preds[i] =",
"[] max_error_list = [] #max angle error for each image res_list = []",
"preds = preds.numpy() for i in range(preds.shape[0]): width = bbox[2][i] - bbox[0][i] height",
"__future__ import absolute_import import math import numpy as np import matplotlib.pyplot as plt",
"than x,y locations First value to be returned is average accuracy across 'idxs',",
"heatmap rather than x,y locations First value to be returned is average accuracy",
"update(self, val, n=1): self.val = val self.sum += val * n self.count +=",
"absolute_import import math import numpy as np import matplotlib.pyplot as plt from random",
"final_preds_bbox(output, bbox, res): preds = get_preds(output) # float typ preds = preds.numpy() for",
"value\"\"\" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum",
"back for i in range(coords.size(0)): preds[i] = transform_preds(coords[i], center[i], scale[i], res) if preds.dim()",
"res[1]: diff = torch.Tensor([hm[py - 1][px] - hm[py - 1][px - 2], hm[py][px",
"gts, percent = .5): num_samples = len(preds) acc = np.zeros_like(preds[0]) hit = 0",
"/ scores.size(3)) + 1 pred_mask = maxval.gt(0).repeat(1, 1, 2).float() preds *= pred_mask return",
"for n in range(coords.size(0)): for p in range(coords.size(1)): hm = output[n][p] px =",
"error. sorted_list = np.argsort(max_error_list) for i in range(top_n): acc += res_list[sorted_list[i]] return (acc/top_n)[:4]",
"n in range(preds.size(0)): for c in range(preds.size(1)): if target[n,c,0] > 1 and target[n,",
"torch.LongTensor ''' assert scores.dim() == 4, 'Score maps should be 4-dim' maxval, idx",
"= maxval.gt(0).repeat(1, 1, 2).float() preds *= pred_mask return preds def calc_dists(preds, target, normalize):",
"c in range(preds.size(1)): if target[n,c,0] > 1 and target[n, c, 1] > 1:",
"miss_list.append(i) top_n = int(percent * num_samples) #take top N images with smallesr error.",
"pred_mask return preds def calc_dists(preds, target, normalize): preds = preds.float() target = target.float()",
"preds.dim() < 3: preds = preds.view(1, preds.size()) return preds def d3_acc(preds, gts, percent",
"= (preds[:,:,0] - 1) % scores.size(3) + 1 preds[:,:,1] = torch.floor((preds[:,:,1] - 1)",
"def calc_dists(preds, target, normalize): preds = preds.float() target = target.float() dists = torch.zeros(preds.size(1),",
"cnt += 1 if cnt != 0: acc[0] = avg_acc / cnt return",
"res_list = [] for i in range(num_samples): pred = np.array(preds[i]) gt = np.array(gts[i])",
"get_preds(output) # float typ preds = preds.numpy() for i in range(preds.shape[0]): width =",
"= 0 def update(self, val, n=1): self.val = val self.sum += val *",
"calc_dists(preds, gts, norm) acc = torch.zeros(len(idxs)+1) avg_acc = 0 cnt = 0 for",
"if dists.ne(-1).sum() > 0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy() else: return -1 def accuracy(output,",
"images with smallesr error. sorted_list = np.argsort(max_error_list) for i in range(top_n): acc +=",
"+= res # hit = hit + 1 # else: # miss_list.append(i) top_n",
"c, 1] > 1: dists[c, n] = torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else: dists[c, n] =",
"top_n = int(percent * num_samples) #take top N images with smallesr error. sorted_list",
"if acc[i+1] >= 0: avg_acc = avg_acc + acc[i+1] cnt += 1 if",
"= .5): num_samples = len(preds) acc = np.zeros_like(preds[0]) hit = 0 # miss_list",
"= get_preds(output) # float typ preds = preds.numpy() for i in range(preds.shape[0]): width",
"np import matplotlib.pyplot as plt from random import randint import torch from .misc",
"accuracy(output, target, idxs, thr=0.5): ''' Calculate accuracy according to PCK, but uses ground",
"n in range(coords.size(0)): for p in range(coords.size(1)): hm = output[n][p] px = int(math.floor(coords[n][p][0]))",
"1 # else: # miss_list.append(i) top_n = int(percent * num_samples) #take top N",
"''' Return percentage below threshold while ignoring values with a -1 ''' if",
"np.array(preds[i]) gt = np.array(gts[i]) res = np.abs(pred - gt) res[0:7] = np.abs((res[0:7] +",
"0 for i in range(len(idxs)): acc[i+1] = dist_acc(dists[idxs[i]-1], thr=thr) if acc[i+1] >= 0:",
"get_preds(scores): ''' get predictions from score maps in torch Tensor return type: torch.LongTensor",
"in range(top_n): acc += res_list[sorted_list[i]] return (acc/top_n)[:4] class AverageMeter(object): \"\"\"Computes and stores the",
"if cnt != 0: acc[0] = avg_acc / cnt return acc def final_preds_bbox(output,",
"avg_acc = 0 cnt = 0 for i in range(len(idxs)): acc[i+1] = dist_acc(dists[idxs[i]-1],",
".25 coords[:, :, 0] += 0.5 coords[:, :, 1] -= 0.5 preds =",
"j, :] / res * np.array([width, height]) + np.array([bbox[0][i], bbox[0][i]]) return torch.from_numpy(preds) def",
"+= 0.5 coords[:, :, 1] -= 0.5 preds = coords.clone() # Transform back",
"'Score maps should be 4-dim' maxval, idx = torch.max(scores.view(scores.size(0), scores.size(1), -1), 2) maxval",
"# acc += res # hit = hit + 1 # else: #",
"= maxval.view(scores.size(0), scores.size(1), 1) idx = idx.view(scores.size(0), scores.size(1), 1) + 1 preds =",
"1) + 1 preds = idx.repeat(1, 1, 2).float() preds[:,:,0] = (preds[:,:,0] - 1)",
"= torch.ones(preds.size(0))*output.size(3)/4.0 dists = calc_dists(preds, gts, norm) acc = torch.zeros(len(idxs)+1) avg_acc = 0",
"- 1][px - 2], hm[py][px - 1]-hm[py - 2][px - 1]]) coords[n][p] +=",
"- bbox[0][i] height = bbox[3][i] - bbox[1][i] for j in range(preds.shape[1]): preds[i, j,",
"be returned is average accuracy across 'idxs', followed by individual accuracies ''' preds",
"> 1 and target[n, c, 1] > 1: dists[c, n] = torch.dist(preds[n,c,:], target[n,c,:])/normalize[n]",
"self.sum += val * n self.count += n self.avg = self.sum / self.count",
"> 1 and py < res[1]: diff = torch.Tensor([hm[py - 1][px] - hm[py",
"coords[:, :, 0] += 0.5 coords[:, :, 1] -= 0.5 preds = coords.clone()",
"maxval, idx = torch.max(scores.view(scores.size(0), scores.size(1), -1), 2) maxval = maxval.view(scores.size(0), scores.size(1), 1) idx",
"int(percent * num_samples) #take top N images with smallesr error. sorted_list = np.argsort(max_error_list)",
"= 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self,",
".5): num_samples = len(preds) acc = np.zeros_like(preds[0]) hit = 0 # miss_list =",
"uses ground truth heatmap rather than x,y locations First value to be returned",
"thr=thr) if acc[i+1] >= 0: avg_acc = avg_acc + acc[i+1] cnt += 1",
"= bbox[3][i] - bbox[1][i] for j in range(preds.shape[1]): preds[i, j, :] = preds[i,",
"j, :] = preds[i, j, :] / res * np.array([width, height]) + np.array([bbox[0][i],",
"#take top N images with smallesr error. sorted_list = np.argsort(max_error_list) for i in",
"2][px - 1]]) coords[n][p] += diff.sign() * .25 coords[:, :, 0] += 0.5",
"import transform, transform_preds __all__ = ['accuracy', 'AverageMeter'] def get_preds(scores): ''' get predictions from",
"# if not np.any(res[0:4]>10): #false prediction # acc += res # hit =",
"from score maps in torch Tensor return type: torch.LongTensor ''' assert scores.dim() ==",
"self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def",
"miss_list = [] max_error_list = [] #max angle error for each image res_list",
"typ preds = preds.numpy() for i in range(preds.shape[0]): width = bbox[2][i] - bbox[0][i]",
"preds.size(0)) for n in range(preds.size(0)): for c in range(preds.size(1)): if target[n,c,0] > 1",
"1 preds = idx.repeat(1, 1, 2).float() preds[:,:,0] = (preds[:,:,0] - 1) % scores.size(3)",
"cnt = 0 for i in range(len(idxs)): acc[i+1] = dist_acc(dists[idxs[i]-1], thr=thr) if acc[i+1]",
"> 1 and px < res[0] and py > 1 and py <",
"and stores the average and current value\"\"\" def __init__(self): self.reset() def reset(self): self.val",
"if target[n,c,0] > 1 and target[n, c, 1] > 1: dists[c, n] =",
"= get_preds(target) norm = torch.ones(preds.size(0))*output.size(3)/4.0 dists = calc_dists(preds, gts, norm) acc = torch.zeros(len(idxs)+1)",
"= target.float() dists = torch.zeros(preds.size(1), preds.size(0)) for n in range(preds.size(0)): for c in",
"avg_acc + acc[i+1] cnt += 1 if cnt != 0: acc[0] = avg_acc",
"be 4-dim' maxval, idx = torch.max(scores.view(scores.size(0), scores.size(1), -1), 2) maxval = maxval.view(scores.size(0), scores.size(1),",
"res * np.array([width, height]) + np.array([bbox[0][i], bbox[0][i]]) return torch.from_numpy(preds) def final_preds(output, center, scale,",
"bbox[1][i] for j in range(preds.shape[1]): preds[i, j, :] = preds[i, j, :] /",
"return dists def dist_acc(dists, thr=0.5): ''' Return percentage below threshold while ignoring values",
"def accuracy(output, target, idxs, thr=0.5): ''' Calculate accuracy according to PCK, but uses",
"0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val =",
"n] = -1 return dists def dist_acc(dists, thr=0.5): ''' Return percentage below threshold",
"= int(math.floor(coords[n][p][1])) if px > 1 and px < res[0] and py >",
"gts = get_preds(target) norm = torch.ones(preds.size(0))*output.size(3)/4.0 dists = calc_dists(preds, gts, norm) acc =",
"= output[n][p] px = int(math.floor(coords[n][p][0])) py = int(math.floor(coords[n][p][1])) if px > 1 and",
"''' get predictions from score maps in torch Tensor return type: torch.LongTensor '''",
"gt = np.array(gts[i]) res = np.abs(pred - gt) res[0:7] = np.abs((res[0:7] + 180.0)",
"while ignoring values with a -1 ''' if dists.ne(-1).sum() > 0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy()",
"- bbox[1][i] for j in range(preds.shape[1]): preds[i, j, :] = preds[i, j, :]",
"px = int(math.floor(coords[n][p][0])) py = int(math.floor(coords[n][p][1])) if px > 1 and px <",
"< res[1]: diff = torch.Tensor([hm[py - 1][px] - hm[py - 1][px - 2],",
"i in range(coords.size(0)): preds[i] = transform_preds(coords[i], center[i], scale[i], res) if preds.dim() < 3:",
"if not np.any(res[0:4]>10): #false prediction # acc += res # hit = hit",
"acc[i+1] = dist_acc(dists[idxs[i]-1], thr=thr) if acc[i+1] >= 0: avg_acc = avg_acc + acc[i+1]",
"range(preds.size(1)): if target[n,c,0] > 1 and target[n, c, 1] > 1: dists[c, n]",
"- 1]-hm[py - 2][px - 1]]) coords[n][p] += diff.sign() * .25 coords[:, :,",
"for i in range(preds.shape[0]): width = bbox[2][i] - bbox[0][i] height = bbox[3][i] -",
"def update(self, val, n=1): self.val = val self.sum += val * n self.count",
"n=1): self.val = val self.sum += val * n self.count += n self.avg",
"maps in torch Tensor return type: torch.LongTensor ''' assert scores.dim() == 4, 'Score",
"Calculate accuracy according to PCK, but uses ground truth heatmap rather than x,y",
"0] += 0.5 coords[:, :, 1] -= 0.5 preds = coords.clone() # Transform",
"cnt return acc def final_preds_bbox(output, bbox, res): preds = get_preds(output) # float typ",
"self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val",
"in range(coords.size(1)): hm = output[n][p] px = int(math.floor(coords[n][p][0])) py = int(math.floor(coords[n][p][1])) if px",
"self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count",
"* .25 coords[:, :, 0] += 0.5 coords[:, :, 1] -= 0.5 preds",
":] / res * np.array([width, height]) + np.array([bbox[0][i], bbox[0][i]]) return torch.from_numpy(preds) def final_preds(output,",
":, 1] -= 0.5 preds = coords.clone() # Transform back for i in",
"return preds def d3_acc(preds, gts, percent = .5): num_samples = len(preds) acc =",
"in range(coords.size(0)): for p in range(coords.size(1)): hm = output[n][p] px = int(math.floor(coords[n][p][0])) py",
"0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val,",
"accuracy across 'idxs', followed by individual accuracies ''' preds = get_preds(output) gts =",
"plt from random import randint import torch from .misc import * from .transforms",
"in range(preds.size(0)): for c in range(preds.size(1)): if target[n,c,0] > 1 and target[n, c,",
"First value to be returned is average accuracy across 'idxs', followed by individual",
"dists.ne(-1).sum().numpy() else: return -1 def accuracy(output, target, idxs, thr=0.5): ''' Calculate accuracy according",
"#max angle error for each image res_list = [] for i in range(num_samples):",
"def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count =",
"1] > 1: dists[c, n] = torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else: dists[c, n] = -1",
"numpy as np import matplotlib.pyplot as plt from random import randint import torch",
"0 def update(self, val, n=1): self.val = val self.sum += val * n",
"idx = idx.view(scores.size(0), scores.size(1), 1) + 1 preds = idx.repeat(1, 1, 2).float() preds[:,:,0]",
"coords[:, :, 1] -= 0.5 preds = coords.clone() # Transform back for i",
"dist_acc(dists[idxs[i]-1], thr=thr) if acc[i+1] >= 0: avg_acc = avg_acc + acc[i+1] cnt +=",
"== 4, 'Score maps should be 4-dim' maxval, idx = torch.max(scores.view(scores.size(0), scores.size(1), -1),",
"% 360.0 - 180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res) # if not np.any(res[0:4]>10): #false prediction #",
"n] = torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else: dists[c, n] = -1 return dists def dist_acc(dists,",
"1][px - 2], hm[py][px - 1]-hm[py - 2][px - 1]]) coords[n][p] += diff.sign()",
"score maps in torch Tensor return type: torch.LongTensor ''' assert scores.dim() == 4,",
"return dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy() else: return -1 def accuracy(output, target, idxs, thr=0.5): '''",
"= coords.clone() # Transform back for i in range(coords.size(0)): preds[i] = transform_preds(coords[i], center[i],",
"dist_acc(dists, thr=0.5): ''' Return percentage below threshold while ignoring values with a -1",
"Transform back for i in range(coords.size(0)): preds[i] = transform_preds(coords[i], center[i], scale[i], res) if",
"range(coords.size(1)): hm = output[n][p] px = int(math.floor(coords[n][p][0])) py = int(math.floor(coords[n][p][1])) if px >",
"angle error for each image res_list = [] for i in range(num_samples): pred",
"values with a -1 ''' if dists.ne(-1).sum() > 0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy()",
"j in range(preds.shape[1]): preds[i, j, :] = preds[i, j, :] / res *",
"maps should be 4-dim' maxval, idx = torch.max(scores.view(scores.size(0), scores.size(1), -1), 2) maxval =",
"percent = .5): num_samples = len(preds) acc = np.zeros_like(preds[0]) hit = 0 #",
"180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res) # if not np.any(res[0:4]>10): #false prediction # acc += res",
"coords[n][p] += diff.sign() * .25 coords[:, :, 0] += 0.5 coords[:, :, 1]",
"- 1) / scores.size(3)) + 1 pred_mask = maxval.gt(0).repeat(1, 1, 2).float() preds *=",
"= np.abs(pred - gt) res[0:7] = np.abs((res[0:7] + 180.0) % 360.0 - 180.0)",
"norm) acc = torch.zeros(len(idxs)+1) avg_acc = 0 cnt = 0 for i in",
"= torch.Tensor([hm[py - 1][px] - hm[py - 1][px - 2], hm[py][px - 1]-hm[py",
"= len(preds) acc = np.zeros_like(preds[0]) hit = 0 # miss_list = [] max_error_list",
"bbox[0][i]]) return torch.from_numpy(preds) def final_preds(output, center, scale, res): coords = get_preds(output) # float",
"AverageMeter(object): \"\"\"Computes and stores the average and current value\"\"\" def __init__(self): self.reset() def",
"scores.size(1), -1), 2) maxval = maxval.view(scores.size(0), scores.size(1), 1) idx = idx.view(scores.size(0), scores.size(1), 1)",
"np.abs(pred - gt) res[0:7] = np.abs((res[0:7] + 180.0) % 360.0 - 180.0) max_error_list.append(np.max(res[0:4]))",
"return -1 def accuracy(output, target, idxs, thr=0.5): ''' Calculate accuracy according to PCK,",
"and target[n, c, 1] > 1: dists[c, n] = torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else: dists[c,",
"def final_preds_bbox(output, bbox, res): preds = get_preds(output) # float typ preds = preds.numpy()",
"preds = idx.repeat(1, 1, 2).float() preds[:,:,0] = (preds[:,:,0] - 1) % scores.size(3) +",
"preds.float() target = target.float() dists = torch.zeros(preds.size(1), preds.size(0)) for n in range(preds.size(0)): for",
"range(coords.size(0)): for p in range(coords.size(1)): hm = output[n][p] px = int(math.floor(coords[n][p][0])) py =",
"res[0:7] = np.abs((res[0:7] + 180.0) % 360.0 - 180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res) # if",
"180.0) % 360.0 - 180.0) max_error_list.append(np.max(res[0:4])) res_list.append(res) # if not np.any(res[0:4]>10): #false prediction",
"= int(percent * num_samples) #take top N images with smallesr error. sorted_list =",
"__init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0",
"acc[i+1] >= 0: avg_acc = avg_acc + acc[i+1] cnt += 1 if cnt",
"type: torch.LongTensor ''' assert scores.dim() == 4, 'Score maps should be 4-dim' maxval,",
"bbox, res): preds = get_preds(output) # float typ preds = preds.numpy() for i",
"i in range(len(idxs)): acc[i+1] = dist_acc(dists[idxs[i]-1], thr=thr) if acc[i+1] >= 0: avg_acc =",
"idxs, thr=0.5): ''' Calculate accuracy according to PCK, but uses ground truth heatmap",
"0 cnt = 0 for i in range(len(idxs)): acc[i+1] = dist_acc(dists[idxs[i]-1], thr=thr) if",
"+= 1 if cnt != 0: acc[0] = avg_acc / cnt return acc",
"np.array([width, height]) + np.array([bbox[0][i], bbox[0][i]]) return torch.from_numpy(preds) def final_preds(output, center, scale, res): coords",
"''' preds = get_preds(output) gts = get_preds(target) norm = torch.ones(preds.size(0))*output.size(3)/4.0 dists = calc_dists(preds,",
"height]) + np.array([bbox[0][i], bbox[0][i]]) return torch.from_numpy(preds) def final_preds(output, center, scale, res): coords =",
"# else: # miss_list.append(i) top_n = int(percent * num_samples) #take top N images",
"maxval = maxval.view(scores.size(0), scores.size(1), 1) idx = idx.view(scores.size(0), scores.size(1), 1) + 1 preds",
"scale[i], res) if preds.dim() < 3: preds = preds.view(1, preds.size()) return preds def",
"coords.clone() # Transform back for i in range(coords.size(0)): preds[i] = transform_preds(coords[i], center[i], scale[i],",
"np.argsort(max_error_list) for i in range(top_n): acc += res_list[sorted_list[i]] return (acc/top_n)[:4] class AverageMeter(object): \"\"\"Computes",
"transform_preds __all__ = ['accuracy', 'AverageMeter'] def get_preds(scores): ''' get predictions from score maps",
"py > 1 and py < res[1]: diff = torch.Tensor([hm[py - 1][px] -",
"torch.from_numpy(preds) def final_preds(output, center, scale, res): coords = get_preds(output) # float type #",
"if px > 1 and px < res[0] and py > 1 and",
"as np import matplotlib.pyplot as plt from random import randint import torch from",
"import matplotlib.pyplot as plt from random import randint import torch from .misc import",
"# hit = hit + 1 # else: # miss_list.append(i) top_n = int(percent",
"in torch Tensor return type: torch.LongTensor ''' assert scores.dim() == 4, 'Score maps",
"= preds.float() target = target.float() dists = torch.zeros(preds.size(1), preds.size(0)) for n in range(preds.size(0)):",
"scores.size(3) + 1 preds[:,:,1] = torch.floor((preds[:,:,1] - 1) / scores.size(3)) + 1 pred_mask",
"maxval.view(scores.size(0), scores.size(1), 1) idx = idx.view(scores.size(0), scores.size(1), 1) + 1 preds = idx.repeat(1,",
"range(preds.shape[1]): preds[i, j, :] = preds[i, j, :] / res * np.array([width, height])",
"return type: torch.LongTensor ''' assert scores.dim() == 4, 'Score maps should be 4-dim'",
"for i in range(coords.size(0)): preds[i] = transform_preds(coords[i], center[i], scale[i], res) if preds.dim() <",
"else: dists[c, n] = -1 return dists def dist_acc(dists, thr=0.5): ''' Return percentage",
"bbox[0][i] height = bbox[3][i] - bbox[1][i] for j in range(preds.shape[1]): preds[i, j, :]",
"self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1):",
"for j in range(preds.shape[1]): preds[i, j, :] = preds[i, j, :] / res",
"smallesr error. sorted_list = np.argsort(max_error_list) for i in range(top_n): acc += res_list[sorted_list[i]] return",
"value to be returned is average accuracy across 'idxs', followed by individual accuracies",
"accuracies ''' preds = get_preds(output) gts = get_preds(target) norm = torch.ones(preds.size(0))*output.size(3)/4.0 dists =",
"+ 1 preds = idx.repeat(1, 1, 2).float() preds[:,:,0] = (preds[:,:,0] - 1) %",
"[] #max angle error for each image res_list = [] for i in",
"normalize): preds = preds.float() target = target.float() dists = torch.zeros(preds.size(1), preds.size(0)) for n",
"a -1 ''' if dists.ne(-1).sum() > 0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy() else: return",
"import torch from .misc import * from .transforms import transform, transform_preds __all__ =",
"output[n][p] px = int(math.floor(coords[n][p][0])) py = int(math.floor(coords[n][p][1])) if px > 1 and px",
"def get_preds(scores): ''' get predictions from score maps in torch Tensor return type:",
"np.array([bbox[0][i], bbox[0][i]]) return torch.from_numpy(preds) def final_preds(output, center, scale, res): coords = get_preds(output) #",
"int(math.floor(coords[n][p][1])) if px > 1 and px < res[0] and py > 1",
"calc_dists(preds, target, normalize): preds = preds.float() target = target.float() dists = torch.zeros(preds.size(1), preds.size(0))",
"range(len(idxs)): acc[i+1] = dist_acc(dists[idxs[i]-1], thr=thr) if acc[i+1] >= 0: avg_acc = avg_acc +",
"-1 ''' if dists.ne(-1).sum() > 0: return dists.le(thr).eq(dists.ne(-1)).sum().numpy() / dists.ne(-1).sum().numpy() else: return -1",
"preds def d3_acc(preds, gts, percent = .5): num_samples = len(preds) acc = np.zeros_like(preds[0])",
"= bbox[2][i] - bbox[0][i] height = bbox[3][i] - bbox[1][i] for j in range(preds.shape[1]):",
"transform, transform_preds __all__ = ['accuracy', 'AverageMeter'] def get_preds(scores): ''' get predictions from score",
"-1 def accuracy(output, target, idxs, thr=0.5): ''' Calculate accuracy according to PCK, but",
"1: dists[c, n] = torch.dist(preds[n,c,:], target[n,c,:])/normalize[n] else: dists[c, n] = -1 return dists",
"__all__ = ['accuracy', 'AverageMeter'] def get_preds(scores): ''' get predictions from score maps in",
"predictions from score maps in torch Tensor return type: torch.LongTensor ''' assert scores.dim()",
"i in range(num_samples): pred = np.array(preds[i]) gt = np.array(gts[i]) res = np.abs(pred -",
"+ 1 preds[:,:,1] = torch.floor((preds[:,:,1] - 1) / scores.size(3)) + 1 pred_mask =",
"''' Calculate accuracy according to PCK, but uses ground truth heatmap rather than",
"from .misc import * from .transforms import transform, transform_preds __all__ = ['accuracy', 'AverageMeter']",
"p in range(coords.size(1)): hm = output[n][p] px = int(math.floor(coords[n][p][0])) py = int(math.floor(coords[n][p][1])) if",
"= [] #max angle error for each image res_list = [] for i",
"= torch.zeros(len(idxs)+1) avg_acc = 0 cnt = 0 for i in range(len(idxs)): acc[i+1]",
"= ['accuracy', 'AverageMeter'] def get_preds(scores): ''' get predictions from score maps in torch",
"each image res_list = [] for i in range(num_samples): pred = np.array(preds[i]) gt",
"-1), 2) maxval = maxval.view(scores.size(0), scores.size(1), 1) idx = idx.view(scores.size(0), scores.size(1), 1) +",
"height = bbox[3][i] - bbox[1][i] for j in range(preds.shape[1]): preds[i, j, :] =",
"and px < res[0] and py > 1 and py < res[1]: diff",
"'idxs', followed by individual accuracies ''' preds = get_preds(output) gts = get_preds(target) norm",
".misc import * from .transforms import transform, transform_preds __all__ = ['accuracy', 'AverageMeter'] def",
"(acc/top_n)[:4] class AverageMeter(object): \"\"\"Computes and stores the average and current value\"\"\" def __init__(self):",
"acc = torch.zeros(len(idxs)+1) avg_acc = 0 cnt = 0 for i in range(len(idxs)):",
"# float type # pose-processing for n in range(coords.size(0)): for p in range(coords.size(1)):",
"else: return -1 def accuracy(output, target, idxs, thr=0.5): ''' Calculate accuracy according to",
"- 1]]) coords[n][p] += diff.sign() * .25 coords[:, :, 0] += 0.5 coords[:,",
"1] -= 0.5 preds = coords.clone() # Transform back for i in range(coords.size(0)):",
"torch from .misc import * from .transforms import transform, transform_preds __all__ = ['accuracy',",
"final_preds(output, center, scale, res): coords = get_preds(output) # float type # pose-processing for",
"from random import randint import torch from .misc import * from .transforms import",
"res # hit = hit + 1 # else: # miss_list.append(i) top_n =",
"torch.Tensor([hm[py - 1][px] - hm[py - 1][px - 2], hm[py][px - 1]-hm[py -",
"# float typ preds = preds.numpy() for i in range(preds.shape[0]): width = bbox[2][i]",
"target[n,c,0] > 1 and target[n, c, 1] > 1: dists[c, n] = torch.dist(preds[n,c,:],",
"def d3_acc(preds, gts, percent = .5): num_samples = len(preds) acc = np.zeros_like(preds[0]) hit",
"locations First value to be returned is average accuracy across 'idxs', followed by",
"''' assert scores.dim() == 4, 'Score maps should be 4-dim' maxval, idx =",
"for i in range(num_samples): pred = np.array(preds[i]) gt = np.array(gts[i]) res = np.abs(pred",
"torch Tensor return type: torch.LongTensor ''' assert scores.dim() == 4, 'Score maps should",
"dists = torch.zeros(preds.size(1), preds.size(0)) for n in range(preds.size(0)): for c in range(preds.size(1)): if",
"= np.array(preds[i]) gt = np.array(gts[i]) res = np.abs(pred - gt) res[0:7] = np.abs((res[0:7]",
"center[i], scale[i], res) if preds.dim() < 3: preds = preds.view(1, preds.size()) return preds",
"# pose-processing for n in range(coords.size(0)): for p in range(coords.size(1)): hm = output[n][p]",
"/ dists.ne(-1).sum().numpy() else: return -1 def accuracy(output, target, idxs, thr=0.5): ''' Calculate accuracy",
"= torch.zeros(preds.size(1), preds.size(0)) for n in range(preds.size(0)): for c in range(preds.size(1)): if target[n,c,0]",
"hm[py - 1][px - 2], hm[py][px - 1]-hm[py - 2][px - 1]]) coords[n][p]",
"- 2][px - 1]]) coords[n][p] += diff.sign() * .25 coords[:, :, 0] +="
] |
[
"if self._secure_header['Auth'] is None: raise Exception('Auth token for the header is undefined. No",
"networking setup task completes successfully. This needs to be done for OVA's that",
"the next reboot. if self._secure_header: return self._secure_header payload = {\"userName\": \"Administrator\", \"password\": \"<PASSWORD>\"}",
"via their own API # This will embed another REST process using POST",
"request on URL: {0}. Exception: {1}'.format(calling_url, e)) def first_time_setup(self, ntpserver, use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False,",
"get the base for the payload, but # we need to know if",
"get secure connection. Status {0}.'.format(r.status_code)) try: safe_json = r.json() self._secure_header = self._header.copy() self._secure_header['Auth']",
"return ipv6address def ping(hosts): \"\"\" Returns True if host (str) responds to a",
"False if network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] = '' network[\"app1Ipv4Addr\"] = ova_ip network[\"app2Ipv4Addr\"] =",
"function depends on get_secure_headers(). Parameters ---------- request_type: str accepted values are: \"POST\", \"PUT\",",
"platform # For getting the operating system name import subprocess # For executing",
"already_reset_session = True self.sess.close() self.sess = requests.Session() adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://',",
"except requests.exceptions.RequestException as e: raise Exception(\"There was an issue connecting to the appliance",
"network definition has the \"time\" dictionary defined in it; if it does, copy",
"not success: raise Exception('get_time_locale_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True,",
"= networking_data else: appliance_mac_address = self.get_mac() ipv4_name_servers = self.get_ipv4_name_servers() # Only ipv6 with",
"r.status_code < 300: success = True else: polling_results = {'task_state': safe_json_result.get('errorCode', 'Error'), 'task_status':",
"fqdn for any subsequent rest actions and then use the fqdn to make",
"Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else: raise Exception('first_time_setup failure. Polling",
"command rest_call_timeout_sec = 60 max_retries_in_session = 50 polling_call_timeout_sec = 10 * 60 sec_between_polling",
"or integer Defaults to rest_call_timeout_sec if 'None' or unspecified Return ------ return (success,",
"# Query for current time-locale setting. time_locale_settings = self.get_time_locale_data() # Exception will be",
"True/False value. True indicates that the status_code was under 300 and the polling",
"self.sess.mount('https://', adap) if r_tree: r_treejson = r_tree.json() task_resource = r_treejson.get('resource') task_state = task_resource.get('taskState')",
"ping_output.returncode if success == 0: return (str(i)+str('%ens160')) if __name__ == '__main__': post_eula_delay =",
"if r_tree: r_treejson = r_tree.json() task_resource = r_treejson.get('resource') task_state = task_resource.get('taskState') task_status =",
"connection # to the orginal location after the POST command to set the",
"the change administrator password call fails, then we attempt to login with the",
"overrides at each REST call. if override_version: self.api_version = override_version else: self.api_version =",
"of the appliance use_ip : bool Flag to indicate if an IP address",
"IP address, FQDN, etc can make use lose the session. else: already_reset_session =",
"to get the base for the payload, but # we need to know",
"if not success: raise Exception('get_time_locale_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response,",
"until the operation completes' in ntp_polling_results.get(\"task_status\"): raise Exception( 'time-locale setting failed. Polling State:",
"ntp_polling_results.get(\"task_status\"))) else: raise Exception( 'time-locale setting failure. Polling State: {0}. Polling Status: {1}.",
"does not set DNS. If the appliance returns an error status (anything outside",
"JSON, it is set via an independent REST endpoint. :param ntpserver: IP address",
"and the accurate administrator password. If the administrator login is not successful, an",
"for POST or PUT calls, to be serialized into JSON. other_properties (optional): dict",
"{1}'.format(calling_url, e)) except Exception as e: raise Exception('Error in polling for the task.",
"def __init__(self, appliance_name, use_ip=False, override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None):",
"JSON value. polling_results: dict. dictionary with two values, task_state and task_status. Both are",
"HTTP session. appliance_dhcp_ip_address : str appliance dhcp ip address, will be used to",
"set of parameters that appliance_request() returns. Parameters ---------- calling_url : string The URL",
"in a value for override_version. Ideally, this computation should be moved to a",
"self.sess = requests.Session() adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) if r_tree: r_treejson",
"above version 100, this will set a DNS Server IP address and set",
"process using POST inside the generation of a POST to do the network",
"readIPV6FromFile() pingableipv6 = ping(ipv6address) ra = FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None,",
"self.sess.mount('https://', adap) # if version is passed in, use that. Else use the",
"False If the api_version is below version 100, it does not set DNS.",
"for {0}\".format(full_rest_url)) return(task_state, task_status) except ValueError as e: raise Exception('Error getting the JSON",
"the HTTP Call to get headers. Exception message: {0}\".format(e)) if r.status_code >= 300:",
"task_status: str. State of the task. For Example: Unknown, Running, Terminated, Error, Warning,",
"\"DHCP\": network['ipv4Type'] = \"STATIC\" network['ipv6Type'] = \"UNCONFIGURE\" networks.append(network) if use_i3s_fts: network['ipv6Type'] = \"UNCONFIGURE\"",
"Exception(\"There was an issue with the HTTP Call to get headers. Exception message:",
"is not part of the network-interfaces JSON, it is set via an independent",
"requirements that we need. Defined per program. # Eventually we may need version",
"the appliance. If the appliance returns an error status (anything outside of the",
"need to be saved.') else: logging.debug('Call EULA Acceptance with enable service access={0}'.format(service_access)) url",
"information. Return ------ _secure_header: dict. Dictionary containing X-API-Verions, Content-Type, and Auth. The Auth",
"time_locale_url = \"/rest/appliance/configuration/time-locale\" # Query for current time-locale setting. time_locale_settings = self.get_time_locale_data() #",
"admin_user, \"password\": <PASSWORD>} (logon_success, _, _, _) = self.appliance_request(request_type='POST', url=logon_url, secure=False, payload=logon_payload) if",
"resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_networking_data call",
"JSON: {0}\".format(r_treejson)) else: logging.debug(\"Exception during get call, response was not set\") logging.debug(\"Unable to",
"# of the atlas team. # # there are now at least two",
"DNS hostname. override_version (Optional): int The default version string (determined by program name)",
"if version is passed in, use that. Else use the default for the",
"as e: raise Exception('Error in polling for the task. Originating request on URL:",
"failover setups timeout: None or integer Defaults to rest_call_timeout_sec if 'None' or unspecified",
"the JSON returned from the HTTP request. None if the request did not",
"self._header else: head = self.get_secure_headers() head = dict(head.items() + extra_headers.items()) full_url = self.base_url",
"deepcopy(old_network[\"time\"]) # This is the later data model, where the time server and",
"change administrator password call fails, then we attempt to login with the administrator",
"<PASSWORD>, \"newPassword\": <PASSWORD>} (success, resp, json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if",
"Request module. The dictionary is unpacked and added to Request. For example: other_properties={'stream':",
"# place for the test below this set of conditional branches. Since both",
"if request_type == \"POST\": r = self.sess.post(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif",
"in polling for the task. Originating request on URL: {0}. Exception: {1}'.format(calling_url, e))",
"make sure the # networking setup task completes successfully. This needs to be",
"connection. Status {0}.'.format(r.status_code)) try: safe_json = r.json() self._secure_header = self._header.copy() self._secure_header['Auth'] = safe_json.get('sessionID')",
"will accept service access \"no\" will not allow service access empty value will",
"default version string (determined by program name) can be overridden. Currently only accepting",
"UI does so we follow network[\"aliasDisabled\"] = True network[\"overrideIpv4DhcpDnsServers\"] = False if network[\"app1Ipv4Addr\"]",
"dict. dictionary with two values, task_state and task_status. Both are populated whenever the",
"\"oldPassword\": <PASSWORD>, \"newPassword\": <PASSWORD>} (success, resp, json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload)",
"ntp_polling_results.get(\"task_status\"): raise Exception( 'time-locale setting failed. Polling State: {0}. Polling Status: {1}. '.format(",
"e: raise Exception('Error in polling for the task. Originating request on URL: {0}.",
"consistant with the Task Tracker mechanism. I have brought this to the attention",
"static since the ip address will change after setting up the networking. if",
"rest_call_timeout_sec if 'None' or unspecified Return ------ return (success, r, safe_json_result, polling_results) A",
"API Version utilized is {0}.\".format(self.api_version)) self._header = {'X-API-Version': '{}'.format(self.api_version), 'Content-Type': 'application/json'} self._secure_header =",
"if use_i3s_fts: network['ipv6Type'] = \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] = False network['virtIpv4Addr'] = None networks.append(network) appliance_domain_name",
"initial_admin, \"oldPassword\": <PASSWORD>, \"newPassword\": <PASSWORD>} (success, resp, json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False,",
"if not json_result: # if False, eula acceptance has already occurred. logging.warning('EULA does",
"retries (Optional): int Number of retries to do in HTTP session. appliance_dhcp_ip_address :",
"computation should be moved to a default in the datastore. Parameters ---------- appliance_name",
"file. This needs to be moved to a more formal location. Parameters ----------",
"Since both get_mac and get_ipv4_name_servers # use calls to get_networking_data, this seems poorly",
"full_rest_url = self.base_url + url task_state = 'Running' start_time = time.time() try: logging.debug(\"Starting",
"to access the sessionID from the response. Status: {0}. JSON: {1}'.format(r.status_code, r.json())) def",
"header is only good for that user (administrator), 24 hours, and until the",
"tasks will return immiedtaly - needed for failover setups timeout: None or integer",
"success: bool. A True/False value. True indicates that the status_code was under 300",
"self.sess.close() self.sess = requests.Session() adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) if r_tree:",
"except requests.exceptions.RequestException as e: raise Exception(\"There was an issue connecting to the appliance.",
"data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) # Closing file vm_network_json_file.close() return ipv6address def ping(hosts): \"\"\" Returns True",
"will be raised if an unknown value for request_type is utilized. Exceptions will",
"url location of the REST call. This method concatenates https:// and the fully",
"orginal location after the POST command to set the networking. Instead, we will",
"\"ping -c 1 google.com\" ping_command = ['ping', param, '1', i] ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE)",
"appliance_request(). Gives header information required by the appliance with authentication information. Return ------",
"have brought this to the attention # of the atlas team. # #",
"'{}'.format(self.api_version), 'Content-Type': 'application/json'} self._secure_header = {} def get_secure_headers(self): \"\"\"Helper method to appliance_request(). Gives",
"''' # network-interfaces is a special case. Rather than network-interfaces returning a object",
"calls to get_networking_data, this seems poorly designed, but given how complex the code",
"in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) # Closing file vm_network_json_file.close() return ipv6address def ping(hosts): \"\"\" Returns",
"False if r.status_code == 202: if not poll: return (True, r, safe_json_result, {'task_state':",
"if the network definition has the \"time\" dictionary defined in it; if it",
"120 logging.info(\"The API Version utilized is {0}.\".format(self.api_version)) self._header = {'X-API-Version': '{}'.format(self.api_version), 'Content-Type': 'application/json'}",
"{1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First time setup was successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True)) def readIPV6FromFile(self):",
"task. Originating request on URL: {0}. Exception: {1}'.format(calling_url, e)) except Exception as e:",
"ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\": \"\", \"ipv4Gateway\": None, \"confOneNode\": True, \"activeNode\": 1 } ],",
"to a more formal location. Parameters ---------- none \"\"\" # The changePassword REST",
"was an issue with the HTTP Call to get headers. Exception message: {0}\".format(e))",
"ipv6_type = \"UNCONFIGURE\" payload = {\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\": \"DHCP\", \"ipv6Type\": ipv6_type, \"macAddress\":",
"is {0}.\".format(self.api_version)) self._header = {'X-API-Version': '{}'.format(self.api_version), 'Content-Type': 'application/json'} self._secure_header = {} def get_secure_headers(self):",
"TaskResourceV2, this end point returns Void. # From my reading of the documentation,",
"address, will be used to connect to the appliance if not None \"\"\"",
"the atlas team. # # there are now at least two responses with",
"calls. The version can be overridden by passing in a value for override_version.",
"e: raise Exception(\"There was an issue connecting to the appliance. Exception message: {0}\".format(e))",
"for e in task_errors: logging.error(e) task_status += \";\" + \";\".join([str(e) for e in",
"set the overrideIpv4DhcpDnsServers value to False. \"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\": False If the api_version",
"# Iterating through the json list for i in data['results'][0]['msg']: for j in",
"accepted.') elif resp.status_code == 400: logon_url = '/rest/login-sessions' logon_payload = {\"userName\": admin_user, \"password\":",
"Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def accept_eula(self, service_access=\"yes\", tries=3, retry_interval=5):",
"below this set of conditional branches. Since both get_mac and get_ipv4_name_servers # use",
"None or integer Defaults to rest_call_timeout_sec if 'None' or unspecified Return ------ return",
"for response in the header, if not there, check in the JSON. Poor",
"(Optional): int The default version string (determined by program name) can be overridden.",
"and get_ipv4_name_servers # use calls to get_networking_data, this seems poorly designed, but given",
"the task. Originating request on URL: {0}. Exception: {1}'.format(calling_url, e)) except Exception as",
"Payload: {0}.\".format(json.dumps(payload))) polling_results = {} try: if request_type == \"POST\": r = self.sess.post(full_url,",
"using POST inside the generation of a POST to do the network setup.",
"in task_errors]) logging.debug(\"Percent Complete : {0}. State: {1}. Status: {2}.\".format(task_resource.get('percentComplete'), task_state, task_status)) logging.debug(\"The",
"else: raise Exception('accept_eula failed. Status: {0}. JSON Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True, indent=4, separators=(',',",
"'/rest/appliance/configuration/time-locale' # Go to checking for response in the header, if not there,",
"response.json().get('uri') if url is None: raise Exception('Could not read the task to poll.",
"polling. Exception message: {0}\".format(e)) # delete and recreate of the session if it",
"logging.warning('Administrator password has already been changed. Password is {0}'.format(<PASSWORD>)) else: raise Exception('change_administrator_password failed.",
"a more formal location. Parameters ---------- none \"\"\" # The changePassword REST end",
"session. appliance_dhcp_ip_address : str appliance dhcp ip address, will be used to connect",
"and '/rest/appliance/configuration/time-locale' # Go to checking for response in the header, if not",
"JSON. other_properties (optional): dict A dictionary of extra properties that we can give",
"password. If successful, we log a message and the accurate administrator password. If",
"polling_results.get(\"task_status\"))) else: raise Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\")))",
"password change. url = '/rest/users/changePassword' payload = {\"userName\": initial_admin, \"oldPassword\": <PASSWORD>, \"newPassword\": <PASSWORD>}",
"the task. if ova_ip: poll = False (success, response, rjson, polling_results) = self.appliance_request(request_type='POST',",
"== \"PUT\": r = self.sess.put(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type ==",
"{'task_state': safe_json_result.get('errorCode', 'Error'), 'task_status': safe_json_result.get('details', str(safe_json_result))} return (success, r, safe_json_result, polling_results) except requests.exceptions.RequestException",
"url = \"/rest/appliance/configuration/time-locale\" (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not",
"http request other than POST, PUT, or GET. request_type: {0}. url: {1}\".format(request_type, url))",
"Response 202 indicates an asynchronous REST call. Poll until the task is complete",
"url: str url location of the REST call. This method concatenates https:// and",
"already_reset_session = False while task_state in ['Running', 'New', 'Pending', 'Starting']: if time.time() >=",
"= '/rest/appliance/eula/save' payload = {\"supportAccess\": service_access} (save_success, save_resp, save_json_response, _) = self.appliance_request(request_type='POST', url=url,",
"return (success, r, safe_json_result, polling_results) except requests.exceptions.RequestException as e: raise Exception(\"There was an",
"')))) def accept_eula(self, service_access=\"yes\", tries=3, retry_interval=5): thistry = 1 while True: logging.info(\"accept_eula try",
"appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Constructor method to RestAppliance. We compute",
"{} def get_secure_headers(self): \"\"\"Helper method to appliance_request(). Gives header information required by the",
"contacted. If secure=True, this function depends on get_secure_headers(). Parameters ---------- request_type: str accepted",
"from the HTTP request. None if the request did not return a JSON",
"{0} is:\".format(full_rest_url)) logging.debug(\"Returned JSON: {0}\".format(r_treejson)) else: logging.debug(\"Exception during get call, response was not",
"This will embed another REST process using POST inside the generation of a",
"to Request. For example: other_properties={'stream': True} poll : boolean If false, polling tasks",
"200 range), an error is raised. Parameters ---------- none Return ------ list of",
"{1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server setting was successful\") def poll_for_task(self, calling_url, response):",
"raised. Parameters ---------- none Return ------ list of ipv4 name servers: list \"\"\"",
"self.use_ip = use_ip # create a persistant session so that we can retry",
"we can give to the Python Request module. The dictionary is unpacked and",
"and the fully qualified domain name of the system with this string. secure",
"ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Constructor method to RestAppliance. We compute the correct API-Version for",
"use lose the session. else: already_reset_session = True self.sess.close() self.sess = requests.Session() adap",
"try: logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree = self.sess.get(full_rest_url + \"?view=tree\", verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except",
"none Return ------ list of ipv4 name servers: list \"\"\" json_answer = self.get_networking_data()",
"# this is what UI does so we follow network[\"aliasDisabled\"] = True network[\"overrideIpv4DhcpDnsServers\"]",
"Status: {0}.'.format(r.status_code)) except: raise Exception('Failure to access the sessionID from the response. Status:",
"= {\"userName\": admin_user, \"password\": <PASSWORD>} (logon_success, _, _, _) = self.appliance_request(request_type='POST', url=logon_url, secure=False,",
"and the polling was successful. r: a response object from a Requests call.",
"networking_data.pop('serverCertificate', None) payload = networking_data else: appliance_mac_address = self.get_mac() ipv4_name_servers = self.get_ipv4_name_servers() #",
"the accurate administrator password. If the administrator login is not successful, an error",
"sort_keys=True)) def readIPV6FromFile(self): ipv6address = [] vm_network_json_file = open('vm_network.json',) data = json.load(vm_network_json_file) #",
"head = self.get_secure_headers() head = dict(head.items() + extra_headers.items()) full_url = self.base_url + url",
"success = False if r.status_code == 202: if not poll: return (True, r,",
"administrator password change is attempted. If the change administrator password call fails, then",
"= True if operating_sys == 'windows' else False # Building the command. Ex:",
"connect to the appliance if not None \"\"\" self.fqdn = appliance_name if appliance_dhcp_ip_address:",
"deepcopy import platform # For getting the operating system name import subprocess #",
"administrator password change. url = '/rest/users/changePassword' payload = {\"userName\": initial_admin, \"oldPassword\": <PASSWORD>, \"newPassword\":",
"url to the the fqdn for any subsequent rest actions and then use",
"authentication information. Return ------ _secure_header: dict. Dictionary containing X-API-Verions, Content-Type, and Auth. The",
"has already occurred. logging.warning('EULA does not need to be saved.') else: logging.debug('Call EULA",
"------ list of ipv4 name servers: list \"\"\" json_answer = self.get_networking_data() for network",
"if an unknown value for request_type is utilized. Exceptions will also be raised",
"task_status = task_resource.get('taskStatus', '') task_errors = task_resource.get('taskErrors', None) if task_errors: # in case",
"setting was successful\") def poll_for_task(self, calling_url, response): '''Helper method to appliance_request(). Status Response",
"time.time() >= start_time + polling_call_timeout_sec: raise Exception('Task Polling did not respond within {0}",
"message: {0}\".format(e)) # delete and recreate of the session if it loses connection.",
"platform.system().lower() for i in hosts: param = '-n' if operating_sys=='windows' else '-c' shell_needed",
"the appliance as DHCP. The appliance queries itself to define its macAddress. If",
"open('vm_network.json',) data = json.load(vm_network_json_file) # Iterating through the json list for i in",
"get_time_locale_data(self): \"\"\"Request the networking information from the appliance. If the appliance returns an",
"REST calls. The version can be overridden by passing in a value for",
"= \"UNCONFIGURE\" payload = {\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\": \"DHCP\", \"ipv6Type\": ipv6_type, \"macAddress\": appliance_mac_address,",
"the requirements that we need. Defined per program. # Eventually we may need",
"indicates that the status_code was under 300 and the polling was successful. r:",
"authentication information no value defaults in True payload (optional): dict Python object payload",
"Once _secure_header is defined, we can use it over and over again for",
"to rest_call_timeout_sec if 'None' or unspecified Return ------ return (success, r, safe_json_result, polling_results)",
"# '/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale' # Go to checking for response in the header,",
"status of the EULA nor the status of the service access. If a",
"success: logging.info('Administrator password change was accepted.') elif resp.status_code == 400: logon_url = '/rest/login-sessions'",
"'time-locale setting failed. Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else:",
"Exception: {1}'.format(calling_url, e)) def first_time_setup(self, ntpserver, use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None):",
"\"macAddress\": appliance_mac_address, \"hostname\": self.fqdn, \"device\": \"eth0\", \"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\": \"\", \"ipv4Gateway\":",
"old_network = self.get_networking_data() if \"time\" in old_network: payload[\"time\"] = deepcopy(old_network[\"time\"]) # This is",
"user service agreement (EULA) must be accepted. This only needs to occur once.",
"Exception('Could not read the task to poll. Originating request on URL: {0}.'.format(calling_url)) full_rest_url",
"task tree for {0}\".format(full_rest_url)) return(task_state, task_status) except ValueError as e: raise Exception('Error getting",
"} ], } # Not clear why this conditions fails to query the",
": bool Flag to indicate if an IP address is being passed instead",
"poll = True # Do not poll for the task if a ova_ip",
"The call to the administrator password change is attempted. If the change administrator",
"EULA Acceptance with enable service access={0}'.format(service_access)) url = '/rest/appliance/eula/save' payload = {\"supportAccess\": service_access}",
"until the next reboot. if self._secure_header: return self._secure_header payload = {\"userName\": \"Administrator\", \"password\":",
"end user service agreement (EULA) must be accepted. This only needs to occur",
"necessarily the NTP time, so don't set it. time_locale_settings[\"ntpServers\"] = [str(ntpserver)] # use",
"Time out and exit. Originating request on URL: {1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling) r_tree =",
"until the operation completes' in polling_results.get(\"task_status\"): raise Exception('first_time_setup failure. Polling State: {0}. Polling",
"json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def get_mac(self): \"\"\"Request the MAC address from",
"the task. For Example: Unknown, Running, Terminated, Error, Warning, Completed. ''' # network-interfaces",
"interface to get the base for the payload, but # we need to",
"Parameters ---------- none Return ------ a response object from a call to the",
"to be serialized into JSON. other_properties (optional): dict A dictionary of extra properties",
"the HTTP Call for task polling. Exception message: {0}\".format(e)) # delete and recreate",
"= {'task_state': safe_json_result.get('errorCode', 'Error'), 'task_status': safe_json_result.get('details', str(safe_json_result))} return (success, r, safe_json_result, polling_results) except",
"timeout is None: timeout = rest_call_timeout_sec if not secure: head = self._header else:",
"None networks.append(network) appliance_domain_name = self.fqdn.split(\".\", 1)[1] if appliance_domain_name not in network[\"hostname\"]: network[\"hostname\"] =",
"r.status_code == 202: if not poll: return (True, r, safe_json_result, {'task_state': 'N/A', 'task_status':",
"url: {1}\".format(request_type, url)) try: safe_json_result = r.json() except: safe_json_result = {} logging.debug(\"Returned. Status",
"https:// and the fully qualified domain name of the system with this string.",
"A tuple with these values: success: bool. A True/False value. True indicates that",
"# there are now at least two responses with the task URL in",
"None) if task_errors: # in case of errors place them in log output",
"token for the header is undefined. No Session ID available. Status: {0}.'.format(r.status_code)) return",
"the Python Request module. The dictionary is unpacked and added to Request. For",
"Address is: {0}'.format(mac_address)) return mac_address raise Exception('MAC Address is not defined') def get_ipv4_name_servers(self):",
"url = '/rest/appliance/network-interfaces' if ova_ip: networking_data = self.get_networking_data() network = networking_data['applianceNetworks'][0] network[\"hostname\"] =",
"call. This method concatenates https:// and the fully qualified domain name of the",
"not in network[\"hostname\"]: network[\"hostname\"] = network[\"hostname\"] + '.' + appliance_domain_name logging.info(\"Setting fqdn for",
"secure=False) if not json_result: # if False, eula acceptance has already occurred. logging.warning('EULA",
"This is the later data model, where the time server and locale are",
"not allow service access empty value will default to \"yes\" \"\"\" url =",
"else: raise Exception(\"Impossible happened: app1Ipv4Addr != virtIpv4Addr\") network[\"ipv6Type\"] = \"UNCONFIGURE\" payload = networking_data",
"make use lose the session. else: already_reset_session = True self.sess.close() self.sess = requests.Session()",
"\"DHCP\", \"ipv6Type\": ipv6_type, \"macAddress\": appliance_mac_address, \"hostname\": self.fqdn, \"device\": \"eth0\", \"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False,",
"the network-interfaces JSON, it is set via an independent REST endpoint. :param ntpserver:",
"follow network[\"aliasDisabled\"] = True network[\"overrideIpv4DhcpDnsServers\"] = False if network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] =",
"indent=4, separators=(',', ': '))) if 'Wait until the operation completes' in ntp_polling_results.get(\"task_status\"): raise",
"= '/rest/appliance/network-interfaces' if ova_ip: networking_data = self.get_networking_data() network = networking_data['applianceNetworks'][0] network[\"hostname\"] = self.fqdn",
"the polling was successful. r: a response object from a Requests call. safe_json_results:",
"task_status)) logging.debug(\"The task tree for {0} is:\".format(full_rest_url)) logging.debug(\"Returned JSON: {0}\".format(r_treejson)) else: logging.debug(\"Exception during",
"Flag to indicate if an IP address is being passed instead of DNS",
"the appliance with authentication information. Return ------ _secure_header: dict. Dictionary containing X-API-Verions, Content-Type,",
"command. Ex: \"ping -c 1 google.com\" ping_command = ['ping', param, '1', i] ping_output",
"indent=4, separators=(',', ': ')))) return json_response def get_time_locale_data(self): \"\"\"Request the networking information from",
"be raised if an unknown value for request_type is utilized. Exceptions will also",
"return self._secure_header payload = {\"userName\": \"Administrator\", \"password\": \"<PASSWORD>\"} url = '/rest/login-sessions' try: r",
"'application/json'} self._secure_header = {} def get_secure_headers(self): \"\"\"Helper method to appliance_request(). Gives header information",
">= tries: raise e time.sleep(retry_interval) thistry += 1 def change_administrator_password(self): \"\"\"On initial logon,",
"need to be configured as static since the ip address will change after",
"qualified name of the appliance use_ip : bool Flag to indicate if an",
"failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else: raise Exception('first_time_setup failure.",
"to be changed from the default value. The call to the administrator password",
"for current time-locale setting. time_locale_settings = self.get_time_locale_data() # Exception will be raised by",
"changed. Password is {0}'.format(<PASSWORD>)) else: raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code,",
"request.\".format(request_type)) logging.debug(\"Preparing URL: {0}.\".format(full_url)) logging.debug(\"Preparing Headers: {0}.\".format(head)) logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload))) polling_results = {}",
"to be configured as static since the ip address will change after setting",
"retry_interval=5): thistry = 1 while True: logging.info(\"accept_eula try {}\".format(thistry)) try: self.accept_eula_once(service_access=service_access) return except",
"= \"https://\" + appliance_name self.use_ip = use_ip # create a persistant session so",
"if not logon_success: raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True,",
"Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) logging.warning('Administrator password",
"logging.debug(\"The task tree for {0} is:\".format(full_rest_url)) logging.debug(\"Returned JSON: {0}\".format(r_treejson)) else: logging.debug(\"Exception during get",
"= 60 max_retries_in_session = 50 polling_call_timeout_sec = 10 * 60 sec_between_polling = 10",
"== \"Warning\": #This is required sicne FTS will try to validate the hostname",
"and task_status. Both are populated whenever the call requires task polling. \"\"\" if",
"polling_call_timeout_sec: raise Exception('Task Polling did not respond within {0} seconds. Time out and",
"to be moved to a more formal location. Parameters ---------- none \"\"\" #",
"= appliance_name if appliance_dhcp_ip_address: self.base_url = \"https://\" + appliance_dhcp_ip_address else: self.base_url = \"https://\"",
"\"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\": \"\", \"ipv4Gateway\": None, \"confOneNode\": True, \"activeNode\": 1 } ], }",
"none \"\"\" # The changePassword REST end point only works for the initial",
"by method if it fails. time_locale_settings[\"dateTime\"] = None # our time is not",
"appliance_request(). Status Response 202 indicates an asynchronous REST call. Poll until the task",
"logging.error(e) task_status += \";\" + \";\".join([str(e) for e in task_errors]) logging.debug(\"Percent Complete :",
"Reset the base url to the the fqdn for any subsequent rest actions",
"Exception message: {0}\".format(e)) # delete and recreate of the session if it loses",
"the appliance, the end user service agreement (EULA) must be accepted. This only",
"logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload))) polling_results = {} try: if request_type == \"POST\": r =",
"== 202: if not poll: return (True, r, safe_json_result, {'task_state': 'N/A', 'task_status': 'N/A'})",
"(anything outside of the 100 or 200 range), an error is raised. No",
"verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"PUT\": r = self.sess.put(full_url, verify=False,",
"of the 100 or 200 range), an error is raised. No authentication on",
"Ideally, this computation should be moved to a default in the datastore. Parameters",
"appliance_dhcp_ip_address: self.base_url = \"https://\" + appliance_dhcp_ip_address else: self.base_url = \"https://\" + appliance_name self.use_ip",
"a message and the accurate administrator password. If the administrator login is not",
"\"applianceNetworks\": [{\"ipv4Type\": \"DHCP\", \"ipv6Type\": ipv6_type, \"macAddress\": appliance_mac_address, \"hostname\": self.fqdn, \"device\": \"eth0\", \"ipv4NameServers\": ipv4_name_servers,",
"{1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else: raise Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}.",
"= safe_json.get('sessionID') if self._secure_header['Auth'] is None: raise Exception('Auth token for the header is",
"head = dict(head.items() + extra_headers.items()) full_url = self.base_url + url logging.debug(\"Preparing HTTP {0}",
"host (str) responds to a ping request. Remember that a host may not",
"except Exception as e: logging.exception(\"FTS get failed: \" + str(e)) if already_reset_session: raise",
"and over again for the duration of its life. # Note, the header",
"itself to define its macAddress. If the api_version is above version 100, this",
"used to connect to the appliance if not None \"\"\" self.fqdn = appliance_name",
"payload=payload) if save_success: logging.info('EULA Accepted.') else: raise Exception('accept_eula failed. Status: {0}. JSON Response:",
"request. Remember that a host may not respond to a ping (ICMP) request",
"timeout=timeout, **other_properties) elif request_type == \"DELETE\": r = self.sess.delete(full_url, verify=False, headers=head, timeout=timeout, **other_properties)",
"appliance_request. response : a response object from a Requests call. Return ------ tuple",
"can retry if the appliance goes offline (e.g. first time setup) self.sess =",
"timeout = rest_call_timeout_sec if not secure: head = self._header else: head = self.get_secure_headers()",
"if operating_sys == 'windows' else False # Building the command. Ex: \"ping -c",
"': ')))) return json_response def get_time_locale_data(self): \"\"\"Request the networking information from the appliance.",
"a default in the datastore. Parameters ---------- appliance_name : str fully qualified name",
"the api_version is above version 100, this will set a DNS Server IP",
"url = '/rest/users/changePassword' payload = {\"userName\": initial_admin, \"oldPassword\": <PASSWORD>, \"newPassword\": <PASSWORD>} (success, resp,",
"there, check in the JSON. Poor consistency in # implementations and inconsistent with",
"that are deployed as DHCP but, # need to be configured as static",
"\"https://\" + appliance_name self.use_ip = use_ip # create a persistant session so that",
"secure=True, this function depends on get_secure_headers(). Parameters ---------- request_type: str accepted values are:",
"self.retries = retries adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) # if version",
"to the the fqdn for any subsequent rest actions and then use the",
"hostname. override_version (Optional): int The default version string (determined by program name) can",
"passed instead of DNS hostname. override_version (Optional): int The default version string (determined",
"a header that includes authentiation information. False requests data without authentication information no",
"it. time_locale_settings[\"ntpServers\"] = [str(ntpserver)] # use the defined NTP server and only it.",
"be moved to a more formal location. Parameters ---------- none \"\"\" # The",
"was accepted.') elif resp.status_code == 400: logon_url = '/rest/login-sessions' logon_payload = {\"userName\": admin_user,",
"NTP time, so don't set it. time_locale_settings[\"ntpServers\"] = [str(ntpserver)] # use the defined",
"# we need to know if the network definition has the \"time\" dictionary",
"Status code: {0}.\".format(r.status_code)) logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result)) # 202 status codes indicate a task",
"password change is attempted. If the change administrator password call fails, then we",
"outside of the 100 or 200 range), an error is raised. No authentication",
"{1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def accept_eula(self, service_access=\"yes\", tries=3, retry_interval=5): thistry",
"Exception, Exception \"\"\" time_locale_url = \"/rest/appliance/configuration/time-locale\" # Query for current time-locale setting. time_locale_settings",
"the 100 or 200 range), an error is raised. \"\"\" url = '/rest/appliance/network-interfaces'",
"json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_time_locale_data call failed.",
"the session. else: already_reset_session = True self.sess.close() self.sess = requests.Session() adap = requests.adapters.HTTPAdapter(max_retries=self.retries)",
"works for the initial administrator password change. url = '/rest/users/changePassword' payload = {\"userName\":",
"change. url = '/rest/users/changePassword' payload = {\"userName\": initial_admin, \"oldPassword\": <PASSWORD>, \"newPassword\": <PASSWORD>} (success,",
"Error, Warning, Completed. ''' # network-interfaces is a special case. Rather than network-interfaces",
"a object of type TaskResourceV2, this end point returns Void. # From my",
"in ntp_polling_results.get(\"task_status\"): raise Exception( 'time-locale setting failed. Polling State: {0}. Polling Status: {1}.",
"successful, we log a message and the accurate administrator password. If the administrator",
"the task. Originating request on URL: {0}. Exception: {1}'.format(calling_url, e)) def first_time_setup(self, ntpserver,",
"pulled from the dictionary in this file. This needs to be moved to",
"status of the service access. If a change to the service access is",
"by the appliance with authentication information. Return ------ _secure_header: dict. Dictionary containing X-API-Verions,",
"self.fqdn.split(\".\", 1)[1] network['ipv4Type'] = \"STATIC\" network[\"searchDomains\"] = None # this is what UI",
"202 indicates an asynchronous REST call. Poll until the task is complete or",
"version 100, this will set a DNS Server IP address and set the",
"that a host may not respond to a ping (ICMP) request even if",
"should be moved to a default in the datastore. Parameters ---------- appliance_name :",
"secure=False, payload=payload) if save_success: logging.info('EULA Accepted.') else: raise Exception('accept_eula failed. Status: {0}. JSON",
"to the service access is required, see the function change_service_access() If the appliance",
"self.get_time_locale_data() # Exception will be raised by method if it fails. time_locale_settings[\"dateTime\"] =",
"'' network[\"app1Ipv4Addr\"] = ova_ip network[\"app2Ipv4Addr\"] = '' else: raise Exception(\"Impossible happened: app1Ipv4Addr !=",
"self._secure_header payload = {\"userName\": \"Administrator\", \"password\": \"<PASSWORD>\"} url = '/rest/login-sessions' try: r =",
"password change was accepted.') elif resp.status_code == 400: logon_url = '/rest/login-sessions' logon_payload =",
"Originating request on URL: {0}. Exception: {1}'.format(calling_url, e)) def first_time_setup(self, ntpserver, use_static_ip=False, use_tbird_fts=False,",
"= self.sess.post(self.base_url + url, verify=False, headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec) except requests.exceptions.RequestException as e: raise",
"url)) try: safe_json_result = r.json() except: safe_json_result = {} logging.debug(\"Returned. Status code: {0}.\".format(r.status_code))",
"to get the task tree for {0}\".format(full_rest_url)) return(task_state, task_status) except ValueError as e:",
"Accepted.') else: raise Exception('accept_eula failed. Status: {0}. JSON Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True, indent=4,",
"to make sure the # networking setup task completes successfully. This needs to",
"get_ipv4_name_servers # use calls to get_networking_data, this seems poorly designed, but given how",
"self.appliance_request(request_type='GET', url=url, secure=False) if not json_result: # if False, eula acceptance has already",
"not defined') def get_ipv4_name_servers(self): \"\"\"Request the list of dns ipv4 name servers. Use",
"it is set via an independent REST endpoint. :param ntpserver: IP address of",
"# use calls to get_networking_data, this seems poorly designed, but given how complex",
"set via their own API # This will embed another REST process using",
"this function depends on get_secure_headers(). Parameters ---------- request_type: str accepted values are: \"POST\",",
"= requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) # if version is passed in, use",
"status codes indicate a task that is pollable. The calling function may not",
"Exception(\"RestAppliance attempted to call an http request other than POST, PUT, or GET.",
"call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': '))))",
"['ping', param, '1', i] ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode if success ==",
"json import logging import time from copy import deepcopy import platform # For",
"[str(ntpserver)] # use the defined NTP server and only it. (ntp_success, _, ntp_rjson,",
"ova_ip=None, host_data=None): \"\"\"Constructor method to RestAppliance. We compute the correct API-Version for REST",
"+ str(e)) if already_reset_session: raise Exception(\"There was an issue with the HTTP Call",
"appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] = networks networking_data.pop('serverCertificate', None) payload = networking_data else: appliance_mac_address = self.get_mac()",
"self.get_networking_data() networks = [] for network in networking_data['applianceNetworks']: if network[\"ipv4Type\"] == \"DHCP\": network['ipv4Type']",
"point returns Void. # From my reading of the documentation, this is not",
"extra properties that we can give to the Python Request module. The dictionary",
"returns. Parameters ---------- calling_url : string The URL that was called in appliance_request.",
"of the atlas team. # # there are now at least two responses",
"been changed. Password is {0}'.format(<PASSWORD>)) else: raise Exception('change_administrator_password failed. Status: {0}. JSON Response:",
"# create a persistant session so that we can retry if the appliance",
"query the network interface to get the base for the payload, but #",
"set_time_server_and_locale(self, ntpserver): \"\"\" If the time definition is not part of the network-interfaces",
"Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree = self.sess.get(full_rest_url + \"?view=tree\", verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except Exception as",
"{1}\".format(request_type, url)) try: safe_json_result = r.json() except: safe_json_result = {} logging.debug(\"Returned. Status code:",
"{0} seconds. Time out and exit. Originating request on URL: {1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling)",
"the new # address and then poll for the task. if ova_ip: poll",
"check in the JSON. Poor consistency in # implementations and inconsistent with REST",
"seems to be the safest change to make. old_network = self.get_networking_data() if \"time\"",
"(str) responds to a ping request. Remember that a host may not respond",
"200 range), an error is raised. Parameters ---------- none Return ------ a response",
"elif r.status_code < 300: success = True else: polling_results = {'task_state': safe_json_result.get('errorCode', 'Error'),",
"ID available. Status: {0}.'.format(r.status_code)) return self._secure_header except ValueError as e: raise Exception('Failure to",
"except Exception as e: raise Exception(\"There was an issue with the HTTP Call.",
"this conditions fails to query the network interface to get the base for",
"setup task completes successfully. This needs to be done for OVA's that are",
"its macAddress. If the api_version is above version 100, this will set a",
"is what UI does so we follow network[\"aliasDisabled\"] = True network[\"overrideIpv4DhcpDnsServers\"] = False",
"to get secure connection. Status {0}.'.format(r.status_code)) try: safe_json = r.json() self._secure_header = self._header.copy()",
"as e: raise Exception(\"There was an issue connecting to the appliance. Exception message:",
"then it will #the warning for post-validation status. success = True elif r.status_code",
"logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True)) def readIPV6FromFile(self): ipv6address = [] vm_network_json_file = open('vm_network.json',) data =",
"# need to be configured as static since the ip address will change",
"\"\"\" operating_sys = platform.system().lower() for i in hosts: param = '-n' if operating_sys=='windows'",
"the execution/completion status task_status: str. State of the task. For Example: Unknown, Running,",
"api_version is below version 100, it does not set DNS. If the appliance",
"operation completes' in polling_results.get(\"task_status\"): raise Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}.",
"eula acceptance has already occurred. logging.warning('EULA does not need to be saved.') else:",
"in case of errors place them in log output and append to status",
"at some point later. if ipv6_type != \"DHCP\": ipv6_type = \"UNCONFIGURE\" payload =",
"1)[1] if appliance_domain_name not in network[\"hostname\"]: network[\"hostname\"] = network[\"hostname\"] + '.' + appliance_domain_name",
"dictionary is unpacked and added to Request. For example: other_properties={'stream': True} poll :",
"j in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) # Closing file vm_network_json_file.close() return ipv6address def ping(hosts): \"\"\"",
"# to the orginal location after the POST command to set the networking.",
"value. True indicates that the status_code was under 300 and the polling was",
"\"\"\" url = '/rest/appliance/eula/status' (_, _, json_result, _) = self.appliance_request(request_type='GET', url=url, secure=False) if",
"import platform # For getting the operating system name import subprocess # For",
"# For executing a shell command rest_call_timeout_sec = 60 max_retries_in_session = 50 polling_call_timeout_sec",
"Exception('IPv4 Name server is not defined') def get_networking_data(self): \"\"\"Request the networking information from",
"example: other_properties={'stream': True} poll : boolean If false, polling tasks will return immiedtaly",
"200 range), an error is raised. No authentication on the appliance is required.",
"of parameters that appliance_request() returns. Parameters ---------- calling_url : string The URL that",
"ipv4_name_servers raise Exception('IPv4 Name server is not defined') def get_networking_data(self): \"\"\"Request the networking",
"the HTTP request. None if the request did not return a JSON value.",
"agreement (EULA) must be accepted. This only needs to occur once. Additional calls",
"'' else: raise Exception(\"Impossible happened: app1Ipv4Addr != virtIpv4Addr\") network[\"ipv6Type\"] = \"UNCONFIGURE\" payload =",
"fails. time_locale_settings[\"dateTime\"] = None # our time is not necessarily the NTP time,",
"base for the payload, but # we need to know if the network",
"false, polling tasks will return immiedtaly - needed for failover setups timeout: None",
"of the ntpserver. :return: :raises: Exception, Exception \"\"\" time_locale_url = \"/rest/appliance/configuration/time-locale\" # Query",
"some point later. if ipv6_type != \"DHCP\": ipv6_type = \"UNCONFIGURE\" payload = {\"type\":",
"a Requests call. safe_json_results: the JSON returned from the HTTP request. None if",
"make. old_network = self.get_networking_data() if \"time\" in old_network: payload[\"time\"] = deepcopy(old_network[\"time\"]) # This",
"hosts: param = '-n' if operating_sys=='windows' else '-c' shell_needed = True if operating_sys",
"be overridden. Currently only accepting values of 100, 199, and 200. retries (Optional):",
"not successful, an error is raised. The administrator data is pulled from the",
"principles. url = response.headers.get('location') if url is None: url = response.json().get('uri') if url",
"containing: task_state: str. A short summary of the execution/completion status task_status: str. State",
"ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else: raise Exception( 'time-locale setting failure. Polling State: {0}. Polling Status:",
"at least two responses with the task URL in the header: # '/rest/appliance/network-interfaces'",
"= None networks.append(network) appliance_domain_name = self.fqdn.split(\".\", 1)[1] if appliance_domain_name not in network[\"hostname\"]: network[\"hostname\"]",
"= '/rest/login-sessions' logon_payload = {\"userName\": admin_user, \"password\": <PASSWORD>} (logon_success, _, _, _) =",
"network[\"app1Ipv4Addr\"] = ova_ip network[\"app2Ipv4Addr\"] = '' else: raise Exception(\"Impossible happened: app1Ipv4Addr != virtIpv4Addr\")",
"boolean If false, polling tasks will return immiedtaly - needed for failover setups",
"range), an error is raised. Parameters ---------- none Return ------ mac address: string",
"')))) return json_response def set_time_server_and_locale(self, ntpserver): \"\"\" If the time definition is not",
"If the change administrator password call fails, then we attempt to login with",
"The Auth parameter value is a sessionID. \"\"\" # Once _secure_header is defined,",
"not poll for the task if a ova_ip is passed in. If a",
"attempted. If the change administrator password call fails, then we attempt to login",
"not None \"\"\" self.fqdn = appliance_name if appliance_dhcp_ip_address: self.base_url = \"https://\" + appliance_dhcp_ip_address",
"be the safest change to make. old_network = self.get_networking_data() if \"time\" in old_network:",
"program # Default to the minimal version number that implements all the requirements",
"ntpserver = \"10.10.10.10\" ipv6address = readIPV6FromFile() pingableipv6 = ping(ipv6address) ra = FirstTimeSetUp(\"appliance_name\", override_version=3200,",
"request_type == \"POST\": r = self.sess.post(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type",
"{0}. Exception: {1}'.format(calling_url, e)) def first_time_setup(self, ntpserver, use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None,",
"in this file. This needs to be moved to a more formal location.",
"200. retries (Optional): int Number of retries to do in HTTP session. appliance_dhcp_ip_address",
"outside of the 100 or 200 range), an error is raised. Parameters ----------",
"(logon_success, _, _, _) = self.appliance_request(request_type='POST', url=logon_url, secure=False, payload=logon_payload) if not logon_success: raise",
"service agreement (EULA) must be accepted. This only needs to occur once. Additional",
"json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def set_time_server_and_locale(self, ntpserver): \"\"\" If",
"logging.info('EULA Accepted.') else: raise Exception('accept_eula failed. Status: {0}. JSON Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True,",
"defined NTP server and only it. (ntp_success, _, ntp_rjson, ntp_polling_results) = self.appliance_request(request_type='POST', url=time_locale_url,",
"of the documentation, this is not consistant with the Task Tracker mechanism. I",
"good for that user (administrator), 24 hours, and until the next reboot. if",
"under 300 and the polling was successful. r: a response object from a",
"[] for network in networking_data['applianceNetworks']: if network[\"ipv4Type\"] == \"DHCP\": network['ipv4Type'] = \"STATIC\" network['ipv6Type']",
"task. For Example: Unknown, Running, Terminated, Error, Warning, Completed. ''' # network-interfaces is",
"is {0}'.format(<PASSWORD>)) else: raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True,",
"time_locale_settings = self.get_time_locale_data() # Exception will be raised by method if it fails.",
"logging.debug(\"Starting polling the rest task {0}.\".format(url)) already_reset_session = False while task_state in ['Running',",
":raises: Exception, Exception \"\"\" time_locale_url = \"/rest/appliance/configuration/time-locale\" # Query for current time-locale setting.",
"FTS will try to validate the hostname and if it is not valid",
"until the task is complete or error. Adds to the set of parameters",
"0: return (str(i)+str('%ens160')) if __name__ == '__main__': post_eula_delay = '10' ntpserver = \"10.10.10.10\"",
"= self.get_secure_headers() head = dict(head.items() + extra_headers.items()) full_url = self.base_url + url logging.debug(\"Preparing",
"task is complete or error. Adds to the set of parameters that appliance_request()",
"host may not respond to a ping (ICMP) request even if the host",
"try to validate the hostname and if it is not valid hostname then",
"raised. Parameters ---------- none Return ------ a response object from a call to",
"the JSON results from the task. Originating request on URL: {0}. Exception: {1}'.format(calling_url,",
"is not valid hostname then it will #the warning for post-validation status. success",
"= self.appliance_request(request_type='GET', url=url, secure=False) if not json_result: # if False, eula acceptance has",
"a ping (ICMP) request even if the host name is valid. \"\"\" operating_sys",
"response. Status: {0}. JSON: {1}'.format(r.status_code, r.json())) def appliance_request(self, request_type, url, secure=True, payload=None, other_properties={},",
"information from the appliance. If the appliance returns an error status (anything outside",
"task_errors = task_resource.get('taskErrors', None) if task_errors: # in case of errors place them",
"Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else: raise Exception( 'time-locale setting failure. Polling",
"appliance goes offline (e.g. first time setup) self.sess = requests.Session() self.retries = retries",
"none Return ------ mac address: string \"\"\" json_answer = self.get_networking_data() for network in",
"this end point returns Void. # From my reading of the documentation, this",
"setups timeout: None or integer Defaults to rest_call_timeout_sec if 'None' or unspecified Return",
"to get_networking_data, this seems poorly designed, but given how complex the code is",
"Parameters ---------- none \"\"\" # The changePassword REST end point only works for",
"of type TaskResourceV2, this end point returns Void. # From my reading of",
"to get a JSON value from the response. Status: {0}.'.format(r.status_code)) except: raise Exception('Failure",
"an unknown value for request_type is utilized. Exceptions will also be raised if",
"start_time + polling_call_timeout_sec: raise Exception('Task Polling did not respond within {0} seconds. Time",
"False. \"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\": False If the api_version is below version 100, it",
"== 0: return (str(i)+str('%ens160')) if __name__ == '__main__': post_eula_delay = '10' ntpserver =",
"Status Response 202 indicates an asynchronous REST call. Poll until the task is",
"the 100 or 200 range), an error is raised. No authentication on the",
"DHCP. The appliance queries itself to define its macAddress. If the api_version is",
"will raise an error. url: str url location of the REST call. This",
"address, FQDN, etc can make use lose the session. else: already_reset_session = True",
"POST, PUT, or GET. request_type: {0}. url: {1}\".format(request_type, url)) try: safe_json_result = r.json()",
"\"\"\" self.fqdn = appliance_name if appliance_dhcp_ip_address: self.base_url = \"https://\" + appliance_dhcp_ip_address else: self.base_url",
"not know that this will return a 202. success = False if r.status_code",
"the task URL in the header: # '/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale' # Go to",
"give to the Python Request module. The dictionary is unpacked and added to",
"the EULA nor the status of the service access. If a change to",
"into JSON. other_properties (optional): dict A dictionary of extra properties that we can",
"the appliance to get headers. Exception message: {0}\".format(e)) except Exception as e: raise",
"to validate the hostname and if it is not valid hostname then it",
"ova_ip is passed in then we will lose connection # to the orginal",
"logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result)) # 202 status codes indicate a task that is pollable.",
"task_status += \";\" + \";\".join([str(e) for e in task_errors]) logging.debug(\"Percent Complete : {0}.",
"the network definition has the \"time\" dictionary defined in it; if it does,",
"\"DELETE\" Any other value will raise an error. url: str url location of",
"to appliance_request(). Status Response 202 indicates an asynchronous REST call. Poll until the",
"an error. url: str url location of the REST call. This method concatenates",
"if task_errors: # in case of errors place them in log output and",
"subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode if success == 0: return (str(i)+str('%ens160')) if __name__ ==",
"error is raised. \"\"\" url = '/rest/appliance/network-interfaces' if ova_ip: networking_data = self.get_networking_data() network",
"ntpserver. :return: :raises: Exception, Exception \"\"\" time_locale_url = \"/rest/appliance/configuration/time-locale\" # Query for current",
"': '))) if 'Wait until the operation completes' in ntp_polling_results.get(\"task_status\"): raise Exception( 'time-locale",
"session so that we can retry if the appliance goes offline (e.g. first",
"A short summary of the execution/completion status task_status: str. State of the task.",
"verify=False, headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec) except requests.exceptions.RequestException as e: raise Exception(\"There was an issue",
"polling_results.get(\"task_status\"): raise Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else:",
"return (success, r, safe_json_result, polling_results) A tuple with these values: success: bool. A",
"passed in then we will lose connection # to the orginal location after",
"version 100, it does not set DNS. If the appliance returns an error",
"change was accepted.') elif resp.status_code == 400: logon_url = '/rest/login-sessions' logon_payload = {\"userName\":",
"the documentation, this is not consistant with the Task Tracker mechanism. I have",
"= True else: success = False if not success: logging.error(json.dumps(rjson, sort_keys=True, indent=4, separators=(',',",
"even if the host name is valid. \"\"\" operating_sys = platform.system().lower() for i",
"logon_success: raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',',",
"use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping {0} seconds to wait for appliance to",
"is not defined') def get_ipv4_name_servers(self): \"\"\"Request the list of dns ipv4 name servers.",
"task_status) = self.poll_for_task(url, response) polling_results = {'task_state': task_state, 'task_status': task_status} if task_state ==",
"State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else: raise Exception( 'time-locale setting",
"safe_json_result, polling_results) except requests.exceptions.RequestException as e: raise Exception(\"There was an issue connecting to",
"instead of DNS hostname. override_version (Optional): int The default version string (determined by",
"{0}'.format(ipv4_name_servers)) return ipv4_name_servers raise Exception('IPv4 Name server is not defined') def get_networking_data(self): \"\"\"Request",
"does, copy into # place for the test below this set of conditional",
"ipv6address.append(j) # Closing file vm_network_json_file.close() return ipv6address def ping(hosts): \"\"\" Returns True if",
"two values, task_state and task_status. Both are populated whenever the call requires task",
"only it. (ntp_success, _, ntp_rjson, ntp_polling_results) = self.appliance_request(request_type='POST', url=time_locale_url, secure=True, payload=time_locale_settings) if not",
"set it. time_locale_settings[\"ntpServers\"] = [str(ntpserver)] # use the defined NTP server and only",
"network[\"overrideIpv4DhcpDnsServers\"] = False network['virtIpv4Addr'] = None networks.append(network) appliance_domain_name = self.fqdn.split(\".\", 1)[1] if appliance_domain_name",
"'/rest/appliance/eula/status' (_, _, json_result, _) = self.appliance_request(request_type='GET', url=url, secure=False) if not json_result: #",
"ip address, will be used to connect to the appliance if not None",
"list of ipv4 name servers: list \"\"\" json_answer = self.get_networking_data() for network in",
"task. Originating request on URL: {0}. Exception: {1}'.format(calling_url, e)) def first_time_setup(self, ntpserver, use_static_ip=False,",
"= '' else: raise Exception(\"Impossible happened: app1Ipv4Addr != virtIpv4Addr\") network[\"ipv6Type\"] = \"UNCONFIGURE\" payload",
"its life. # Note, the header is only good for that user (administrator),",
"on URL: {0}. Exception: {1}'.format(calling_url, e)) except Exception as e: raise Exception('Error in",
"how complex the code is in this # area and the lack of",
"the networking. Instead, we will change to the new # address and then",
"self.sess.delete(full_url, verify=False, headers=head, timeout=timeout, **other_properties) else: raise Exception(\"RestAppliance attempted to call an http",
"safest change to make. old_network = self.get_networking_data() if \"time\" in old_network: payload[\"time\"] =",
"If false, polling tasks will return immiedtaly - needed for failover setups timeout:",
"happened: app1Ipv4Addr != virtIpv4Addr\") network[\"ipv6Type\"] = \"UNCONFIGURE\" payload = networking_data elif use_static_ip: networking_data",
"= requests.Session() adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) if r_tree: r_treejson =",
"If successful, we log a message and the accurate administrator password. If the",
"if ova_ip: poll = False (success, response, rjson, polling_results) = self.appliance_request(request_type='POST', url=url, secure=True,",
"dictionary of extra properties that we can give to the Python Request module.",
"with these values: success: bool. A True/False value. True indicates that the status_code",
"call HTTP requests. An exception will be raised if an unknown value for",
"poll for the task if a ova_ip is passed in. If a ova_ip",
"------ a response object from a call to the network page. \"\"\" url",
"datastore. Parameters ---------- appliance_name : str fully qualified name of the appliance use_ip",
"out and exit. Originating request on URL: {1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling) r_tree = None",
"it will #the warning for post-validation status. success = True elif r.status_code <",
"separators=(',', ': ')))) return json_response def set_time_server_and_locale(self, ntpserver): \"\"\" If the time definition",
"information required by the appliance with authentication information. Return ------ _secure_header: dict. Dictionary",
"service access empty value will default to \"yes\" \"\"\" url = '/rest/appliance/eula/status' (_,",
"'/rest/appliance/network-interfaces' (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise",
"if ipv6_type != \"DHCP\": ipv6_type = \"UNCONFIGURE\" payload = {\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\":",
"For getting the operating system name import subprocess # For executing a shell",
"is pollable. The calling function may not know that this will return a",
"raise Exception(\"There was an issue with the HTTP Call to get headers. Exception",
"poll. Originating request on URL: {0}.'.format(calling_url)) full_rest_url = self.base_url + url task_state =",
"'/rest/users/changePassword' payload = {\"userName\": initial_admin, \"oldPassword\": <PASSWORD>, \"newPassword\": <PASSWORD>} (success, resp, json_response, _)",
"page. \"\"\" url = \"/rest/appliance/configuration/time-locale\" (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True)",
">= 300: raise Exception('Failure to get secure connection. Status {0}.'.format(r.status_code)) try: safe_json =",
"the base for the payload, but # we need to know if the",
"True elif self.use_ip and task_state == \"Warning\": #This is required sicne FTS will",
"---------- none Return ------ list of ipv4 name servers: list \"\"\" json_answer =",
"payload=None, other_properties={}, extra_headers={}, poll=True, timeout=None): \"\"\"Helper method to call HTTP requests. An exception",
"= '/rest/login-sessions' try: r = self.sess.post(self.base_url + url, verify=False, headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec) except",
"task_errors: # in case of errors place them in log output and append",
"of 100, 199, and 200. retries (Optional): int Number of retries to do",
"\"time\" in old_network: payload[\"time\"] = deepcopy(old_network[\"time\"]) # This is the later data model,",
"logging.debug(\"Returned. Status code: {0}.\".format(r.status_code)) logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result)) # 202 status codes indicate a",
"100, this will set a DNS Server IP address and set the overrideIpv4DhcpDnsServers",
"== \"Completed\": success = True elif self.use_ip and task_state == \"Warning\": #This is",
"ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server setting was successful\") def poll_for_task(self, calling_url, response): '''Helper method to",
"Unknown, Running, Terminated, Error, Warning, Completed. ''' # network-interfaces is a special case.",
"True # Do not poll for the task if a ova_ip is passed",
"execution/completion status task_status: str. State of the task. For Example: Unknown, Running, Terminated,",
"Remember that a host may not respond to a ping (ICMP) request even",
"= \"/rest/appliance/configuration/time-locale\" # Query for current time-locale setting. time_locale_settings = self.get_time_locale_data() # Exception",
"raised. \"\"\" url = '/rest/appliance/network-interfaces' if ova_ip: networking_data = self.get_networking_data() network = networking_data['applianceNetworks'][0]",
"of documented test cases, this seems to be the safest change to make.",
"current time-locale setting. time_locale_settings = self.get_time_locale_data() # Exception will be raised by method",
"self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if success: logging.info('Administrator password change was accepted.') elif resp.status_code",
"False, \"ipv4Subnet\": \"\", \"ipv4Gateway\": None, \"confOneNode\": True, \"activeNode\": 1 } ], } #",
"(success, resp, json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if success: logging.info('Administrator password",
"responses with the task URL in the header: # '/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale' #",
"the appliance cannot be contacted. If secure=True, this function depends on get_secure_headers(). Parameters",
"call. Return ------ tuple containing: task_state: str. A short summary of the execution/completion",
"{1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling) r_tree = None try: logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree = self.sess.get(full_rest_url",
"networking_data['applianceNetworks']: if network[\"ipv4Type\"] == \"DHCP\": network['ipv4Type'] = \"STATIC\" network['ipv6Type'] = \"UNCONFIGURE\" networks.append(network) if",
"{0}\".format(time.asctime(time.localtime(time.time())))) r_tree = self.sess.get(full_rest_url + \"?view=tree\", verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except Exception as e:",
"raise Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First time",
"not respond within {0} seconds. Time out and exit. Originating request on URL:",
"it does, copy into # place for the test below this set of",
"and inconsistent with REST principles. url = response.headers.get('location') if url is None: url",
"= True network[\"overrideIpv4DhcpDnsServers\"] = False if network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] = '' network[\"app1Ipv4Addr\"]",
"use_static_ip: networking_data = self.get_networking_data() networks = [] for network in networking_data['applianceNetworks']: if network[\"ipv4Type\"]",
"thistry = 1 while True: logging.info(\"accept_eula try {}\".format(thistry)) try: self.accept_eula_once(service_access=service_access) return except Exception",
"if thistry >= tries: raise e time.sleep(retry_interval) thistry += 1 def change_administrator_password(self): \"\"\"On",
"FQDN, etc can make use lose the session. else: already_reset_session = True self.sess.close()",
": boolean If false, polling tasks will return immiedtaly - needed for failover",
"self.fqdn, \"device\": \"eth0\", \"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\": \"\", \"ipv4Gateway\": None, \"confOneNode\": True,",
"as e: logging.exception(e) if thistry >= tries: raise e time.sleep(retry_interval) thistry += 1",
"= [] for network in networking_data['applianceNetworks']: if network[\"ipv4Type\"] == \"DHCP\": network['ipv4Type'] = \"STATIC\"",
"definition is not part of the network-interfaces JSON, it is set via an",
"None # our time is not necessarily the NTP time, so don't set",
"return ipv4_name_servers raise Exception('IPv4 Name server is not defined') def get_networking_data(self): \"\"\"Request the",
"range), an error is raised. \"\"\" url = '/rest/appliance/network-interfaces' if ova_ip: networking_data =",
"whenever the call requires task polling. \"\"\" if timeout is None: timeout =",
"= platform.system().lower() for i in hosts: param = '-n' if operating_sys=='windows' else '-c'",
"data=json.dumps(payload), timeout=rest_call_timeout_sec) except requests.exceptions.RequestException as e: raise Exception(\"There was an issue connecting to",
"= \"10.10.10.10\" ipv6address = readIPV6FromFile() pingableipv6 = ping(ipv6address) ra = FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False,",
"\"GET\", \"DELETE\" Any other value will raise an error. url: str url location",
"failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def",
"seconds. Time out and exit. Originating request on URL: {1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling) r_tree",
"def get_secure_headers(self): \"\"\"Helper method to appliance_request(). Gives header information required by the appliance",
"\"ipv6Type\": ipv6_type, \"macAddress\": appliance_mac_address, \"hostname\": self.fqdn, \"device\": \"eth0\", \"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\":",
"= self.get_time_locale_data() # Exception will be raised by method if it fails. time_locale_settings[\"dateTime\"]",
"task_resource.get('taskStatus', '') task_errors = task_resource.get('taskErrors', None) if task_errors: # in case of errors",
"r.json() except: safe_json_result = {} logging.debug(\"Returned. Status code: {0}.\".format(r.status_code)) logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result)) #",
"that includes authentiation information. False requests data without authentication information no value defaults",
"in json_answer.get('applianceNetworks', []): ipv4_name_servers = network.get('ipv4NameServers') if ipv4_name_servers: logging.info('IPv4 Name servers: {0}'.format(ipv4_name_servers)) return",
"inconsistent with REST principles. url = response.headers.get('location') if url is None: url =",
"ova_ip=None, host_data=None): \"\"\"Creates networking for the appliance. Configures the appliance as DHCP. The",
"executing a shell command rest_call_timeout_sec = 60 max_retries_in_session = 50 polling_call_timeout_sec = 10",
"not valid hostname then it will #the warning for post-validation status. success =",
"str appliance dhcp ip address, will be used to connect to the appliance",
"Status {0}.'.format(r.status_code)) try: safe_json = r.json() self._secure_header = self._header.copy() self._secure_header['Auth'] = safe_json.get('sessionID') if",
"administrator password. If the administrator login is not successful, an error is raised.",
"it does not set DNS. If the appliance returns an error status (anything",
"{0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First time setup was successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2,",
"from a Requests call. Return ------ tuple containing: task_state: str. A short summary",
"service_access=\"yes\"): \"\"\"On initial communication with the appliance, the end user service agreement (EULA)",
"a Requests call. Return ------ tuple containing: task_state: str. A short summary of",
"self.fqdn (task_state, task_status) = self.poll_for_task(url, response) polling_results = {'task_state': task_state, 'task_status': task_status} if",
"the host name is valid. \"\"\" operating_sys = platform.system().lower() for i in hosts:",
"json_result: # if False, eula acceptance has already occurred. logging.warning('EULA does not need",
"while True: logging.info(\"accept_eula try {}\".format(thistry)) try: self.accept_eula_once(service_access=service_access) return except Exception as e: logging.exception(e)",
"FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping {0} seconds",
"the POST command to set the networking. Instead, we will change to the",
"override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Constructor method to RestAppliance.",
"formal location. Parameters ---------- none \"\"\" # The changePassword REST end point only",
"message and the accurate administrator password. If the administrator login is not successful,",
"a call to the network page. \"\"\" url = '/rest/appliance/network-interfaces' (success, resp, json_response,",
"an error is raised. Parameters ---------- none Return ------ mac address: string \"\"\"",
"need. Defined per program. # Eventually we may need version overrides at each",
"unpacked and added to Request. For example: other_properties={'stream': True} poll : boolean If",
"import logging import time from copy import deepcopy import platform # For getting",
"in network[\"hostname\"]: network[\"hostname\"] = network[\"hostname\"] + '.' + appliance_domain_name logging.info(\"Setting fqdn for the",
"operating_sys=='windows' else '-c' shell_needed = True if operating_sys == 'windows' else False #",
"\"\"\"Helper method to call HTTP requests. An exception will be raised if an",
"sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def set_time_server_and_locale(self, ntpserver): \"\"\" If the",
"raise Exception('Error getting the JSON results from the task. Originating request on URL:",
"\"DELETE\": r = self.sess.delete(full_url, verify=False, headers=head, timeout=timeout, **other_properties) else: raise Exception(\"RestAppliance attempted to",
"safe_json_result = {} logging.debug(\"Returned. Status code: {0}.\".format(r.status_code)) logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result)) # 202 status",
"is:\".format(full_rest_url)) logging.debug(\"Returned JSON: {0}\".format(r_treejson)) else: logging.debug(\"Exception during get call, response was not set\")",
"already been changed. Password is {0}'.format(<PASSWORD>)) else: raise Exception('change_administrator_password failed. Status: {0}. JSON",
"Content-Type, and Auth. The Auth parameter value is a sessionID. \"\"\" # Once",
"headers=head, timeout=timeout, **other_properties) elif request_type == \"DELETE\": r = self.sess.delete(full_url, verify=False, headers=head, timeout=timeout,",
"value will default to \"yes\" \"\"\" url = '/rest/appliance/eula/status' (_, _, json_result, _)",
"will not allow service access empty value will default to \"yes\" \"\"\" url",
"request on URL: {0}.'.format(calling_url)) full_rest_url = self.base_url + url task_state = 'Running' start_time",
"success = True else: success = False if not success: logging.error(json.dumps(rjson, sort_keys=True, indent=4,",
"url=logon_url, secure=False, payload=logon_payload) if not logon_success: raise Exception('change_administrator_password failed. Status: {0}. JSON Response:",
"service access is required, see the function change_service_access() If the appliance returns an",
"the task to poll. Originating request on URL: {0}.'.format(calling_url)) full_rest_url = self.base_url +",
"\"\"\" # Once _secure_header is defined, we can use it over and over",
"not return a JSON value. polling_results: dict. dictionary with two values, task_state and",
"= 120 logging.info(\"The API Version utilized is {0}.\".format(self.api_version)) self._header = {'X-API-Version': '{}'.format(self.api_version), 'Content-Type':",
"100 or 200 range), an error is raised. Parameters ---------- none Return ------",
"= task_resource.get('taskState') task_status = task_resource.get('taskStatus', '') task_errors = task_resource.get('taskErrors', None) if task_errors: #",
"self.poll_for_task(url, r) polling_results = {'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\": success",
"success == 0: return (str(i)+str('%ens160')) if __name__ == '__main__': post_eula_delay = '10' ntpserver",
"logon_url = '/rest/login-sessions' logon_payload = {\"userName\": admin_user, \"password\": <PASSWORD>} (logon_success, _, _, _)",
"!= \"DHCP\": ipv6_type = \"UNCONFIGURE\" payload = {\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\": \"DHCP\", \"ipv6Type\":",
"ping (ICMP) request even if the host name is valid. \"\"\" operating_sys =",
"Exception('get_networking_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ':",
"else: self.api_version = 120 logging.info(\"The API Version utilized is {0}.\".format(self.api_version)) self._header = {'X-API-Version':",
"Exception will be raised by method if it fails. time_locale_settings[\"dateTime\"] = None #",
"secure=True) if not success: raise Exception('get_networking_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code,",
"Exception: {1}'.format(calling_url, e)) except Exception as e: raise Exception('Error in polling for the",
"by passing in a value for override_version. Ideally, this computation should be moved",
"= {\"supportAccess\": service_access} (save_success, save_resp, save_json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if",
"ntpserver: IP address of the ntpserver. :return: :raises: Exception, Exception \"\"\" time_locale_url =",
"value from the response. Status: {0}.'.format(r.status_code)) except: raise Exception('Failure to access the sessionID",
"undefined. No Session ID available. Status: {0}.'.format(r.status_code)) return self._secure_header except ValueError as e:",
"the datastore. Parameters ---------- appliance_name : str fully qualified name of the appliance",
"e)) def first_time_setup(self, ntpserver, use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Creates networking",
"(administrator), 24 hours, and until the next reboot. if self._secure_header: return self._secure_header payload",
"on URL: {0}.'.format(calling_url)) full_rest_url = self.base_url + url task_state = 'Running' start_time =",
"calling function may not know that this will return a 202. success =",
"warning for post-validation status. success = True elif r.status_code < 300: success =",
"is complete or error. Adds to the set of parameters that appliance_request() returns.",
"url is None: url = response.json().get('uri') if url is None: raise Exception('Could not",
"POST or PUT calls, to be serialized into JSON. other_properties (optional): dict A",
"logging.warning('EULA does not need to be saved.') else: logging.debug('Call EULA Acceptance with enable",
"if network[\"ipv4Type\"] == \"DHCP\": network['ipv4Type'] = \"STATIC\" network['ipv6Type'] = \"UNCONFIGURE\" networks.append(network) if use_i3s_fts:",
"r = self.sess.get(full_url, verify=False, headers=head, timeout=timeout, **other_properties) elif request_type == \"DELETE\": r =",
"log a message and the accurate administrator password. If the administrator login is",
"the duration of its life. # Note, the header is only good for",
"that is pollable. The calling function may not know that this will return",
"communication with the appliance, the end user service agreement (EULA) must be accepted.",
"MAC address from the appliance. Use the first one found in applianceNetworks collection.",
"retries adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) # if version is passed",
"do in HTTP session. appliance_dhcp_ip_address : str appliance dhcp ip address, will be",
"to call an http request other than POST, PUT, or GET. request_type: {0}.",
": {0}. State: {1}. Status: {2}.\".format(task_resource.get('percentComplete'), task_state, task_status)) logging.debug(\"The task tree for {0}",
"set a DNS Server IP address and set the overrideIpv4DhcpDnsServers value to False.",
"definition has the \"time\" dictionary defined in it; if it does, copy into",
"r, safe_json_result, polling_results) except requests.exceptions.RequestException as e: raise Exception(\"There was an issue connecting",
"hostname and if it is not valid hostname then it will #the warning",
"I have brought this to the attention # of the atlas team. #",
"REST call. if override_version: self.api_version = override_version else: self.api_version = 120 logging.info(\"The API",
"a task that is pollable. The calling function may not know that this",
"the fqdn to make sure the # networking setup task completes successfully. This",
"task_state = task_resource.get('taskState') task_status = task_resource.get('taskStatus', '') task_errors = task_resource.get('taskErrors', None) if task_errors:",
"timeout=rest_call_timeout_sec) except Exception as e: logging.exception(\"FTS get failed: \" + str(e)) if already_reset_session:",
"Dictionary containing X-API-Verions, Content-Type, and Auth. The Auth parameter value is a sessionID.",
"to the Python Request module. The dictionary is unpacked and added to Request.",
"verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except Exception as e: logging.exception(\"FTS get failed: \" + str(e))",
"actions and then use the fqdn to make sure the # networking setup",
"in, use that. Else use the default for the program # Default to",
"None) payload = networking_data else: appliance_mac_address = self.get_mac() ipv4_name_servers = self.get_ipv4_name_servers() # Only",
"None try: logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree = self.sess.get(full_rest_url + \"?view=tree\", verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec)",
"[dns_server_ip], \"overrideIpv4DhcpDnsServers\": False If the api_version is below version 100, it does not",
"1 } ], } # Not clear why this conditions fails to query",
"try: safe_json = r.json() self._secure_header = self._header.copy() self._secure_header['Auth'] = safe_json.get('sessionID') if self._secure_header['Auth'] is",
"raise Exception('Auth token for the header is undefined. No Session ID available. Status:",
"need to know if the network definition has the \"time\" dictionary defined in",
"network['ipv6Type'] = \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] = False network['virtIpv4Addr'] = None networks.append(network) appliance_domain_name = self.fqdn.split(\".\",",
"response, rjson, polling_results) = self.appliance_request(request_type='POST', url=url, secure=True, payload=payload, poll=poll) # Reset the base",
"r = self.sess.delete(full_url, verify=False, headers=head, timeout=timeout, **other_properties) else: raise Exception(\"RestAppliance attempted to call",
"two responses with the task URL in the header: # '/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale'",
"Currently only accepting values of 100, 199, and 200. retries (Optional): int Number",
"url is None: raise Exception('Could not read the task to poll. Originating request",
"save_json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if save_success: logging.info('EULA Accepted.') else: raise",
"the appliance returns an error status (anything outside of the 100 or 200",
"task {0}.\".format(url)) already_reset_session = False while task_state in ['Running', 'New', 'Pending', 'Starting']: if",
"an issue connecting to the appliance. Exception message: {0}\".format(e)) except Exception as e:",
"the generation of a POST to do the network setup. self.set_time_server_and_locale(ntpserver) poll =",
"outside of the 100 or 200 range), an error is raised. \"\"\" url",
"is raised. Parameters ---------- none Return ------ a response object from a call",
"\"\"\"Constructor method to RestAppliance. We compute the correct API-Version for REST calls. The",
"Originating request on URL: {0}. Exception: {1}'.format(calling_url, e)) except Exception as e: raise",
"server and locale are set via their own API # This will embed",
"was successful. r: a response object from a Requests call. safe_json_results: the JSON",
"requests.Session() adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) if r_tree: r_treejson = r_tree.json()",
"not set DNS. If the appliance returns an error status (anything outside of",
"branches. Since both get_mac and get_ipv4_name_servers # use calls to get_networking_data, this seems",
"ping_command = ['ping', param, '1', i] ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode if",
"is required sicne FTS will try to validate the hostname and if it",
"if host (str) responds to a ping request. Remember that a host may",
"Exception('accept_eula failed. Status: {0}. JSON Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True, indent=4, separators=(',', ': '))))",
"headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"PUT\": r = self.sess.put(full_url, verify=False, headers=head,",
"This only needs to occur once. Additional calls will not change the status",
"for the appliance. Configures the appliance as DHCP. The appliance queries itself to",
"are populated whenever the call requires task polling. \"\"\" if timeout is None:",
"if network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] = '' network[\"app1Ipv4Addr\"] = ova_ip network[\"app2Ipv4Addr\"] = ''",
"by program name) can be overridden. Currently only accepting values of 100, 199,",
"ra = FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping",
"override_version else: self.api_version = 120 logging.info(\"The API Version utilized is {0}.\".format(self.api_version)) self._header =",
"# use the defined NTP server and only it. (ntp_success, _, ntp_rjson, ntp_polling_results)",
"response object from a Requests call. safe_json_results: the JSON returned from the HTTP",
"calls, to be serialized into JSON. other_properties (optional): dict A dictionary of extra",
"logging.debug(\"Preparing Headers: {0}.\".format(head)) logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload))) polling_results = {} try: if request_type ==",
"Exception('Failure to access the sessionID from the response. Status: {0}. JSON: {1}'.format(r.status_code, r.json()))",
"for the payload, but # we need to know if the network definition",
"number that implements all the requirements that we need. Defined per program. #",
"__name__ == '__main__': post_eula_delay = '10' ntpserver = \"10.10.10.10\" ipv6address = readIPV6FromFile() pingableipv6",
"success = True else: polling_results = {'task_state': safe_json_result.get('errorCode', 'Error'), 'task_status': safe_json_result.get('details', str(safe_json_result))} return",
"password has already been changed. Password is {0}'.format(<PASSWORD>)) else: raise Exception('change_administrator_password failed. Status:",
"the initial administrator password change. url = '/rest/users/changePassword' payload = {\"userName\": initial_admin, \"oldPassword\":",
"not change the status of the EULA nor the status of the service",
"reading of the documentation, this is not consistant with the Task Tracker mechanism.",
"else: logging.debug(\"Exception during get call, response was not set\") logging.debug(\"Unable to get the",
"wait for appliance to stabilize\".format(post_eula_delay)) time.sleep(post_eula_delay) ra.change_administrator_password() ra.first_time_setup(ntpserver, use_static_ip=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None,",
"pollable. The calling function may not know that this will return a 202.",
"during get call, response was not set\") logging.debug(\"Unable to get the task tree",
"self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_networking_data call failed. Status: {0}. JSON",
"resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_time_locale_data call",
"and locale are set via their own API # This will embed another",
"the operating system name import subprocess # For executing a shell command rest_call_timeout_sec",
"= {\"userName\": \"Administrator\", \"password\": \"<PASSWORD>\"} url = '/rest/login-sessions' try: r = self.sess.post(self.base_url +",
"lack of documented test cases, this seems to be the safest change to",
"'N/A', 'task_status': 'N/A'}) (task_state, task_status) = self.poll_for_task(url, r) polling_results = {'task_state': task_state, 'task_status':",
"'/rest/login-sessions' logon_payload = {\"userName\": admin_user, \"password\": <PASSWORD>} (logon_success, _, _, _) = self.appliance_request(request_type='POST',",
"not success: logging.error(json.dumps(rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until the operation",
"(ICMP) request even if the host name is valid. \"\"\" operating_sys = platform.system().lower()",
"task_state, 'task_status': task_status} if task_state == \"Completed\": success = True elif self.use_ip and",
"extra_headers.items()) full_url = self.base_url + url logging.debug(\"Preparing HTTP {0} request.\".format(request_type)) logging.debug(\"Preparing URL: {0}.\".format(full_url))",
"a value for override_version. Ideally, this computation should be moved to a default",
"to the minimal version number that implements all the requirements that we need.",
"the network setup. self.set_time_server_and_locale(ntpserver) poll = True # Do not poll for the",
"r_tree = None try: logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree = self.sess.get(full_rest_url + \"?view=tree\", verify=False,",
"< 300: success = True else: polling_results = {'task_state': safe_json_result.get('errorCode', 'Error'), 'task_status': safe_json_result.get('details',",
"'/rest/login-sessions' try: r = self.sess.post(self.base_url + url, verify=False, headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec) except requests.exceptions.RequestException",
"= self.sess.put(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"GET\": r =",
"We compute the correct API-Version for REST calls. The version can be overridden",
"sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until the operation completes' in ntp_polling_results.get(\"task_status\"):",
"response in the header, if not there, check in the JSON. Poor consistency",
"in IP address, FQDN, etc can make use lose the session. else: already_reset_session",
"State: {1}. Status: {2}.\".format(task_resource.get('percentComplete'), task_state, task_status)) logging.debug(\"The task tree for {0} is:\".format(full_rest_url)) logging.debug(\"Returned",
"'-n' if operating_sys=='windows' else '-c' shell_needed = True if operating_sys == 'windows' else",
"data['results'][0]['msg']: for j in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) # Closing file vm_network_json_file.close() return ipv6address def",
"of the REST call. This method concatenates https:// and the fully qualified domain",
"version can be overridden by passing in a value for override_version. Ideally, this",
"self._secure_header: return self._secure_header payload = {\"userName\": \"Administrator\", \"password\": \"<PASSWORD>\"} url = '/rest/login-sessions' try:",
"with the HTTP Call to get headers. Exception message: {0}\".format(e)) if r.status_code >=",
"appliance_dhcp_ip_address : str appliance dhcp ip address, will be used to connect to",
"r, safe_json_result, polling_results) A tuple with these values: success: bool. A True/False value.",
"other_properties={}, extra_headers={}, poll=True, timeout=None): \"\"\"Helper method to call HTTP requests. An exception will",
"self.get_secure_headers() head = dict(head.items() + extra_headers.items()) full_url = self.base_url + url logging.debug(\"Preparing HTTP",
"to a ping request. Remember that a host may not respond to a",
"networking_data['applianceNetworks'] = networks networking_data.pop('serverCertificate', None) payload = networking_data else: appliance_mac_address = self.get_mac() ipv4_name_servers",
"defined in it; if it does, copy into # place for the test",
"Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server setting was successful\") def poll_for_task(self, calling_url,",
"the status of the EULA nor the status of the service access. If",
"{1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) logging.warning('Administrator password has already been changed.",
"service_access=\"yes\", tries=3, retry_interval=5): thistry = 1 while True: logging.info(\"accept_eula try {}\".format(thistry)) try: self.accept_eula_once(service_access=service_access)",
"json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []): ipv4_name_servers = network.get('ipv4NameServers') if ipv4_name_servers:",
"on URL: {1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling) r_tree = None try: logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree",
"Example: Unknown, Running, Terminated, Error, Warning, Completed. ''' # network-interfaces is a special",
"use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping {0} seconds to wait",
"== \"Completed\": success = True else: success = False if not success: logging.error(json.dumps(rjson,",
"else: raise Exception(\"RestAppliance attempted to call an http request other than POST, PUT,",
"except: safe_json_result = {} logging.debug(\"Returned. Status code: {0}.\".format(r.status_code)) logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result)) # 202",
"override_version (Optional): int The default version string (determined by program name) can be",
"but given how complex the code is in this # area and the",
"+= \";\" + \";\".join([str(e) for e in task_errors]) logging.debug(\"Percent Complete : {0}. State:",
"the payload, but # we need to know if the network definition has",
"acceptance has already occurred. logging.warning('EULA does not need to be saved.') else: logging.debug('Call",
"Eventually we may need version overrides at each REST call. if override_version: self.api_version",
"Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def get_time_locale_data(self): \"\"\"Request",
"with the administrator password. If successful, we log a message and the accurate",
"---------- none \"\"\" # The changePassword REST end point only works for the",
"Defined per program. # Eventually we may need version overrides at each REST",
"case. Rather than network-interfaces returning a object of type TaskResourceV2, this end point",
"task_resource.get('taskState') task_status = task_resource.get('taskStatus', '') task_errors = task_resource.get('taskErrors', None) if task_errors: # in",
"location after the POST command to set the networking. Instead, we will change",
"of a POST to do the network setup. self.set_time_server_and_locale(ntpserver) poll = True #",
"return immiedtaly - needed for failover setups timeout: None or integer Defaults to",
"login is not successful, an error is raised. The administrator data is pulled",
"(success, response, rjson, polling_results) = self.appliance_request(request_type='POST', url=url, secure=True, payload=payload, poll=poll) # Reset the",
"that implements all the requirements that we need. Defined per program. # Eventually",
"requests data without authentication information no value defaults in True payload (optional): dict",
"change is attempted. If the change administrator password call fails, then we attempt",
"OVA's that are deployed as DHCP but, # need to be configured as",
"1 def change_administrator_password(self): \"\"\"On initial logon, the administrator's password has to be changed",
"version overrides at each REST call. if override_version: self.api_version = override_version else: self.api_version",
":param ntpserver: IP address of the ntpserver. :return: :raises: Exception, Exception \"\"\" time_locale_url",
"\"overrideIpv4DhcpDnsServers\": False If the api_version is below version 100, it does not set",
"DNS. If the appliance returns an error status (anything outside of the 100",
"host_data=None): \"\"\"Constructor method to RestAppliance. We compute the correct API-Version for REST calls.",
"sure the # networking setup task completes successfully. This needs to be done",
"URL in the header: # '/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale' # Go to checking for",
"header, if not there, check in the JSON. Poor consistency in # implementations",
"try: logging.debug(\"Starting polling the rest task {0}.\".format(url)) already_reset_session = False while task_state in",
"raised if the appliance cannot be contacted. If secure=True, this function depends on",
"[]): ipv4_name_servers = network.get('ipv4NameServers') if ipv4_name_servers: logging.info('IPv4 Name servers: {0}'.format(ipv4_name_servers)) return ipv4_name_servers raise",
"success = True elif self.use_ip and task_state == \"Warning\": #This is required sicne",
"# Building the command. Ex: \"ping -c 1 google.com\" ping_command = ['ping', param,",
"secure: head = self._header else: head = self.get_secure_headers() head = dict(head.items() + extra_headers.items())",
"verify=False, headers=head, timeout=timeout, **other_properties) else: raise Exception(\"RestAppliance attempted to call an http request",
"Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else: raise Exception('first_time_setup",
"changePassword REST end point only works for the initial administrator password change. url",
"generation of a POST to do the network setup. self.set_time_server_and_locale(ntpserver) poll = True",
"True if operating_sys == 'windows' else False # Building the command. Ex: \"ping",
"= FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping {0}",
"with this string. secure (optional): boolean True requests data adding a header that",
"def get_time_locale_data(self): \"\"\"Request the networking information from the appliance. If the appliance returns",
"': ')))) return json_response def set_time_server_and_locale(self, ntpserver): \"\"\" If the time definition is",
"version is passed in, use that. Else use the default for the program",
"already_reset_session: raise Exception(\"There was an issue with the HTTP Call for task polling.",
"if appliance_domain_name not in network[\"hostname\"]: network[\"hostname\"] = network[\"hostname\"] + '.' + appliance_domain_name logging.info(\"Setting",
"to wait for appliance to stabilize\".format(post_eula_delay)) time.sleep(post_eula_delay) ra.change_administrator_password() ra.first_time_setup(ntpserver, use_static_ip=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None,",
"other than POST, PUT, or GET. request_type: {0}. url: {1}\".format(request_type, url)) try: safe_json_result",
"---------- none Return ------ mac address: string \"\"\" json_answer = self.get_networking_data() for network",
"_, _) = self.appliance_request(request_type='POST', url=logon_url, secure=False, payload=logon_payload) if not logon_success: raise Exception('change_administrator_password failed.",
"create a persistant session so that we can retry if the appliance goes",
"required by the appliance with authentication information. Return ------ _secure_header: dict. Dictionary containing",
"for i in data['results'][0]['msg']: for j in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) # Closing file vm_network_json_file.close()",
"passed in, use that. Else use the default for the program # Default",
"headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec) except requests.exceptions.RequestException as e: raise Exception(\"There was an issue connecting",
"for e in task_errors]) logging.debug(\"Percent Complete : {0}. State: {1}. Status: {2}.\".format(task_resource.get('percentComplete'), task_state,",
"host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping {0} seconds to wait for appliance to stabilize\".format(post_eula_delay)) time.sleep(post_eula_delay) ra.change_administrator_password()",
"#the warning for post-validation status. success = True elif r.status_code < 300: success",
"POST inside the generation of a POST to do the network setup. self.set_time_server_and_locale(ntpserver)",
"return a 202. success = False if r.status_code == 202: if not poll:",
"value. The call to the administrator password change is attempted. If the change",
"raise Exception(\"RestAppliance attempted to call an http request other than POST, PUT, or",
"address from the appliance. Use the first one found in applianceNetworks collection. If",
"for the task. if ova_ip: poll = False (success, response, rjson, polling_results) =",
"offline (e.g. first time setup) self.sess = requests.Session() self.retries = retries adap =",
"{'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\": success = True elif self.use_ip",
"request even if the host name is valid. \"\"\" operating_sys = platform.system().lower() for",
"page. \"\"\" url = '/rest/appliance/network-interfaces' (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True)",
"\"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\": \"DHCP\", \"ipv6Type\": ipv6_type, \"macAddress\": appliance_mac_address, \"hostname\": self.fqdn, \"device\": \"eth0\", \"ipv4NameServers\":",
"indent=4, separators=(',', ': '))) if 'Wait until the operation completes' in polling_results.get(\"task_status\"): raise",
"dictionary in this file. This needs to be moved to a more formal",
"Headers: {0}.\".format(head)) logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload))) polling_results = {} try: if request_type == \"POST\":",
"{0}.\".format(r.status_code)) logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result)) # 202 status codes indicate a task that is",
"failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return",
"from the appliance. Use the first one found in applianceNetworks collection. If the",
"e in task_errors: logging.error(e) task_status += \";\" + \";\".join([str(e) for e in task_errors])",
"{0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def get_mac(self): \"\"\"Request",
"for the header is undefined. No Session ID available. Status: {0}.'.format(r.status_code)) return self._secure_header",
"not defined') def get_networking_data(self): \"\"\"Request the networking information from the appliance. If the",
"': ')))) def accept_eula(self, service_access=\"yes\", tries=3, retry_interval=5): thistry = 1 while True: logging.info(\"accept_eula",
"for the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] = networks networking_data.pop('serverCertificate', None) payload = networking_data else: appliance_mac_address",
"url = '/rest/appliance/eula/status' (_, _, json_result, _) = self.appliance_request(request_type='GET', url=url, secure=False) if not",
"'None' or unspecified Return ------ return (success, r, safe_json_result, polling_results) A tuple with",
"location of the REST call. This method concatenates https:// and the fully qualified",
"value for request_type is utilized. Exceptions will also be raised if the appliance",
"indent=4, separators=(',', ': ')))) def accept_eula(self, service_access=\"yes\", tries=3, retry_interval=5): thistry = 1 while",
"#This is required sicne FTS will try to validate the hostname and if",
"passing in a value for override_version. Ideally, this computation should be moved to",
"HTTP Call for task polling. Exception message: {0}\".format(e)) # delete and recreate of",
"= task_resource.get('taskStatus', '') task_errors = task_resource.get('taskErrors', None) if task_errors: # in case of",
"with the task URL in the header: # '/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale' # Go",
"the lack of documented test cases, this seems to be the safest change",
"was successful\") def poll_for_task(self, calling_url, response): '''Helper method to appliance_request(). Status Response 202",
"appliance to get headers. Exception message: {0}\".format(e)) except Exception as e: raise Exception(\"There",
"Exception('get_time_locale_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ':",
"there are now at least two responses with the task URL in the",
"\"\"\"On initial communication with the appliance, the end user service agreement (EULA) must",
"networks.append(network) appliance_domain_name = self.fqdn.split(\".\", 1)[1] if appliance_domain_name not in network[\"hostname\"]: network[\"hostname\"] = network[\"hostname\"]",
"= False network['virtIpv4Addr'] = None networks.append(network) appliance_domain_name = self.fqdn.split(\".\", 1)[1] if appliance_domain_name not",
"is the later data model, where the time server and locale are set",
"set the networking. Instead, we will change to the new # address and",
"sicne FTS will try to validate the hostname and if it is not",
"to a default in the datastore. Parameters ---------- appliance_name : str fully qualified",
"logging.debug(\"Returned JSON: {0}\".format(r_treejson)) else: logging.debug(\"Exception during get call, response was not set\") logging.debug(\"Unable",
"ntpserver): \"\"\" If the time definition is not part of the network-interfaces JSON,",
"data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"PUT\": r = self.sess.put(full_url, verify=False, headers=head, data=json.dumps(payload),",
"session. else: already_reset_session = True self.sess.close() self.sess = requests.Session() adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://',",
"from a call to the network page. \"\"\" url = \"/rest/appliance/configuration/time-locale\" (success, resp,",
"appliance_mac_address = self.get_mac() ipv4_name_servers = self.get_ipv4_name_servers() # Only ipv6 with DHCP is supported,",
"concatenates https:// and the fully qualified domain name of the system with this",
"elif request_type == \"GET\": r = self.sess.get(full_url, verify=False, headers=head, timeout=timeout, **other_properties) elif request_type",
"required, see the function change_service_access() If the appliance returns an error status (anything",
"another REST process using POST inside the generation of a POST to do",
"the status_code was under 300 and the polling was successful. r: a response",
"it over and over again for the duration of its life. # Note,",
"dict(head.items() + extra_headers.items()) full_url = self.base_url + url logging.debug(\"Preparing HTTP {0} request.\".format(request_type)) logging.debug(\"Preparing",
"to indicate if an IP address is being passed instead of DNS hostname.",
"issue with the HTTP Call to get headers. Exception message: {0}\".format(e)) if r.status_code",
"may need version overrides at each REST call. if override_version: self.api_version = override_version",
"def set_time_server_and_locale(self, ntpserver): \"\"\" If the time definition is not part of the",
"HTTP Call. Exception message: {0}\".format(e)) def accept_eula_once(self, service_access=\"yes\"): \"\"\"On initial communication with the",
"self.base_url = \"https://\" + appliance_dhcp_ip_address else: self.base_url = \"https://\" + appliance_name self.use_ip =",
"use that. Else use the default for the program # Default to the",
"{\"userName\": initial_admin, \"oldPassword\": <PASSWORD>, \"newPassword\": <PASSWORD>} (success, resp, json_response, _) = self.appliance_request(request_type='POST', url=url,",
"lose connection # to the orginal location after the POST command to set",
"HTTP Call to get headers. Exception message: {0}\".format(e)) if r.status_code >= 300: raise",
"logging.debug(\"Unable to get the task tree for {0}\".format(full_rest_url)) return(task_state, task_status) except ValueError as",
"Tracker mechanism. I have brought this to the attention # of the atlas",
"self.sess.post(self.base_url + url, verify=False, headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec) except requests.exceptions.RequestException as e: raise Exception(\"There",
"administrator's password has to be changed from the default value. The call to",
"is: {0}'.format(mac_address)) return mac_address raise Exception('MAC Address is not defined') def get_ipv4_name_servers(self): \"\"\"Request",
"url=url, secure=True) if not success: raise Exception('get_networking_data call failed. Status: {0}. JSON Response:",
"use the fqdn to make sure the # networking setup task completes successfully.",
"location. Parameters ---------- none \"\"\" # The changePassword REST end point only works",
"raise Exception('get_networking_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',',",
"returning a object of type TaskResourceV2, this end point returns Void. # From",
"sec_between_polling = 10 class FirstTimeSetUp(object): def __init__(self, appliance_name, use_ip=False, override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0,",
"values of 100, 199, and 200. retries (Optional): int Number of retries to",
"False network['virtIpv4Addr'] = None networks.append(network) appliance_domain_name = self.fqdn.split(\".\", 1)[1] if appliance_domain_name not in",
"rest actions and then use the fqdn to make sure the # networking",
"+ self.fqdn (task_state, task_status) = self.poll_for_task(url, response) polling_results = {'task_state': task_state, 'task_status': task_status}",
"_) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if save_success: logging.info('EULA Accepted.') else: raise Exception('accept_eula",
"Number of retries to do in HTTP session. appliance_dhcp_ip_address : str appliance dhcp",
"True: logging.info(\"accept_eula try {}\".format(thistry)) try: self.accept_eula_once(service_access=service_access) return except Exception as e: logging.exception(e) if",
"first one found in applianceNetworks collection. If the appliance returns an error status",
"a JSON value from the response. Status: {0}.'.format(r.status_code)) except: raise Exception('Failure to access",
"network['ipv4Type'] = \"STATIC\" network[\"searchDomains\"] = None # this is what UI does so",
"None \"\"\" self.fqdn = appliance_name if appliance_dhcp_ip_address: self.base_url = \"https://\" + appliance_dhcp_ip_address else:",
"collection. If the appliance returns an error status (anything outside of the 100",
"for {0} is:\".format(full_rest_url)) logging.debug(\"Returned JSON: {0}\".format(r_treejson)) else: logging.debug(\"Exception during get call, response was",
"we will change to the new # address and then poll for the",
"= self.base_url + url task_state = 'Running' start_time = time.time() try: logging.debug(\"Starting polling",
"url=url, secure=False) if not json_result: # if False, eula acceptance has already occurred.",
"or 200 range), an error is raised. \"\"\" url = '/rest/appliance/network-interfaces' if ova_ip:",
"Parameters ---------- appliance_name : str fully qualified name of the appliance use_ip :",
"Exception('Task Polling did not respond within {0} seconds. Time out and exit. Originating",
"not set\") logging.debug(\"Unable to get the task tree for {0}\".format(full_rest_url)) return(task_state, task_status) except",
"'10' ntpserver = \"10.10.10.10\" ipv6address = readIPV6FromFile() pingableipv6 = ping(ipv6address) ra = FirstTimeSetUp(\"appliance_name\",",
"of the service access. If a change to the service access is required,",
"completes' in polling_results.get(\"task_status\"): raise Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"),",
"not success: raise Exception('get_networking_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True,",
"def poll_for_task(self, calling_url, response): '''Helper method to appliance_request(). Status Response 202 indicates an",
"list for i in data['results'][0]['msg']: for j in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) # Closing file",
"is unpacked and added to Request. For example: other_properties={'stream': True} poll : boolean",
"r_treejson.get('resource') task_state = task_resource.get('taskState') task_status = task_resource.get('taskStatus', '') task_errors = task_resource.get('taskErrors', None) if",
"task that is pollable. The calling function may not know that this will",
"str \"yes\" will accept service access \"no\" will not allow service access empty",
"shell_needed = True if operating_sys == 'windows' else False # Building the command.",
"recreate of the session if it loses connection. Changes in IP address, FQDN,",
"def readIPV6FromFile(self): ipv6address = [] vm_network_json_file = open('vm_network.json',) data = json.load(vm_network_json_file) # Iterating",
"Instead, we will change to the new # address and then poll for",
"address: string \"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []): mac_address =",
"mechanism. I have brought this to the attention # of the atlas team.",
"raised. The administrator data is pulled from the dictionary in this file. This",
"str(safe_json_result))} return (success, r, safe_json_result, polling_results) except requests.exceptions.RequestException as e: raise Exception(\"There was",
"be changed from the default value. The call to the administrator password change",
"for override_version. Ideally, this computation should be moved to a default in the",
"system with this string. secure (optional): boolean True requests data adding a header",
"be used to connect to the appliance if not None \"\"\" self.fqdn =",
"[] vm_network_json_file = open('vm_network.json',) data = json.load(vm_network_json_file) # Iterating through the json list",
"setup. self.set_time_server_and_locale(ntpserver) poll = True # Do not poll for the task if",
"If a ova_ip is passed in then we will lose connection # to",
"goes offline (e.g. first time setup) self.sess = requests.Session() self.retries = retries adap",
"= '/rest/users/changePassword' payload = {\"userName\": initial_admin, \"oldPassword\": <PASSWORD>, \"newPassword\": <PASSWORD>} (success, resp, json_response,",
"Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) logging.warning('Administrator password has already been",
"= override_version else: self.api_version = 120 logging.info(\"The API Version utilized is {0}.\".format(self.api_version)) self._header",
"service_access} (save_success, save_resp, save_json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if save_success: logging.info('EULA",
"to get headers. Exception message: {0}\".format(e)) if r.status_code >= 300: raise Exception('Failure to",
"to call HTTP requests. An exception will be raised if an unknown value",
"{0}\".format(e)) except Exception as e: raise Exception(\"There was an issue with the HTTP",
"json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []): mac_address = network.get('macAddress') if mac_address:",
"from the dictionary in this file. This needs to be moved to a",
": str fully qualified name of the appliance use_ip : bool Flag to",
"has to be changed from the default value. The call to the administrator",
"\"PUT\": r = self.sess.put(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"GET\":",
"network in networking_data['applianceNetworks']: if network[\"ipv4Type\"] == \"DHCP\": network['ipv4Type'] = \"STATIC\" network['ipv6Type'] = \"UNCONFIGURE\"",
"task_resource.get('taskErrors', None) if task_errors: # in case of errors place them in log",
"as DHCP. The appliance queries itself to define its macAddress. If the api_version",
"payload, but # we need to know if the network definition has the",
"independent REST endpoint. :param ntpserver: IP address of the ntpserver. :return: :raises: Exception,",
"be raised by method if it fails. time_locale_settings[\"dateTime\"] = None # our time",
"\"/rest/appliance/configuration/time-locale\" # Query for current time-locale setting. time_locale_settings = self.get_time_locale_data() # Exception will",
"end point only works for the initial administrator password change. url = '/rest/users/changePassword'",
"that was called in appliance_request. response : a response object from a Requests",
"} # Not clear why this conditions fails to query the network interface",
"Acceptance with enable service access={0}'.format(service_access)) url = '/rest/appliance/eula/save' payload = {\"supportAccess\": service_access} (save_success,",
"== \"GET\": r = self.sess.get(full_url, verify=False, headers=head, timeout=timeout, **other_properties) elif request_type == \"DELETE\":",
"True, \"activeNode\": 1 } ], } # Not clear why this conditions fails",
"_) = self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_time_locale_data call failed. Status:",
"Password is {0}'.format(<PASSWORD>)) else: raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response,",
"for REST calls. The version can be overridden by passing in a value",
"for network in networking_data['applianceNetworks']: if network[\"ipv4Type\"] == \"DHCP\": network['ipv4Type'] = \"STATIC\" network['ipv6Type'] =",
"error status (anything outside of the 100 or 200 range), an error is",
"Python object payload for POST or PUT calls, to be serialized into JSON.",
"\"\"\"Request the list of dns ipv4 name servers. Use the first one found",
"that the status_code was under 300 and the polling was successful. r: a",
"': ')))) def get_mac(self): \"\"\"Request the MAC address from the appliance. Use the",
"the 100 or 200 range), an error is raised. Parameters ---------- none Return",
"was an issue with the HTTP Call for task polling. Exception message: {0}\".format(e))",
"= self.fqdn.split(\".\", 1)[1] if appliance_domain_name not in network[\"hostname\"]: network[\"hostname\"] = network[\"hostname\"] + '.'",
"the # networking setup task completes successfully. This needs to be done for",
"= {} logging.debug(\"Returned. Status code: {0}.\".format(r.status_code)) logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result)) # 202 status codes",
"appliance_request(self, request_type, url, secure=True, payload=None, other_properties={}, extra_headers={}, poll=True, timeout=None): \"\"\"Helper method to call",
"Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def set_time_server_and_locale(self, ntpserver):",
"the orginal location after the POST command to set the networking. Instead, we",
"file vm_network_json_file.close() return ipv6address def ping(hosts): \"\"\" Returns True if host (str) responds",
"'time-locale setting failure. Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP",
"Exception as e: logging.exception(\"FTS get failed: \" + str(e)) if already_reset_session: raise Exception(\"There",
"operating system name import subprocess # For executing a shell command rest_call_timeout_sec =",
"{2}.\".format(task_resource.get('percentComplete'), task_state, task_status)) logging.debug(\"The task tree for {0} is:\".format(full_rest_url)) logging.debug(\"Returned JSON: {0}\".format(r_treejson)) else:",
"Return ------ tuple containing: task_state: str. A short summary of the execution/completion status",
"within {0} seconds. Time out and exit. Originating request on URL: {1}'.format(polling_call_timeout_sec, calling_url))",
"be overridden by passing in a value for override_version. Ideally, this computation should",
"REST call. This method concatenates https:// and the fully qualified domain name of",
"old_network: payload[\"time\"] = deepcopy(old_network[\"time\"]) # This is the later data model, where the",
"Status: {0}.'.format(r.status_code)) return self._secure_header except ValueError as e: raise Exception('Failure to get a",
"rest_call_timeout_sec if not secure: head = self._header else: head = self.get_secure_headers() head =",
"300: success = True else: polling_results = {'task_state': safe_json_result.get('errorCode', 'Error'), 'task_status': safe_json_result.get('details', str(safe_json_result))}",
"(determined by program name) can be overridden. Currently only accepting values of 100,",
"appliance. If the appliance returns an error status (anything outside of the 100",
"10 * 60 sec_between_polling = 10 class FirstTimeSetUp(object): def __init__(self, appliance_name, use_ip=False, override_version=None,",
"is pulled from the dictionary in this file. This needs to be moved",
"Poll until the task is complete or error. Adds to the set of",
"= {} def get_secure_headers(self): \"\"\"Helper method to appliance_request(). Gives header information required by",
"poll = False (success, response, rjson, polling_results) = self.appliance_request(request_type='POST', url=url, secure=True, payload=payload, poll=poll)",
"failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First time setup was",
"message: {0}\".format(e)) except Exception as e: raise Exception(\"There was an issue with the",
"case of errors place them in log output and append to status message",
"to RestAppliance. We compute the correct API-Version for REST calls. The version can",
"is passed in, use that. Else use the default for the program #",
"if url is None: url = response.json().get('uri') if url is None: raise Exception('Could",
"the dictionary in this file. This needs to be moved to a more",
"URL: {0}. Exception: {1}'.format(calling_url, e)) def first_time_setup(self, ntpserver, use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None,",
"to define its macAddress. If the api_version is above version 100, this will",
"this will set a DNS Server IP address and set the overrideIpv4DhcpDnsServers value",
"is raised. Parameters ---------- none Return ------ list of ipv4 name servers: list",
"operation completes' in ntp_polling_results.get(\"task_status\"): raise Exception( 'time-locale setting failed. Polling State: {0}. Polling",
"network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] = '' network[\"app1Ipv4Addr\"] = ova_ip network[\"app2Ipv4Addr\"] = '' else:",
"appliance if not None \"\"\" self.fqdn = appliance_name if appliance_dhcp_ip_address: self.base_url = \"https://\"",
"Ex: \"ping -c 1 google.com\" ping_command = ['ping', param, '1', i] ping_output =",
"safe_json_result, polling_results) A tuple with these values: success: bool. A True/False value. True",
"app1Ipv4Addr != virtIpv4Addr\") network[\"ipv6Type\"] = \"UNCONFIGURE\" payload = networking_data elif use_static_ip: networking_data =",
"task_status. Both are populated whenever the call requires task polling. \"\"\" if timeout",
"_) = self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_networking_data call failed. Status:",
"---------- none Return ------ a response object from a call to the network",
"successful. r: a response object from a Requests call. safe_json_results: the JSON returned",
"from the response. Status: {0}. JSON: {1}'.format(r.status_code, r.json())) def appliance_request(self, request_type, url, secure=True,",
"is passed in then we will lose connection # to the orginal location",
"ova_ip: poll = False (success, response, rjson, polling_results) = self.appliance_request(request_type='POST', url=url, secure=True, payload=payload,",
"a ova_ip is passed in then we will lose connection # to the",
"The version can be overridden by passing in a value for override_version. Ideally,",
"call. if override_version: self.api_version = override_version else: self.api_version = 120 logging.info(\"The API Version",
"JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def set_time_server_and_locale(self,",
"network in json_answer.get('applianceNetworks', []): ipv4_name_servers = network.get('ipv4NameServers') if ipv4_name_servers: logging.info('IPv4 Name servers: {0}'.format(ipv4_name_servers))",
"logging.info('IPv4 Name servers: {0}'.format(ipv4_name_servers)) return ipv4_name_servers raise Exception('IPv4 Name server is not defined')",
"if ova_ip and success: self.base_url = \"https://\" + self.fqdn (task_state, task_status) = self.poll_for_task(url,",
"Use the first one found in applianceNetworks collection. If the appliance returns an",
"\"STATIC\" network['ipv6Type'] = \"UNCONFIGURE\" networks.append(network) if use_i3s_fts: network['ipv6Type'] = \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] = False",
"logging.exception(\"FTS get failed: \" + str(e)) if already_reset_session: raise Exception(\"There was an issue",
"- needed for failover setups timeout: None or integer Defaults to rest_call_timeout_sec if",
"raise Exception('Error in polling for the task. Originating request on URL: {0}. Exception:",
"ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode if success == 0: return (str(i)+str('%ens160')) if",
"else: raise Exception( 'time-locale setting failure. Polling State: {0}. Polling Status: {1}. '.format(",
"accurate administrator password. If the administrator login is not successful, an error is",
"we need to know if the network definition has the \"time\" dictionary defined",
"in the datastore. Parameters ---------- appliance_name : str fully qualified name of the",
"is above version 100, this will set a DNS Server IP address and",
"appliance as DHCP. The appliance queries itself to define its macAddress. If the",
"200 range), an error is raised. \"\"\" url = '/rest/appliance/network-interfaces' if ova_ip: networking_data",
"duration of its life. # Note, the header is only good for that",
"use_static_ip=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Constructor method to RestAppliance. We compute the correct",
"= network[\"hostname\"] + '.' + appliance_domain_name logging.info(\"Setting fqdn for the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] =",
"can make use lose the session. else: already_reset_session = True self.sess.close() self.sess =",
"network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] = '' network[\"app1Ipv4Addr\"] = ova_ip network[\"app2Ipv4Addr\"] = '' else: raise Exception(\"Impossible",
"program. # Eventually we may need version overrides at each REST call. if",
"of the EULA nor the status of the service access. If a change",
"depends on get_secure_headers(). Parameters ---------- request_type: str accepted values are: \"POST\", \"PUT\", \"GET\",",
"the \"time\" dictionary defined in it; if it does, copy into # place",
"then poll for the task. if ova_ip: poll = False (success, response, rjson,",
"'/rest/appliance/eula/save' payload = {\"supportAccess\": service_access} (save_success, save_resp, save_json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False,",
"setting failed. Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else: raise",
"requests import json import logging import time from copy import deepcopy import platform",
"**other_properties) elif request_type == \"DELETE\": r = self.sess.delete(full_url, verify=False, headers=head, timeout=timeout, **other_properties) else:",
"logging.info(\"accept_eula try {}\".format(thistry)) try: self.accept_eula_once(service_access=service_access) return except Exception as e: logging.exception(e) if thistry",
"Parameters ---------- calling_url : string The URL that was called in appliance_request. response",
"{1}'.format(calling_url, e)) def first_time_setup(self, ntpserver, use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Creates",
"else: success = False if not success: logging.error(json.dumps(rjson, sort_keys=True, indent=4, separators=(',', ': ')))",
"populated whenever the call requires task polling. \"\"\" if timeout is None: timeout",
"values, task_state and task_status. Both are populated whenever the call requires task polling.",
"\"10.10.10.10\" ipv6address = readIPV6FromFile() pingableipv6 = ping(ipv6address) ra = FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False, appliance_dhcp_ip_address=None,",
"URL: {1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling) r_tree = None try: logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree =",
"+= 1 def change_administrator_password(self): \"\"\"On initial logon, the administrator's password has to be",
"networks.append(network) if use_i3s_fts: network['ipv6Type'] = \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] = False network['virtIpv4Addr'] = None networks.append(network)",
"requests.exceptions.RequestException as e: raise Exception(\"There was an issue connecting to the appliance to",
"_secure_header: dict. Dictionary containing X-API-Verions, Content-Type, and Auth. The Auth parameter value is",
"(ntp_success, _, ntp_rjson, ntp_polling_results) = self.appliance_request(request_type='POST', url=time_locale_url, secure=True, payload=time_locale_settings) if not ntp_success: logging.error(json.dumps(ntp_rjson,",
"timeout=timeout, **other_properties) elif request_type == \"GET\": r = self.sess.get(full_url, verify=False, headers=head, timeout=timeout, **other_properties)",
"adding a header that includes authentiation information. False requests data without authentication information",
"respond within {0} seconds. Time out and exit. Originating request on URL: {1}'.format(polling_call_timeout_sec,",
"subsequent rest actions and then use the fqdn to make sure the #",
"next reboot. if self._secure_header: return self._secure_header payload = {\"userName\": \"Administrator\", \"password\": \"<PASSWORD>\"} url",
"rjson, polling_results) = self.appliance_request(request_type='POST', url=url, secure=True, payload=payload, poll=poll) # Reset the base url",
"on get_secure_headers(). Parameters ---------- request_type: str accepted values are: \"POST\", \"PUT\", \"GET\", \"DELETE\"",
"str accepted values are: \"POST\", \"PUT\", \"GET\", \"DELETE\" Any other value will raise",
"the function change_service_access() If the appliance returns an error status (anything outside of",
"complete or error. Adds to the set of parameters that appliance_request() returns. Parameters",
"# delete and recreate of the session if it loses connection. Changes in",
"error is raised. Parameters ---------- none Return ------ mac address: string \"\"\" json_answer",
"serialized into JSON. other_properties (optional): dict A dictionary of extra properties that we",
"documentation, this is not consistant with the Task Tracker mechanism. I have brought",
"networking_data['applianceNetworks'][0] network[\"hostname\"] = self.fqdn network[\"domainName\"] = self.fqdn.split(\".\", 1)[1] network['ipv4Type'] = \"STATIC\" network[\"searchDomains\"] =",
"to the appliance to get headers. Exception message: {0}\".format(e)) except Exception as e:",
"first_time_setup(self, ntpserver, use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Creates networking for the",
"fully qualified name of the appliance use_ip : bool Flag to indicate if",
"timeout: None or integer Defaults to rest_call_timeout_sec if 'None' or unspecified Return ------",
"mac_address: logging.info('MAC Address is: {0}'.format(mac_address)) return mac_address raise Exception('MAC Address is not defined')",
"e in task_errors]) logging.debug(\"Percent Complete : {0}. State: {1}. Status: {2}.\".format(task_resource.get('percentComplete'), task_state, task_status))",
"can give to the Python Request module. The dictionary is unpacked and added",
"log output and append to status message for e in task_errors: logging.error(e) task_status",
"appliance use_ip : bool Flag to indicate if an IP address is being",
"request_type: {0}. url: {1}\".format(request_type, url)) try: safe_json_result = r.json() except: safe_json_result = {}",
"a special case. Rather than network-interfaces returning a object of type TaskResourceV2, this",
"Status: {2}.\".format(task_resource.get('percentComplete'), task_state, task_status)) logging.debug(\"The task tree for {0} is:\".format(full_rest_url)) logging.debug(\"Returned JSON: {0}\".format(r_treejson))",
"then we attempt to login with the administrator password. If successful, we log",
"raise Exception( 'time-locale setting failure. Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"),",
"that we can give to the Python Request module. The dictionary is unpacked",
"are set via their own API # This will embed another REST process",
"_) = self.appliance_request(request_type='GET', url=url, secure=False) if not json_result: # if False, eula acceptance",
"success: raise Exception('get_time_locale_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4,",
"set via an independent REST endpoint. :param ntpserver: IP address of the ntpserver.",
"networking. if ova_ip and success: self.base_url = \"https://\" + self.fqdn (task_state, task_status) =",
"in old_network: payload[\"time\"] = deepcopy(old_network[\"time\"]) # This is the later data model, where",
"logging.debug(\"Exception during get call, response was not set\") logging.debug(\"Unable to get the task",
"[]): mac_address = network.get('macAddress') if mac_address: logging.info('MAC Address is: {0}'.format(mac_address)) return mac_address raise",
"if the appliance cannot be contacted. If secure=True, this function depends on get_secure_headers().",
"applianceNetworks collection. If the appliance returns an error status (anything outside of the",
"\"\"\"Creates networking for the appliance. Configures the appliance as DHCP. The appliance queries",
"polling was successful. r: a response object from a Requests call. safe_json_results: the",
"self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_time_locale_data call failed. Status: {0}. JSON",
"'/rest/appliance/network-interfaces' if ova_ip: networking_data = self.get_networking_data() network = networking_data['applianceNetworks'][0] network[\"hostname\"] = self.fqdn network[\"domainName\"]",
"False # Building the command. Ex: \"ping -c 1 google.com\" ping_command = ['ping',",
"we may need version overrides at each REST call. if override_version: self.api_version =",
"thistry += 1 def change_administrator_password(self): \"\"\"On initial logon, the administrator's password has to",
"= self.get_mac() ipv4_name_servers = self.get_ipv4_name_servers() # Only ipv6 with DHCP is supported, will",
"completes successfully. This needs to be done for OVA's that are deployed as",
"Void. # From my reading of the documentation, this is not consistant with",
"in ['Running', 'New', 'Pending', 'Starting']: if time.time() >= start_time + polling_call_timeout_sec: raise Exception('Task",
"setting failure. Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server",
"dict. Dictionary containing X-API-Verions, Content-Type, and Auth. The Auth parameter value is a",
"password. If the administrator login is not successful, an error is raised. The",
"# The changePassword REST end point only works for the initial administrator password",
"= \"/rest/appliance/configuration/time-locale\" (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not success:",
"parameters that appliance_request() returns. Parameters ---------- calling_url : string The URL that was",
"the ip address will change after setting up the networking. if ova_ip and",
"and task_state == \"Warning\": #This is required sicne FTS will try to validate",
"we log a message and the accurate administrator password. If the administrator login",
"in the JSON. Poor consistency in # implementations and inconsistent with REST principles.",
"a shell command rest_call_timeout_sec = 60 max_retries_in_session = 50 polling_call_timeout_sec = 10 *",
"my reading of the documentation, this is not consistant with the Task Tracker",
"networking for the appliance. Configures the appliance as DHCP. The appliance queries itself",
"as static since the ip address will change after setting up the networking.",
"import deepcopy import platform # For getting the operating system name import subprocess",
"\"confOneNode\": True, \"activeNode\": 1 } ], } # Not clear why this conditions",
"{\"userName\": admin_user, \"password\": <PASSWORD>} (logon_success, _, _, _) = self.appliance_request(request_type='POST', url=logon_url, secure=False, payload=logon_payload)",
"to poll. Originating request on URL: {0}.'.format(calling_url)) full_rest_url = self.base_url + url task_state",
"def change_administrator_password(self): \"\"\"On initial logon, the administrator's password has to be changed from",
"REST principles. url = response.headers.get('location') if url is None: url = response.json().get('uri') if",
"polling_results) except requests.exceptions.RequestException as e: raise Exception(\"There was an issue connecting to the",
"{\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\": \"DHCP\", \"ipv6Type\": ipv6_type, \"macAddress\": appliance_mac_address, \"hostname\": self.fqdn, \"device\": \"eth0\",",
"per program. # Eventually we may need version overrides at each REST call.",
"successful, an error is raised. The administrator data is pulled from the dictionary",
"error is raised. Parameters ---------- none Return ------ list of ipv4 name servers:",
"save_success: logging.info('EULA Accepted.') else: raise Exception('accept_eula failed. Status: {0}. JSON Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response,",
"will be used to connect to the appliance if not None \"\"\" self.fqdn",
"networking_data = self.get_networking_data() network = networking_data['applianceNetworks'][0] network[\"hostname\"] = self.fqdn network[\"domainName\"] = self.fqdn.split(\".\", 1)[1]",
"------ return (success, r, safe_json_result, polling_results) A tuple with these values: success: bool.",
"safe_json_result = r.json() except: safe_json_result = {} logging.debug(\"Returned. Status code: {0}.\".format(r.status_code)) logging.debug(\"Returned. JSON:",
"access empty value will default to \"yes\" \"\"\" url = '/rest/appliance/eula/status' (_, _,",
"below version 100, it does not set DNS. If the appliance returns an",
"an error is raised. Parameters ---------- none Return ------ list of ipv4 name",
"in hosts: param = '-n' if operating_sys=='windows' else '-c' shell_needed = True if",
"= {'X-API-Version': '{}'.format(self.api_version), 'Content-Type': 'application/json'} self._secure_header = {} def get_secure_headers(self): \"\"\"Helper method to",
"reboot. if self._secure_header: return self._secure_header payload = {\"userName\": \"Administrator\", \"password\": \"<PASSWORD>\"} url =",
"# Note, the header is only good for that user (administrator), 24 hours,",
"or error. Adds to the set of parameters that appliance_request() returns. Parameters ----------",
"will return a 202. success = False if r.status_code == 202: if not",
"vm_network_json_file.close() return ipv6address def ping(hosts): \"\"\" Returns True if host (str) responds to",
"short summary of the execution/completion status task_status: str. State of the task. For",
"'))) if 'Wait until the operation completes' in ntp_polling_results.get(\"task_status\"): raise Exception( 'time-locale setting",
"except ValueError as e: raise Exception('Error getting the JSON results from the task.",
"raise Exception('accept_eula failed. Status: {0}. JSON Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True, indent=4, separators=(',', ':",
"implements all the requirements that we need. Defined per program. # Eventually we",
"request_type: str accepted values are: \"POST\", \"PUT\", \"GET\", \"DELETE\" Any other value will",
"IP address of the ntpserver. :return: :raises: Exception, Exception \"\"\" time_locale_url = \"/rest/appliance/configuration/time-locale\"",
"task completes successfully. This needs to be done for OVA's that are deployed",
"None: raise Exception('Auth token for the header is undefined. No Session ID available.",
"Originating request on URL: {0}.'.format(calling_url)) full_rest_url = self.base_url + url task_state = 'Running'",
"100, 199, and 200. retries (Optional): int Number of retries to do in",
"an independent REST endpoint. :param ntpserver: IP address of the ntpserver. :return: :raises:",
"url=time_locale_url, secure=True, payload=time_locale_settings) if not ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4, separators=(',', ': '))) if",
"poll : boolean If false, polling tasks will return immiedtaly - needed for",
"Call to get headers. Exception message: {0}\".format(e)) if r.status_code >= 300: raise Exception('Failure",
"else: self.base_url = \"https://\" + appliance_name self.use_ip = use_ip # create a persistant",
"\"UNCONFIGURE\" payload = networking_data elif use_static_ip: networking_data = self.get_networking_data() networks = [] for",
"= False if r.status_code == 202: if not poll: return (True, r, safe_json_result,",
"self.appliance_request(request_type='POST', url=time_locale_url, secure=True, payload=time_locale_settings) if not ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4, separators=(',', ': ')))",
"r = self.sess.post(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"PUT\": r",
"task polling. \"\"\" if timeout is None: timeout = rest_call_timeout_sec if not secure:",
"will change to the new # address and then poll for the task.",
"self._header = {'X-API-Version': '{}'.format(self.api_version), 'Content-Type': 'application/json'} self._secure_header = {} def get_secure_headers(self): \"\"\"Helper method",
"True network[\"overrideIpv4DhcpDnsServers\"] = False if network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] = '' network[\"app1Ipv4Addr\"] =",
"poll=True, timeout=None): \"\"\"Helper method to call HTTP requests. An exception will be raised",
"get_secure_headers(self): \"\"\"Helper method to appliance_request(). Gives header information required by the appliance with",
"copy import deepcopy import platform # For getting the operating system name import",
"life. # Note, the header is only good for that user (administrator), 24",
"will #the warning for post-validation status. success = True elif r.status_code < 300:",
"not read the task to poll. Originating request on URL: {0}.'.format(calling_url)) full_rest_url =",
"'''Helper method to appliance_request(). Status Response 202 indicates an asynchronous REST call. Poll",
"then we will lose connection # to the orginal location after the POST",
"True requests data adding a header that includes authentiation information. False requests data",
"str url location of the REST call. This method concatenates https:// and the",
"= self.sess.post(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"PUT\": r =",
"appliance, the end user service agreement (EULA) must be accepted. This only needs",
"= True # Do not poll for the task if a ova_ip is",
"self.get_networking_data() network = networking_data['applianceNetworks'][0] network[\"hostname\"] = self.fqdn network[\"domainName\"] = self.fqdn.split(\".\", 1)[1] network['ipv4Type'] =",
"address will change after setting up the networking. if ova_ip and success: self.base_url",
"properties that we can give to the Python Request module. The dictionary is",
"\"https://\" + appliance_dhcp_ip_address else: self.base_url = \"https://\" + appliance_name self.use_ip = use_ip #",
"from a call to the network page. \"\"\" url = '/rest/appliance/network-interfaces' (success, resp,",
"the json list for i in data['results'][0]['msg']: for j in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) #",
"was an issue with the HTTP Call. Exception message: {0}\".format(e)) def accept_eula_once(self, service_access=\"yes\"):",
"to the attention # of the atlas team. # # there are now",
"for the duration of its life. # Note, the header is only good",
"False while task_state in ['Running', 'New', 'Pending', 'Starting']: if time.time() >= start_time +",
"to occur once. Additional calls will not change the status of the EULA",
"to query the network interface to get the base for the payload, but",
"response object from a call to the network page. \"\"\" url = '/rest/appliance/network-interfaces'",
"the the fqdn for any subsequent rest actions and then use the fqdn",
"safe_json = r.json() self._secure_header = self._header.copy() self._secure_header['Auth'] = safe_json.get('sessionID') if self._secure_header['Auth'] is None:",
"def get_mac(self): \"\"\"Request the MAC address from the appliance. Use the first one",
"setting. time_locale_settings = self.get_time_locale_data() # Exception will be raised by method if it",
"payload = networking_data else: appliance_mac_address = self.get_mac() ipv4_name_servers = self.get_ipv4_name_servers() # Only ipv6",
"ova_ip=None, host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping {0} seconds to wait for appliance to stabilize\".format(post_eula_delay)) time.sleep(post_eula_delay)",
"json_response def set_time_server_and_locale(self, ntpserver): \"\"\" If the time definition is not part of",
"address is being passed instead of DNS hostname. override_version (Optional): int The default",
"in it; if it does, copy into # place for the test below",
"overrideIpv4DhcpDnsServers value to False. \"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\": False If the api_version is below",
"True if host (str) responds to a ping request. Remember that a host",
"Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server setting was successful\") def poll_for_task(self,",
"None: raise Exception('Could not read the task to poll. Originating request on URL:",
"is valid. \"\"\" operating_sys = platform.system().lower() for i in hosts: param = '-n'",
"use the default for the program # Default to the minimal version number",
"= self.poll_for_task(url, response) polling_results = {'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\":",
"with the appliance, the end user service agreement (EULA) must be accepted. This",
"self.api_version = 120 logging.info(\"The API Version utilized is {0}.\".format(self.api_version)) self._header = {'X-API-Version': '{}'.format(self.api_version),",
"in the header: # '/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale' # Go to checking for response",
"not json_result: # if False, eula acceptance has already occurred. logging.warning('EULA does not",
"inside the generation of a POST to do the network setup. self.set_time_server_and_locale(ntpserver) poll",
"= ping_output.returncode if success == 0: return (str(i)+str('%ens160')) if __name__ == '__main__': post_eula_delay",
"'.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First time setup was successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True)) def readIPV6FromFile(self): ipv6address",
"{\"userName\": \"Administrator\", \"password\": \"<PASSWORD>\"} url = '/rest/login-sessions' try: r = self.sess.post(self.base_url + url,",
"later. if ipv6_type != \"DHCP\": ipv6_type = \"UNCONFIGURE\" payload = {\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\":",
"ping(ipv6address) ra = FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None) ra.accept_eula(\"yes\")",
"it is not valid hostname then it will #the warning for post-validation status.",
"JSON: {0}.\".format(safe_json_result)) # 202 status codes indicate a task that is pollable. The",
"the later data model, where the time server and locale are set via",
"time-locale setting. time_locale_settings = self.get_time_locale_data() # Exception will be raised by method if",
"\"\"\" Returns True if host (str) responds to a ping request. Remember that",
"if success: logging.info('Administrator password change was accepted.') elif resp.status_code == 400: logon_url =",
"if it does, copy into # place for the test below this set",
"the fully qualified domain name of the system with this string. secure (optional):",
"and set the overrideIpv4DhcpDnsServers value to False. \"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\": False If the",
"== '__main__': post_eula_delay = '10' ntpserver = \"10.10.10.10\" ipv6address = readIPV6FromFile() pingableipv6 =",
"'.' + appliance_domain_name logging.info(\"Setting fqdn for the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] = networks networking_data.pop('serverCertificate', None)",
"range), an error is raised. No authentication on the appliance is required. Parameters",
"logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until the operation completes' in",
"'Running' start_time = time.time() try: logging.debug(\"Starting polling the rest task {0}.\".format(url)) already_reset_session =",
"time setup was successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True)) def readIPV6FromFile(self): ipv6address = [] vm_network_json_file",
"except Exception as e: logging.exception(e) if thistry >= tries: raise e time.sleep(retry_interval) thistry",
"\"time\" dictionary defined in it; if it does, copy into # place for",
"values are: \"POST\", \"PUT\", \"GET\", \"DELETE\" Any other value will raise an error.",
"network.get('macAddress') if mac_address: logging.info('MAC Address is: {0}'.format(mac_address)) return mac_address raise Exception('MAC Address is",
"\"yes\" will accept service access \"no\" will not allow service access empty value",
"secure connection. Status {0}.'.format(r.status_code)) try: safe_json = r.json() self._secure_header = self._header.copy() self._secure_header['Auth'] =",
"string The URL that was called in appliance_request. response : a response object",
"extra_headers={}, poll=True, timeout=None): \"\"\"Helper method to call HTTP requests. An exception will be",
"URL: {0}.\".format(full_url)) logging.debug(\"Preparing Headers: {0}.\".format(head)) logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload))) polling_results = {} try: if",
"value defaults in True payload (optional): dict Python object payload for POST or",
"the list of dns ipv4 name servers. Use the first one found in",
"needed for failover setups timeout: None or integer Defaults to rest_call_timeout_sec if 'None'",
"separators=(',', ': ')))) def get_mac(self): \"\"\"Request the MAC address from the appliance. Use",
"= networks networking_data.pop('serverCertificate', None) payload = networking_data else: appliance_mac_address = self.get_mac() ipv4_name_servers =",
"elif resp.status_code == 400: logon_url = '/rest/login-sessions' logon_payload = {\"userName\": admin_user, \"password\": <PASSWORD>}",
"valid. \"\"\" operating_sys = platform.system().lower() for i in hosts: param = '-n' if",
"indent=4, separators=(',', ': ')))) return json_response def set_time_server_and_locale(self, ntpserver): \"\"\" If the time",
"poll for the task. if ova_ip: poll = False (success, response, rjson, polling_results)",
"+ appliance_domain_name logging.info(\"Setting fqdn for the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] = networks networking_data.pop('serverCertificate', None) payload",
"int Number of retries to do in HTTP session. appliance_dhcp_ip_address : str appliance",
"other value will raise an error. url: str url location of the REST",
"Exception message: {0}\".format(e)) except Exception as e: raise Exception(\"There was an issue with",
"so that we can retry if the appliance goes offline (e.g. first time",
"= self.base_url + url logging.debug(\"Preparing HTTP {0} request.\".format(request_type)) logging.debug(\"Preparing URL: {0}.\".format(full_url)) logging.debug(\"Preparing Headers:",
"URL: {0}.'.format(calling_url)) full_rest_url = self.base_url + url task_state = 'Running' start_time = time.time()",
"if ova_ip: networking_data = self.get_networking_data() network = networking_data['applianceNetworks'][0] network[\"hostname\"] = self.fqdn network[\"domainName\"] =",
"Auth. The Auth parameter value is a sessionID. \"\"\" # Once _secure_header is",
"# Closing file vm_network_json_file.close() return ipv6address def ping(hosts): \"\"\" Returns True if host",
"response): '''Helper method to appliance_request(). Status Response 202 indicates an asynchronous REST call.",
"locale are set via their own API # This will embed another REST",
"respond to a ping (ICMP) request even if the host name is valid.",
"method to appliance_request(). Status Response 202 indicates an asynchronous REST call. Poll until",
"task to poll. Originating request on URL: {0}.'.format(calling_url)) full_rest_url = self.base_url + url",
"Else use the default for the program # Default to the minimal version",
"to connect to the appliance if not None \"\"\" self.fqdn = appliance_name if",
"defined') def get_networking_data(self): \"\"\"Request the networking information from the appliance. If the appliance",
"ova_ip: networking_data = self.get_networking_data() network = networking_data['applianceNetworks'][0] network[\"hostname\"] = self.fqdn network[\"domainName\"] = self.fqdn.split(\".\",",
"Originating request on URL: {1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling) r_tree = None try: logging.debug(\"Current Time",
"do the network setup. self.set_time_server_and_locale(ntpserver) poll = True # Do not poll for",
"post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping {0} seconds to wait for appliance",
"ipv4_name_servers = network.get('ipv4NameServers') if ipv4_name_servers: logging.info('IPv4 Name servers: {0}'.format(ipv4_name_servers)) return ipv4_name_servers raise Exception('IPv4",
"boolean True requests data adding a header that includes authentiation information. False requests",
"= [] vm_network_json_file = open('vm_network.json',) data = json.load(vm_network_json_file) # Iterating through the json",
"ova_ip and success: self.base_url = \"https://\" + self.fqdn (task_state, task_status) = self.poll_for_task(url, response)",
"self.base_url + url task_state = 'Running' start_time = time.time() try: logging.debug(\"Starting polling the",
"json_answer.get('applianceNetworks', []): mac_address = network.get('macAddress') if mac_address: logging.info('MAC Address is: {0}'.format(mac_address)) return mac_address",
"Exception \"\"\" time_locale_url = \"/rest/appliance/configuration/time-locale\" # Query for current time-locale setting. time_locale_settings =",
"\"password\": \"<PASSWORD>\"} url = '/rest/login-sessions' try: r = self.sess.post(self.base_url + url, verify=False, headers=self._header,",
"{0}.\".format(self.api_version)) self._header = {'X-API-Version': '{}'.format(self.api_version), 'Content-Type': 'application/json'} self._secure_header = {} def get_secure_headers(self): \"\"\"Helper",
"i in hosts: param = '-n' if operating_sys=='windows' else '-c' shell_needed = True",
"Completed. ''' # network-interfaces is a special case. Rather than network-interfaces returning a",
"we can retry if the appliance goes offline (e.g. first time setup) self.sess",
"get_mac and get_ipv4_name_servers # use calls to get_networking_data, this seems poorly designed, but",
"if operating_sys=='windows' else '-c' shell_needed = True if operating_sys == 'windows' else False",
"end point returns Void. # From my reading of the documentation, this is",
"Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First time setup was successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True)) def",
"\"\"\" time_locale_url = \"/rest/appliance/configuration/time-locale\" # Query for current time-locale setting. time_locale_settings = self.get_time_locale_data()",
"error is raised. The administrator data is pulled from the dictionary in this",
"validate the hostname and if it is not valid hostname then it will",
"self.base_url = \"https://\" + self.fqdn (task_state, task_status) = self.poll_for_task(url, response) polling_results = {'task_state':",
"Session ID available. Status: {0}.'.format(r.status_code)) return self._secure_header except ValueError as e: raise Exception('Failure",
"networks = [] for network in networking_data['applianceNetworks']: if network[\"ipv4Type\"] == \"DHCP\": network['ipv4Type'] =",
"mac_address raise Exception('MAC Address is not defined') def get_ipv4_name_servers(self): \"\"\"Request the list of",
"them in log output and append to status message for e in task_errors:",
"= self.fqdn.split(\".\", 1)[1] network['ipv4Type'] = \"STATIC\" network[\"searchDomains\"] = None # this is what",
"will default to \"yes\" \"\"\" url = '/rest/appliance/eula/status' (_, _, json_result, _) =",
"raise Exception('MAC Address is not defined') def get_ipv4_name_servers(self): \"\"\"Request the list of dns",
"= {'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\": success = True elif",
"errors place them in log output and append to status message for e",
"PUT calls, to be serialized into JSON. other_properties (optional): dict A dictionary of",
"into # place for the test below this set of conditional branches. Since",
"any subsequent rest actions and then use the fqdn to make sure the",
"was an issue connecting to the appliance. Exception message: {0}\".format(e)) except Exception as",
"\"POST\", \"PUT\", \"GET\", \"DELETE\" Any other value will raise an error. url: str",
"api_version is above version 100, this will set a DNS Server IP address",
"# address and then poll for the task. if ova_ip: poll = False",
"the hostname and if it is not valid hostname then it will #the",
"100 or 200 range), an error is raised. \"\"\" url = '/rest/appliance/network-interfaces' if",
"not ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until the operation",
"while task_state in ['Running', 'New', 'Pending', 'Starting']: if time.time() >= start_time + polling_call_timeout_sec:",
"Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else: raise Exception('first_time_setup failure. Polling State: {0}. Polling Status:",
"self.appliance_request(request_type='POST', url=url, secure=True, payload=payload, poll=poll) # Reset the base url to the the",
"Return ------ _secure_header: dict. Dictionary containing X-API-Verions, Content-Type, and Auth. The Auth parameter",
"we need. Defined per program. # Eventually we may need version overrides at",
"\"no\" will not allow service access empty value will default to \"yes\" \"\"\"",
"verify=False, headers=head, timeout=timeout, **other_properties) elif request_type == \"DELETE\": r = self.sess.delete(full_url, verify=False, headers=head,",
"error is raised. Parameters ---------- none Return ------ a response object from a",
"appliance. Configures the appliance as DHCP. The appliance queries itself to define its",
"Defaults to rest_call_timeout_sec if 'None' or unspecified Return ------ return (success, r, safe_json_result,",
"payload = {\"userName\": \"Administrator\", \"password\": \"<PASSWORD>\"} url = '/rest/login-sessions' try: r = self.sess.post(self.base_url",
"* 60 sec_between_polling = 10 class FirstTimeSetUp(object): def __init__(self, appliance_name, use_ip=False, override_version=None, retries=max_retries_in_session,",
"For executing a shell command rest_call_timeout_sec = 60 max_retries_in_session = 50 polling_call_timeout_sec =",
"secure=True) if not success: raise Exception('get_time_locale_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code,",
"From my reading of the documentation, this is not consistant with the Task",
"if override_version: self.api_version = override_version else: self.api_version = 120 logging.info(\"The API Version utilized",
"overridden by passing in a value for override_version. Ideally, this computation should be",
"not need to be saved.') else: logging.debug('Call EULA Acceptance with enable service access={0}'.format(service_access))",
"+ url task_state = 'Running' start_time = time.time() try: logging.debug(\"Starting polling the rest",
"and Auth. The Auth parameter value is a sessionID. \"\"\" # Once _secure_header",
"server and only it. (ntp_success, _, ntp_rjson, ntp_polling_results) = self.appliance_request(request_type='POST', url=time_locale_url, secure=True, payload=time_locale_settings)",
"json.dumps(save_json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def accept_eula(self, service_access=\"yes\", tries=3, retry_interval=5): thistry =",
"Name servers: {0}'.format(ipv4_name_servers)) return ipv4_name_servers raise Exception('IPv4 Name server is not defined') def",
"so we follow network[\"aliasDisabled\"] = True network[\"overrideIpv4DhcpDnsServers\"] = False if network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]:",
"if save_success: logging.info('EULA Accepted.') else: raise Exception('accept_eula failed. Status: {0}. JSON Response: {1}'.format(save_resp.status_code,",
"than network-interfaces returning a object of type TaskResourceV2, this end point returns Void.",
"= network.get('ipv4NameServers') if ipv4_name_servers: logging.info('IPv4 Name servers: {0}'.format(ipv4_name_servers)) return ipv4_name_servers raise Exception('IPv4 Name",
"brought this to the attention # of the atlas team. # # there",
"authentication on the appliance is required. Parameters ---------- service_access (optional): str \"yes\" will",
"{1}. Status: {2}.\".format(task_resource.get('percentComplete'), task_state, task_status)) logging.debug(\"The task tree for {0} is:\".format(full_rest_url)) logging.debug(\"Returned JSON:",
"raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ':",
"has already been changed. Password is {0}'.format(<PASSWORD>)) else: raise Exception('change_administrator_password failed. Status: {0}.",
"resp, json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if success: logging.info('Administrator password change",
"import json import logging import time from copy import deepcopy import platform #",
"or 200 range), an error is raised. Parameters ---------- none Return ------ a",
"this computation should be moved to a default in the datastore. Parameters ----------",
"readIPV6FromFile(self): ipv6address = [] vm_network_json_file = open('vm_network.json',) data = json.load(vm_network_json_file) # Iterating through",
"know if the network definition has the \"time\" dictionary defined in it; if",
"utilized is {0}.\".format(self.api_version)) self._header = {'X-API-Version': '{}'.format(self.api_version), 'Content-Type': 'application/json'} self._secure_header = {} def",
"set of conditional branches. Since both get_mac and get_ipv4_name_servers # use calls to",
"in applianceNetworks collection. If the appliance returns an error status (anything outside of",
"name import subprocess # For executing a shell command rest_call_timeout_sec = 60 max_retries_in_session",
"requests.Session() self.retries = retries adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) # if",
"head = self._header else: head = self.get_secure_headers() head = dict(head.items() + extra_headers.items()) full_url",
"be accepted. This only needs to occur once. Additional calls will not change",
"the NTP time, so don't set it. time_locale_settings[\"ntpServers\"] = [str(ntpserver)] # use the",
"payload=logon_payload) if not logon_success: raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response,",
"(success, r, safe_json_result, polling_results) except requests.exceptions.RequestException as e: raise Exception(\"There was an issue",
"else False # Building the command. Ex: \"ping -c 1 google.com\" ping_command =",
"with enable service access={0}'.format(service_access)) url = '/rest/appliance/eula/save' payload = {\"supportAccess\": service_access} (save_success, save_resp,",
"with the HTTP Call for task polling. Exception message: {0}\".format(e)) # delete and",
"and exit. Originating request on URL: {1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling) r_tree = None try:",
"get_networking_data, this seems poorly designed, but given how complex the code is in",
"Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else: raise Exception('first_time_setup failure. Polling State: {0}. Polling",
"parameter value is a sessionID. \"\"\" # Once _secure_header is defined, we can",
"bool Flag to indicate if an IP address is being passed instead of",
"initial logon, the administrator's password has to be changed from the default value.",
"return except Exception as e: logging.exception(e) if thistry >= tries: raise e time.sleep(retry_interval)",
"= self.sess.get(full_rest_url + \"?view=tree\", verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except Exception as e: logging.exception(\"FTS get",
"for task polling. Exception message: {0}\".format(e)) # delete and recreate of the session",
"def ping(hosts): \"\"\" Returns True if host (str) responds to a ping request.",
"was not set\") logging.debug(\"Unable to get the task tree for {0}\".format(full_rest_url)) return(task_state, task_status)",
"if False, eula acceptance has already occurred. logging.warning('EULA does not need to be",
"network page. \"\"\" url = \"/rest/appliance/configuration/time-locale\" (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url,",
"Go to checking for response in the header, if not there, check in",
"\"POST\": r = self.sess.post(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"PUT\":",
"= {} try: if request_type == \"POST\": r = self.sess.post(full_url, verify=False, headers=head, data=json.dumps(payload),",
"json_result, _) = self.appliance_request(request_type='GET', url=url, secure=False) if not json_result: # if False, eula",
"raised. Parameters ---------- none Return ------ mac address: string \"\"\" json_answer = self.get_networking_data()",
"call to the network page. \"\"\" url = \"/rest/appliance/configuration/time-locale\" (success, resp, json_response, _)",
"= use_ip # create a persistant session so that we can retry if",
"again for the duration of its life. # Note, the header is only",
"is only good for that user (administrator), 24 hours, and until the next",
"# # there are now at least two responses with the task URL",
"= self._header else: head = self.get_secure_headers() head = dict(head.items() + extra_headers.items()) full_url =",
"time, so don't set it. time_locale_settings[\"ntpServers\"] = [str(ntpserver)] # use the defined NTP",
"test below this set of conditional branches. Since both get_mac and get_ipv4_name_servers #",
"= self.appliance_request(request_type='POST', url=url, secure=True, payload=payload, poll=poll) # Reset the base url to the",
"requires task polling. \"\"\" if timeout is None: timeout = rest_call_timeout_sec if not",
"get_secure_headers(). Parameters ---------- request_type: str accepted values are: \"POST\", \"PUT\", \"GET\", \"DELETE\" Any",
"is attempted. If the change administrator password call fails, then we attempt to",
"appliance_name : str fully qualified name of the appliance use_ip : bool Flag",
"only needs to occur once. Additional calls will not change the status of",
"payload=payload) if success: logging.info('Administrator password change was accepted.') elif resp.status_code == 400: logon_url",
"success: self.base_url = \"https://\" + self.fqdn (task_state, task_status) = self.poll_for_task(url, response) polling_results =",
"logging import time from copy import deepcopy import platform # For getting the",
"\"ipv4Subnet\": \"\", \"ipv4Gateway\": None, \"confOneNode\": True, \"activeNode\": 1 } ], } # Not",
"an IP address is being passed instead of DNS hostname. override_version (Optional): int",
"more formal location. Parameters ---------- none \"\"\" # The changePassword REST end point",
"seems poorly designed, but given how complex the code is in this #",
"= self.sess.delete(full_url, verify=False, headers=head, timeout=timeout, **other_properties) else: raise Exception(\"RestAppliance attempted to call an",
"network[\"searchDomains\"] = None # this is what UI does so we follow network[\"aliasDisabled\"]",
"Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': '))))",
"100 or 200 range), an error is raised. No authentication on the appliance",
"a response object from a call to the network page. \"\"\" url =",
"dictionary with two values, task_state and task_status. Both are populated whenever the call",
"will be raised by method if it fails. time_locale_settings[\"dateTime\"] = None # our",
"Exception as e: raise Exception('Error in polling for the task. Originating request on",
"requests. An exception will be raised if an unknown value for request_type is",
"server setting was successful\") def poll_for_task(self, calling_url, response): '''Helper method to appliance_request(). Status",
"Changes in IP address, FQDN, etc can make use lose the session. else:",
"response) polling_results = {'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\": success =",
"# our time is not necessarily the NTP time, so don't set it.",
"enable service access={0}'.format(service_access)) url = '/rest/appliance/eula/save' payload = {\"supportAccess\": service_access} (save_success, save_resp, save_json_response,",
"= \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] = False network['virtIpv4Addr'] = None networks.append(network) appliance_domain_name = self.fqdn.split(\".\", 1)[1]",
"'task_status': 'N/A'}) (task_state, task_status) = self.poll_for_task(url, r) polling_results = {'task_state': task_state, 'task_status': task_status}",
"place for the test below this set of conditional branches. Since both get_mac",
"State of the task. For Example: Unknown, Running, Terminated, Error, Warning, Completed. '''",
"static at some point later. if ipv6_type != \"DHCP\": ipv6_type = \"UNCONFIGURE\" payload",
"str(e)) if already_reset_session: raise Exception(\"There was an issue with the HTTP Call for",
"change_administrator_password(self): \"\"\"On initial logon, the administrator's password has to be changed from the",
"# network-interfaces is a special case. Rather than network-interfaces returning a object of",
"json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if success: logging.info('Administrator password change was",
"Parameters ---------- none Return ------ mac address: string \"\"\" json_answer = self.get_networking_data() for",
"Return ------ mac address: string \"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks',",
"bool. A True/False value. True indicates that the status_code was under 300 and",
"if it is not valid hostname then it will #the warning for post-validation",
"\";\" + \";\".join([str(e) for e in task_errors]) logging.debug(\"Percent Complete : {0}. State: {1}.",
"# 202 status codes indicate a task that is pollable. The calling function",
"the system with this string. secure (optional): boolean True requests data adding a",
"accept_eula_once(self, service_access=\"yes\"): \"\"\"On initial communication with the appliance, the end user service agreement",
"user (administrator), 24 hours, and until the next reboot. if self._secure_header: return self._secure_header",
"without authentication information no value defaults in True payload (optional): dict Python object",
"{0}.'.format(calling_url)) full_rest_url = self.base_url + url task_state = 'Running' start_time = time.time() try:",
"append to status message for e in task_errors: logging.error(e) task_status += \";\" +",
"(task_state, task_status) = self.poll_for_task(url, r) polling_results = {'task_state': task_state, 'task_status': task_status} if task_state",
"POST command to set the networking. Instead, we will change to the new",
"implementations and inconsistent with REST principles. url = response.headers.get('location') if url is None:",
"'task_status': safe_json_result.get('details', str(safe_json_result))} return (success, r, safe_json_result, polling_results) except requests.exceptions.RequestException as e: raise",
"Additional calls will not change the status of the EULA nor the status",
"requests.exceptions.RequestException as e: raise Exception(\"There was an issue connecting to the appliance. Exception",
"== 400: logon_url = '/rest/login-sessions' logon_payload = {\"userName\": admin_user, \"password\": <PASSWORD>} (logon_success, _,",
"to appliance_request(). Gives header information required by the appliance with authentication information. Return",
"Name server is not defined') def get_networking_data(self): \"\"\"Request the networking information from the",
"Exception(\"There was an issue with the HTTP Call. Exception message: {0}\".format(e)) def accept_eula_once(self,",
"checking for response in the header, if not there, check in the JSON.",
"= 50 polling_call_timeout_sec = 10 * 60 sec_between_polling = 10 class FirstTimeSetUp(object): def",
"self.sess.post(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"PUT\": r = self.sess.put(full_url,",
"seconds to wait for appliance to stabilize\".format(post_eula_delay)) time.sleep(post_eula_delay) ra.change_administrator_password() ra.first_time_setup(ntpserver, use_static_ip=False, use_i3s_fts=False, use_one_ip=False,",
"indicate if an IP address is being passed instead of DNS hostname. override_version",
"to the appliance if not None \"\"\" self.fqdn = appliance_name if appliance_dhcp_ip_address: self.base_url",
"fully qualified domain name of the system with this string. secure (optional): boolean",
"access is required, see the function change_service_access() If the appliance returns an error",
"\"\"\"Helper method to appliance_request(). Gives header information required by the appliance with authentication",
"to checking for response in the header, if not there, check in the",
"or GET. request_type: {0}. url: {1}\".format(request_type, url)) try: safe_json_result = r.json() except: safe_json_result",
"Running, Terminated, Error, Warning, Completed. ''' # network-interfaces is a special case. Rather",
"if r.status_code >= 300: raise Exception('Failure to get secure connection. Status {0}.'.format(r.status_code)) try:",
"call an http request other than POST, PUT, or GET. request_type: {0}. url:",
"of dns ipv4 name servers. Use the first one found in applianceNetworks collection.",
"if __name__ == '__main__': post_eula_delay = '10' ntpserver = \"10.10.10.10\" ipv6address = readIPV6FromFile()",
"override_version=3200, use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping {0} seconds to",
"except: raise Exception('Failure to access the sessionID from the response. Status: {0}. JSON:",
"since the ip address will change after setting up the networking. if ova_ip",
"= network.get('macAddress') if mac_address: logging.info('MAC Address is: {0}'.format(mac_address)) return mac_address raise Exception('MAC Address",
"was successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True)) def readIPV6FromFile(self): ipv6address = [] vm_network_json_file = open('vm_network.json',)",
"the minimal version number that implements all the requirements that we need. Defined",
"the response. Status: {0}. JSON: {1}'.format(r.status_code, r.json())) def appliance_request(self, request_type, url, secure=True, payload=None,",
"payload = {\"userName\": initial_admin, \"oldPassword\": <PASSWORD>, \"newPassword\": <PASSWORD>} (success, resp, json_response, _) =",
"Exception('Failure to get secure connection. Status {0}.'.format(r.status_code)) try: safe_json = r.json() self._secure_header =",
"all the requirements that we need. Defined per program. # Eventually we may",
"r_tree.json() task_resource = r_treejson.get('resource') task_state = task_resource.get('taskState') task_status = task_resource.get('taskStatus', '') task_errors =",
"network = networking_data['applianceNetworks'][0] network[\"hostname\"] = self.fqdn network[\"domainName\"] = self.fqdn.split(\".\", 1)[1] network['ipv4Type'] = \"STATIC\"",
"network['ipv4Type'] = \"STATIC\" network['ipv6Type'] = \"UNCONFIGURE\" networks.append(network) if use_i3s_fts: network['ipv6Type'] = \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"]",
"request on URL: {0}. Exception: {1}'.format(calling_url, e)) except Exception as e: raise Exception('Error",
"is below version 100, it does not set DNS. If the appliance returns",
"GET. request_type: {0}. url: {1}\".format(request_type, url)) try: safe_json_result = r.json() except: safe_json_result =",
"Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server setting was",
"Parameters ---------- none Return ------ list of ipv4 name servers: list \"\"\" json_answer",
"as e: logging.exception(\"FTS get failed: \" + str(e)) if already_reset_session: raise Exception(\"There was",
"this to the attention # of the atlas team. # # there are",
"if not there, check in the JSON. Poor consistency in # implementations and",
"<reponame>chebroluharika/SDK_Automation_Generator import requests import json import logging import time from copy import deepcopy",
"function change_service_access() If the appliance returns an error status (anything outside of the",
"networking information from the appliance. If the appliance returns an error status (anything",
"str fully qualified name of the appliance use_ip : bool Flag to indicate",
"10 class FirstTimeSetUp(object): def __init__(self, appliance_name, use_ip=False, override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False, use_one_ip=False,",
"else: head = self.get_secure_headers() head = dict(head.items() + extra_headers.items()) full_url = self.base_url +",
"status. success = True elif r.status_code < 300: success = True else: polling_results",
"If the api_version is below version 100, it does not set DNS. If",
"servers: {0}'.format(ipv4_name_servers)) return ipv4_name_servers raise Exception('IPv4 Name server is not defined') def get_networking_data(self):",
"for the test below this set of conditional branches. Since both get_mac and",
"= '10' ntpserver = \"10.10.10.10\" ipv6address = readIPV6FromFile() pingableipv6 = ping(ipv6address) ra =",
"State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server setting was successful\")",
"can be overridden by passing in a value for override_version. Ideally, this computation",
"= rest_call_timeout_sec if not secure: head = self._header else: head = self.get_secure_headers() head",
"success = True elif r.status_code < 300: success = True else: polling_results =",
"{0}\".format(e)) # delete and recreate of the session if it loses connection. Changes",
"task tree for {0} is:\".format(full_rest_url)) logging.debug(\"Returned JSON: {0}\".format(r_treejson)) else: logging.debug(\"Exception during get call,",
"Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First time setup was successful\")",
"= self.appliance_request(request_type='POST', url=time_locale_url, secure=True, payload=time_locale_settings) if not ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4, separators=(',', ':",
"use_ip : bool Flag to indicate if an IP address is being passed",
"clear why this conditions fails to query the network interface to get the",
"if not poll: return (True, r, safe_json_result, {'task_state': 'N/A', 'task_status': 'N/A'}) (task_state, task_status)",
"the task is complete or error. Adds to the set of parameters that",
"is None: timeout = rest_call_timeout_sec if not secure: head = self._header else: head",
"appliance. Use the first one found in applianceNetworks collection. If the appliance returns",
"adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) if r_tree: r_treejson = r_tree.json() task_resource",
"request_type == \"DELETE\": r = self.sess.delete(full_url, verify=False, headers=head, timeout=timeout, **other_properties) else: raise Exception(\"RestAppliance",
"this seems poorly designed, but given how complex the code is in this",
"use_i3s_fts: network['ipv6Type'] = \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] = False network['virtIpv4Addr'] = None networks.append(network) appliance_domain_name =",
"from a Requests call. safe_json_results: the JSON returned from the HTTP request. None",
"DNS Server IP address and set the overrideIpv4DhcpDnsServers value to False. \"ipv4NameServers\": [dns_server_ip],",
"adap) self.sess.mount('https://', adap) if r_tree: r_treejson = r_tree.json() task_resource = r_treejson.get('resource') task_state =",
"# Go to checking for response in the header, if not there, check",
"domain name of the system with this string. secure (optional): boolean True requests",
"raised by method if it fails. time_locale_settings[\"dateTime\"] = None # our time is",
"get failed: \" + str(e)) if already_reset_session: raise Exception(\"There was an issue with",
"logging.debug('Call EULA Acceptance with enable service access={0}'.format(service_access)) url = '/rest/appliance/eula/save' payload = {\"supportAccess\":",
"request other than POST, PUT, or GET. request_type: {0}. url: {1}\".format(request_type, url)) try:",
"allow service access empty value will default to \"yes\" \"\"\" url = '/rest/appliance/eula/status'",
"raise Exception('IPv4 Name server is not defined') def get_networking_data(self): \"\"\"Request the networking information",
"start_time = time.time() try: logging.debug(\"Starting polling the rest task {0}.\".format(url)) already_reset_session = False",
"= False while task_state in ['Running', 'New', 'Pending', 'Starting']: if time.time() >= start_time",
"deployed as DHCP but, # need to be configured as static since the",
"cannot be contacted. If secure=True, this function depends on get_secure_headers(). Parameters ---------- request_type:",
"if not success: raise Exception('get_networking_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response,",
"Only ipv6 with DHCP is supported, will add static at some point later.",
"the operation completes' in polling_results.get(\"task_status\"): raise Exception('first_time_setup failure. Polling State: {0}. Polling Status:",
"to the network page. \"\"\" url = \"/rest/appliance/configuration/time-locale\" (success, resp, json_response, _) =",
"the header is undefined. No Session ID available. Status: {0}.'.format(r.status_code)) return self._secure_header except",
"error is raised. No authentication on the appliance is required. Parameters ---------- service_access",
"connecting to the appliance. Exception message: {0}\".format(e)) except Exception as e: raise Exception(\"There",
"access={0}'.format(service_access)) url = '/rest/appliance/eula/save' payload = {\"supportAccess\": service_access} (save_success, save_resp, save_json_response, _) =",
"{0}.\".format(head)) logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload))) polling_results = {} try: if request_type == \"POST\": r",
"\"yes\" \"\"\" url = '/rest/appliance/eula/status' (_, _, json_result, _) = self.appliance_request(request_type='GET', url=url, secure=False)",
"requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) if r_tree: r_treejson = r_tree.json() task_resource = r_treejson.get('resource')",
"to get headers. Exception message: {0}\".format(e)) except Exception as e: raise Exception(\"There was",
"separators=(',', ': ')))) logging.warning('Administrator password has already been changed. Password is {0}'.format(<PASSWORD>)) else:",
"\"UNCONFIGURE\" networks.append(network) if use_i3s_fts: network['ipv6Type'] = \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] = False network['virtIpv4Addr'] = None",
"task URL in the header: # '/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale' # Go to checking",
"{0}.'.format(r.status_code)) return self._secure_header except ValueError as e: raise Exception('Failure to get a JSON",
"will set a DNS Server IP address and set the overrideIpv4DhcpDnsServers value to",
"network[\"overrideIpv4DhcpDnsServers\"] = False if network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] = '' network[\"app1Ipv4Addr\"] = ova_ip",
"headers. Exception message: {0}\".format(e)) if r.status_code >= 300: raise Exception('Failure to get secure",
"poll=poll) # Reset the base url to the the fqdn for any subsequent",
"poll: return (True, r, safe_json_result, {'task_state': 'N/A', 'task_status': 'N/A'}) (task_state, task_status) = self.poll_for_task(url,",
"# Reset the base url to the the fqdn for any subsequent rest",
"version number that implements all the requirements that we need. Defined per program.",
"safe_json_result.get('details', str(safe_json_result))} return (success, r, safe_json_result, polling_results) except requests.exceptions.RequestException as e: raise Exception(\"There",
"self.sess = requests.Session() self.retries = retries adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap)",
"= \"https://\" + appliance_dhcp_ip_address else: self.base_url = \"https://\" + appliance_name self.use_ip = use_ip",
"if time.time() >= start_time + polling_call_timeout_sec: raise Exception('Task Polling did not respond within",
"over and over again for the duration of its life. # Note, the",
"X-API-Verions, Content-Type, and Auth. The Auth parameter value is a sessionID. \"\"\" #",
"= requests.Session() self.retries = retries adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) #",
"task_state == \"Completed\": success = True elif self.use_ip and task_state == \"Warning\": #This",
"complex the code is in this # area and the lack of documented",
"the appliance. Use the first one found in applianceNetworks collection. If the appliance",
"task_status} if task_state == \"Completed\": success = True elif self.use_ip and task_state ==",
"{0}\".format(e)) if r.status_code >= 300: raise Exception('Failure to get secure connection. Status {0}.'.format(r.status_code))",
"REST end point only works for the initial administrator password change. url =",
"network[\"hostname\"]: network[\"hostname\"] = network[\"hostname\"] + '.' + appliance_domain_name logging.info(\"Setting fqdn for the appliance:{0}\".format(network[\"hostname\"]))",
"raise Exception(\"Impossible happened: app1Ipv4Addr != virtIpv4Addr\") network[\"ipv6Type\"] = \"UNCONFIGURE\" payload = networking_data elif",
"safe_json.get('sessionID') if self._secure_header['Auth'] is None: raise Exception('Auth token for the header is undefined.",
"An exception will be raised if an unknown value for request_type is utilized.",
"DHCP but, # need to be configured as static since the ip address",
"network.get('ipv4NameServers') if ipv4_name_servers: logging.info('IPv4 Name servers: {0}'.format(ipv4_name_servers)) return ipv4_name_servers raise Exception('IPv4 Name server",
"appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping {0} seconds to wait for",
"# implementations and inconsistent with REST principles. url = response.headers.get('location') if url is",
"for the task. Originating request on URL: {0}. Exception: {1}'.format(calling_url, e)) def first_time_setup(self,",
"(e.g. first time setup) self.sess = requests.Session() self.retries = retries adap = requests.adapters.HTTPAdapter(max_retries=self.retries)",
"see the function change_service_access() If the appliance returns an error status (anything outside",
"is passed in. If a ova_ip is passed in then we will lose",
"appliance is required. Parameters ---------- service_access (optional): str \"yes\" will accept service access",
"polling tasks will return immiedtaly - needed for failover setups timeout: None or",
"str. A short summary of the execution/completion status task_status: str. State of the",
"is not successful, an error is raised. The administrator data is pulled from",
"appliance cannot be contacted. If secure=True, this function depends on get_secure_headers(). Parameters ----------",
"json list for i in data['results'][0]['msg']: for j in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) # Closing",
"Return ------ return (success, r, safe_json_result, polling_results) A tuple with these values: success:",
"tries: raise e time.sleep(retry_interval) thistry += 1 def change_administrator_password(self): \"\"\"On initial logon, the",
"is not consistant with the Task Tracker mechanism. I have brought this to",
"POST to do the network setup. self.set_time_server_and_locale(ntpserver) poll = True # Do not",
"Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else: raise Exception( 'time-locale",
"self.sess.mount('http://', adap) self.sess.mount('https://', adap) # if version is passed in, use that. Else",
"a JSON value. polling_results: dict. dictionary with two values, task_state and task_status. Both",
"change_service_access() If the appliance returns an error status (anything outside of the 100",
"use the defined NTP server and only it. (ntp_success, _, ntp_rjson, ntp_polling_results) =",
"Both are populated whenever the call requires task polling. \"\"\" if timeout is",
"etc can make use lose the session. else: already_reset_session = True self.sess.close() self.sess",
"to set the networking. Instead, we will change to the new # address",
"headers. Exception message: {0}\".format(e)) except Exception as e: raise Exception(\"There was an issue",
"timeout=timeout, **other_properties) else: raise Exception(\"RestAppliance attempted to call an http request other than",
"== 'windows' else False # Building the command. Ex: \"ping -c 1 google.com\"",
"message: {0}\".format(e)) if r.status_code >= 300: raise Exception('Failure to get secure connection. Status",
"object of type TaskResourceV2, this end point returns Void. # From my reading",
"logging.debug(\"Percent Complete : {0}. State: {1}. Status: {2}.\".format(task_resource.get('percentComplete'), task_state, task_status)) logging.debug(\"The task tree",
"payload = {\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\": \"DHCP\", \"ipv6Type\": ipv6_type, \"macAddress\": appliance_mac_address, \"hostname\": self.fqdn,",
"the safest change to make. old_network = self.get_networking_data() if \"time\" in old_network: payload[\"time\"]",
"= '/rest/appliance/network-interfaces' (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not success:",
"(success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_networking_data",
"API # This will embed another REST process using POST inside the generation",
"Building the command. Ex: \"ping -c 1 google.com\" ping_command = ['ping', param, '1',",
"password has to be changed from the default value. The call to the",
"= self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if save_success: logging.info('EULA Accepted.') else: raise Exception('accept_eula failed.",
"+ url logging.debug(\"Preparing HTTP {0} request.\".format(request_type)) logging.debug(\"Preparing URL: {0}.\".format(full_url)) logging.debug(\"Preparing Headers: {0}.\".format(head)) logging.debug(\"Preparing",
"= self.sess.get(full_url, verify=False, headers=head, timeout=timeout, **other_properties) elif request_type == \"DELETE\": r = self.sess.delete(full_url,",
"was called in appliance_request. response : a response object from a Requests call.",
"atlas team. # # there are now at least two responses with the",
"the default for the program # Default to the minimal version number that",
"else: logging.debug('Call EULA Acceptance with enable service access={0}'.format(service_access)) url = '/rest/appliance/eula/save' payload =",
"macAddress. If the api_version is above version 100, this will set a DNS",
"it fails. time_locale_settings[\"dateTime\"] = None # our time is not necessarily the NTP",
"\"ipv4Gateway\": None, \"confOneNode\": True, \"activeNode\": 1 } ], } # Not clear why",
"url, secure=True, payload=None, other_properties={}, extra_headers={}, poll=True, timeout=None): \"\"\"Helper method to call HTTP requests.",
"responds to a ping request. Remember that a host may not respond to",
"------ tuple containing: task_state: str. A short summary of the execution/completion status task_status:",
"= self.get_networking_data() networks = [] for network in networking_data['applianceNetworks']: if network[\"ipv4Type\"] == \"DHCP\":",
"appliance. Exception message: {0}\".format(e)) except Exception as e: raise Exception(\"There was an issue",
"50 polling_call_timeout_sec = 10 * 60 sec_between_polling = 10 class FirstTimeSetUp(object): def __init__(self,",
"the appliance goes offline (e.g. first time setup) self.sess = requests.Session() self.retries =",
"time_locale_settings[\"ntpServers\"] = [str(ntpserver)] # use the defined NTP server and only it. (ntp_success,",
"if r.status_code == 202: if not poll: return (True, r, safe_json_result, {'task_state': 'N/A',",
"not logon_success: raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4,",
"json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def get_time_locale_data(self): \"\"\"Request the networking",
"self.fqdn network[\"domainName\"] = self.fqdn.split(\".\", 1)[1] network['ipv4Type'] = \"STATIC\" network[\"searchDomains\"] = None # this",
"full_url = self.base_url + url logging.debug(\"Preparing HTTP {0} request.\".format(request_type)) logging.debug(\"Preparing URL: {0}.\".format(full_url)) logging.debug(\"Preparing",
"== \"POST\": r = self.sess.post(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type ==",
"request_type == \"GET\": r = self.sess.get(full_url, verify=False, headers=head, timeout=timeout, **other_properties) elif request_type ==",
"or 200 range), an error is raised. Parameters ---------- none Return ------ mac",
"logging.info('MAC Address is: {0}'.format(mac_address)) return mac_address raise Exception('MAC Address is not defined') def",
"the networking information from the appliance. If the appliance returns an error status",
"is a special case. Rather than network-interfaces returning a object of type TaskResourceV2,",
"r_tree = self.sess.get(full_rest_url + \"?view=tree\", verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except Exception as e: logging.exception(\"FTS",
"= subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode if success == 0: return (str(i)+str('%ens160')) if __name__",
"\"<PASSWORD>\"} url = '/rest/login-sessions' try: r = self.sess.post(self.base_url + url, verify=False, headers=self._header, data=json.dumps(payload),",
"and then poll for the task. if ova_ip: poll = False (success, response,",
"the session if it loses connection. Changes in IP address, FQDN, etc can",
"success = ping_output.returncode if success == 0: return (str(i)+str('%ens160')) if __name__ == '__main__':",
"= self.get_ipv4_name_servers() # Only ipv6 with DHCP is supported, will add static at",
"that this will return a 202. success = False if r.status_code == 202:",
"(anything outside of the 100 or 200 range), an error is raised. \"\"\"",
"self.poll_for_task(url, response) polling_results = {'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\": success",
"completes' in ntp_polling_results.get(\"task_status\"): raise Exception( 'time-locale setting failed. Polling State: {0}. Polling Status:",
"True} poll : boolean If false, polling tasks will return immiedtaly - needed",
"url, verify=False, headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec) except requests.exceptions.RequestException as e: raise Exception(\"There was an",
"= self.get_networking_data() for network in json_answer.get('applianceNetworks', []): ipv4_name_servers = network.get('ipv4NameServers') if ipv4_name_servers: logging.info('IPv4",
"ova_ip network[\"app2Ipv4Addr\"] = '' else: raise Exception(\"Impossible happened: app1Ipv4Addr != virtIpv4Addr\") network[\"ipv6Type\"] =",
"includes authentiation information. False requests data without authentication information no value defaults in",
"to the administrator password change is attempted. If the change administrator password call",
"call. Poll until the task is complete or error. Adds to the set",
"raised. No authentication on the appliance is required. Parameters ---------- service_access (optional): str",
"= networking_data elif use_static_ip: networking_data = self.get_networking_data() networks = [] for network in",
"unknown value for request_type is utilized. Exceptions will also be raised if the",
"point later. if ipv6_type != \"DHCP\": ipv6_type = \"UNCONFIGURE\" payload = {\"type\": \"ApplianceServerConfiguration\",",
"= json.load(vm_network_json_file) # Iterating through the json list for i in data['results'][0]['msg']: for",
"value to False. \"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\": False If the api_version is below version",
"': '))) if 'Wait until the operation completes' in polling_results.get(\"task_status\"): raise Exception('first_time_setup failure.",
"also be raised if the appliance cannot be contacted. If secure=True, this function",
"attempted to call an http request other than POST, PUT, or GET. request_type:",
"= None # this is what UI does so we follow network[\"aliasDisabled\"] =",
"documented test cases, this seems to be the safest change to make. old_network",
"be raised if the appliance cannot be contacted. If secure=True, this function depends",
"if 'Wait until the operation completes' in polling_results.get(\"task_status\"): raise Exception('first_time_setup failure. Polling State:",
"task_state, task_status)) logging.debug(\"The task tree for {0} is:\".format(full_rest_url)) logging.debug(\"Returned JSON: {0}\".format(r_treejson)) else: logging.debug(\"Exception",
"+ \"?view=tree\", verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except Exception as e: logging.exception(\"FTS get failed: \"",
"raise Exception('Task Polling did not respond within {0} seconds. Time out and exit.",
"as e: raise Exception('Error getting the JSON results from the task. Originating request",
"list \"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []): ipv4_name_servers = network.get('ipv4NameServers')",
"it loses connection. Changes in IP address, FQDN, etc can make use lose",
"payload = {\"supportAccess\": service_access} (save_success, save_resp, save_json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload)",
"= \"STATIC\" network['ipv6Type'] = \"UNCONFIGURE\" networks.append(network) if use_i3s_fts: network['ipv6Type'] = \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] =",
"self.fqdn.split(\".\", 1)[1] if appliance_domain_name not in network[\"hostname\"]: network[\"hostname\"] = network[\"hostname\"] + '.' +",
"program name) can be overridden. Currently only accepting values of 100, 199, and",
"if timeout is None: timeout = rest_call_timeout_sec if not secure: head = self._header",
"JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) logging.warning('Administrator password has already",
"Return ------ a response object from a call to the network page. \"\"\"",
"service_access (optional): str \"yes\" will accept service access \"no\" will not allow service",
"codes indicate a task that is pollable. The calling function may not know",
"raise Exception('Failure to get secure connection. Status {0}.'.format(r.status_code)) try: safe_json = r.json() self._secure_header",
"+ \";\".join([str(e) for e in task_errors]) logging.debug(\"Percent Complete : {0}. State: {1}. Status:",
"from the default value. The call to the administrator password change is attempted.",
"networking. Instead, we will change to the new # address and then poll",
"lose the session. else: already_reset_session = True self.sess.close() self.sess = requests.Session() adap =",
"url = response.json().get('uri') if url is None: raise Exception('Could not read the task",
"network[\"ipv6Type\"] = \"UNCONFIGURE\" payload = networking_data elif use_static_ip: networking_data = self.get_networking_data() networks =",
"is being passed instead of DNS hostname. override_version (Optional): int The default version",
"task_state == \"Warning\": #This is required sicne FTS will try to validate the",
"to make. old_network = self.get_networking_data() if \"time\" in old_network: payload[\"time\"] = deepcopy(old_network[\"time\"]) #",
"the response. Status: {0}.'.format(r.status_code)) except: raise Exception('Failure to access the sessionID from the",
"this string. secure (optional): boolean True requests data adding a header that includes",
"in networking_data['applianceNetworks']: if network[\"ipv4Type\"] == \"DHCP\": network['ipv4Type'] = \"STATIC\" network['ipv6Type'] = \"UNCONFIGURE\" networks.append(network)",
"error. Adds to the set of parameters that appliance_request() returns. Parameters ---------- calling_url",
"error. url: str url location of the REST call. This method concatenates https://",
"an error is raised. The administrator data is pulled from the dictionary in",
"calls will not change the status of the EULA nor the status of",
"minimal version number that implements all the requirements that we need. Defined per",
"300: raise Exception('Failure to get secure connection. Status {0}.'.format(r.status_code)) try: safe_json = r.json()",
"logging.info(\"The API Version utilized is {0}.\".format(self.api_version)) self._header = {'X-API-Version': '{}'.format(self.api_version), 'Content-Type': 'application/json'} self._secure_header",
"will lose connection # to the orginal location after the POST command to",
"is required, see the function change_service_access() If the appliance returns an error status",
"information. False requests data without authentication information no value defaults in True payload",
"url = '/rest/login-sessions' try: r = self.sess.post(self.base_url + url, verify=False, headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec)",
"\"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\": \"\", \"ipv4Gateway\": None, \"confOneNode\": True, \"activeNode\": 1 }",
"setting up the networking. if ova_ip and success: self.base_url = \"https://\" + self.fqdn",
"else: raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',',",
": str appliance dhcp ip address, will be used to connect to the",
"in # implementations and inconsistent with REST principles. url = response.headers.get('location') if url",
"a host may not respond to a ping (ICMP) request even if the",
"if an IP address is being passed instead of DNS hostname. override_version (Optional):",
"task_status) except ValueError as e: raise Exception('Error getting the JSON results from the",
"of DNS hostname. override_version (Optional): int The default version string (determined by program",
"and if it is not valid hostname then it will #the warning for",
"call to the network page. \"\"\" url = '/rest/appliance/network-interfaces' (success, resp, json_response, _)",
"connection. Changes in IP address, FQDN, etc can make use lose the session.",
"= \"UNCONFIGURE\" networks.append(network) if use_i3s_fts: network['ipv6Type'] = \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] = False network['virtIpv4Addr'] =",
"# Only ipv6 with DHCP is supported, will add static at some point",
"if success == 0: return (str(i)+str('%ens160')) if __name__ == '__main__': post_eula_delay = '10'",
"calling_url)) time.sleep(sec_between_polling) r_tree = None try: logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree = self.sess.get(full_rest_url +",
"\"https://\" + self.fqdn (task_state, task_status) = self.poll_for_task(url, response) polling_results = {'task_state': task_state, 'task_status':",
"None, \"confOneNode\": True, \"activeNode\": 1 } ], } # Not clear why this",
"the api_version is below version 100, it does not set DNS. If the",
"for network in json_answer.get('applianceNetworks', []): ipv4_name_servers = network.get('ipv4NameServers') if ipv4_name_servers: logging.info('IPv4 Name servers:",
"Task Tracker mechanism. I have brought this to the attention # of the",
"_, json_result, _) = self.appliance_request(request_type='GET', url=url, secure=False) if not json_result: # if False,",
"administrator password. If successful, we log a message and the accurate administrator password.",
"the ntpserver. :return: :raises: Exception, Exception \"\"\" time_locale_url = \"/rest/appliance/configuration/time-locale\" # Query for",
"team. # # there are now at least two responses with the task",
"\"STATIC\" network[\"searchDomains\"] = None # this is what UI does so we follow",
"not poll: return (True, r, safe_json_result, {'task_state': 'N/A', 'task_status': 'N/A'}) (task_state, task_status) =",
"appliance_name if appliance_dhcp_ip_address: self.base_url = \"https://\" + appliance_dhcp_ip_address else: self.base_url = \"https://\" +",
"successful\") def poll_for_task(self, calling_url, response): '''Helper method to appliance_request(). Status Response 202 indicates",
"if not None \"\"\" self.fqdn = appliance_name if appliance_dhcp_ip_address: self.base_url = \"https://\" +",
"accepting values of 100, 199, and 200. retries (Optional): int Number of retries",
"configured as static since the ip address will change after setting up the",
"task_status) = self.poll_for_task(url, r) polling_results = {'task_state': task_state, 'task_status': task_status} if task_state ==",
"queries itself to define its macAddress. If the api_version is above version 100,",
"network['virtIpv4Addr'] = None networks.append(network) appliance_domain_name = self.fqdn.split(\".\", 1)[1] if appliance_domain_name not in network[\"hostname\"]:",
"this seems to be the safest change to make. old_network = self.get_networking_data() if",
"post-validation status. success = True elif r.status_code < 300: success = True else:",
"self.get_networking_data() for network in json_answer.get('applianceNetworks', []): ipv4_name_servers = network.get('ipv4NameServers') if ipv4_name_servers: logging.info('IPv4 Name",
"= False (success, response, rjson, polling_results) = self.appliance_request(request_type='POST', url=url, secure=True, payload=payload, poll=poll) #",
"if it fails. time_locale_settings[\"dateTime\"] = None # our time is not necessarily the",
"= False if network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] = '' network[\"app1Ipv4Addr\"] = ova_ip network[\"app2Ipv4Addr\"]",
"Version utilized is {0}.\".format(self.api_version)) self._header = {'X-API-Version': '{}'.format(self.api_version), 'Content-Type': 'application/json'} self._secure_header = {}",
"can use it over and over again for the duration of its life.",
"call to the administrator password change is attempted. If the change administrator password",
"<PASSWORD>} (success, resp, json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if success: logging.info('Administrator",
"None: url = response.json().get('uri') if url is None: raise Exception('Could not read the",
"= 'Running' start_time = time.time() try: logging.debug(\"Starting polling the rest task {0}.\".format(url)) already_reset_session",
"default in the datastore. Parameters ---------- appliance_name : str fully qualified name of",
"not respond to a ping (ICMP) request even if the host name is",
"e: raise Exception(\"There was an issue with the HTTP Call. Exception message: {0}\".format(e))",
"= 1 while True: logging.info(\"accept_eula try {}\".format(thistry)) try: self.accept_eula_once(service_access=service_access) return except Exception as",
"string (determined by program name) can be overridden. Currently only accepting values of",
"read the task to poll. Originating request on URL: {0}.'.format(calling_url)) full_rest_url = self.base_url",
"raise Exception(\"There was an issue connecting to the appliance. Exception message: {0}\".format(e)) except",
"this will return a 202. success = False if r.status_code == 202: if",
"self.api_version = override_version else: self.api_version = 120 logging.info(\"The API Version utilized is {0}.\".format(self.api_version))",
"# in case of errors place them in log output and append to",
"{0} request.\".format(request_type)) logging.debug(\"Preparing URL: {0}.\".format(full_url)) logging.debug(\"Preparing Headers: {0}.\".format(head)) logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload))) polling_results =",
"if already_reset_session: raise Exception(\"There was an issue with the HTTP Call for task",
"return a JSON value. polling_results: dict. dictionary with two values, task_state and task_status.",
"service access \"no\" will not allow service access empty value will default to",
"to the new # address and then poll for the task. if ova_ip:",
"ipv4_name_servers: logging.info('IPv4 Name servers: {0}'.format(ipv4_name_servers)) return ipv4_name_servers raise Exception('IPv4 Name server is not",
"a call to the network page. \"\"\" url = \"/rest/appliance/configuration/time-locale\" (success, resp, json_response,",
"will not change the status of the EULA nor the status of the",
"base url to the the fqdn for any subsequent rest actions and then",
"on the appliance is required. Parameters ---------- service_access (optional): str \"yes\" will accept",
"(success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_time_locale_data",
"the overrideIpv4DhcpDnsServers value to False. \"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\": False If the api_version is",
"issue connecting to the appliance. Exception message: {0}\".format(e)) except Exception as e: raise",
"host_data=None): \"\"\"Creates networking for the appliance. Configures the appliance as DHCP. The appliance",
"indicates an asynchronous REST call. Poll until the task is complete or error.",
"setup was successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True)) def readIPV6FromFile(self): ipv6address = [] vm_network_json_file =",
"indent=2, sort_keys=True)) def readIPV6FromFile(self): ipv6address = [] vm_network_json_file = open('vm_network.json',) data = json.load(vm_network_json_file)",
"to be the safest change to make. old_network = self.get_networking_data() if \"time\" in",
"an issue with the HTTP Call to get headers. Exception message: {0}\".format(e)) if",
"override_version. Ideally, this computation should be moved to a default in the datastore.",
"'Error'), 'task_status': safe_json_result.get('details', str(safe_json_result))} return (success, r, safe_json_result, polling_results) except requests.exceptions.RequestException as e:",
"Complete : {0}. State: {1}. Status: {2}.\".format(task_resource.get('percentComplete'), task_state, task_status)) logging.debug(\"The task tree for",
"change after setting up the networking. if ova_ip and success: self.base_url = \"https://\"",
"not there, check in the JSON. Poor consistency in # implementations and inconsistent",
"---------- appliance_name : str fully qualified name of the appliance use_ip : bool",
"unspecified Return ------ return (success, r, safe_json_result, polling_results) A tuple with these values:",
"method to appliance_request(). Gives header information required by the appliance with authentication information.",
"tree for {0} is:\".format(full_rest_url)) logging.debug(\"Returned JSON: {0}\".format(r_treejson)) else: logging.debug(\"Exception during get call, response",
"polling_results = {} try: if request_type == \"POST\": r = self.sess.post(full_url, verify=False, headers=head,",
"of the network-interfaces JSON, it is set via an independent REST endpoint. :param",
"ipv6_type, \"macAddress\": appliance_mac_address, \"hostname\": self.fqdn, \"device\": \"eth0\", \"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\": \"\",",
"empty value will default to \"yes\" \"\"\" url = '/rest/appliance/eula/status' (_, _, json_result,",
"not necessarily the NTP time, so don't set it. time_locale_settings[\"ntpServers\"] = [str(ntpserver)] #",
"self.use_ip and task_state == \"Warning\": #This is required sicne FTS will try to",
"raise Exception( 'time-locale setting failed. Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"),",
"'task_status': task_status} if task_state == \"Completed\": success = True else: success = False",
"but, # need to be configured as static since the ip address will",
"authentiation information. False requests data without authentication information no value defaults in True",
"in the header, if not there, check in the JSON. Poor consistency in",
"'N/A'}) (task_state, task_status) = self.poll_for_task(url, r) polling_results = {'task_state': task_state, 'task_status': task_status} if",
"**other_properties) else: raise Exception(\"RestAppliance attempted to call an http request other than POST,",
"use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Constructor method to RestAppliance. We compute the correct API-Version",
"---------- calling_url : string The URL that was called in appliance_request. response :",
"resp.status_code == 400: logon_url = '/rest/login-sessions' logon_payload = {\"userName\": admin_user, \"password\": <PASSWORD>} (logon_success,",
"conditional branches. Since both get_mac and get_ipv4_name_servers # use calls to get_networking_data, this",
"response.headers.get('location') if url is None: url = response.json().get('uri') if url is None: raise",
"Terminated, Error, Warning, Completed. ''' # network-interfaces is a special case. Rather than",
"raise Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else: raise",
"the administrator password change is attempted. If the change administrator password call fails,",
"designed, but given how complex the code is in this # area and",
"else: already_reset_session = True self.sess.close() self.sess = requests.Session() adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap)",
"'1', i] ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode if success == 0: return",
"shell command rest_call_timeout_sec = 60 max_retries_in_session = 50 polling_call_timeout_sec = 10 * 60",
"If the api_version is above version 100, this will set a DNS Server",
"time setup) self.sess = requests.Session() self.retries = retries adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap)",
"Exception('Error in polling for the task. Originating request on URL: {0}. Exception: {1}'.format(calling_url,",
"{0}.'.format(r.status_code)) try: safe_json = r.json() self._secure_header = self._header.copy() self._secure_header['Auth'] = safe_json.get('sessionID') if self._secure_header['Auth']",
"status_code was under 300 and the polling was successful. r: a response object",
"setup) self.sess = requests.Session() self.retries = retries adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://',",
"Default to the minimal version number that implements all the requirements that we",
"service access. If a change to the service access is required, see the",
"try: safe_json_result = r.json() except: safe_json_result = {} logging.debug(\"Returned. Status code: {0}.\".format(r.status_code)) logging.debug(\"Returned.",
"url = '/rest/appliance/network-interfaces' (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not",
"if the appliance goes offline (e.g. first time setup) self.sess = requests.Session() self.retries",
"the operation completes' in ntp_polling_results.get(\"task_status\"): raise Exception( 'time-locale setting failed. Polling State: {0}.",
"network[\"ipv4Type\"] == \"DHCP\": network['ipv4Type'] = \"STATIC\" network['ipv6Type'] = \"UNCONFIGURE\" networks.append(network) if use_i3s_fts: network['ipv6Type']",
"secure (optional): boolean True requests data adding a header that includes authentiation information.",
"if task_state == \"Completed\": success = True elif self.use_ip and task_state == \"Warning\":",
"False, eula acceptance has already occurred. logging.warning('EULA does not need to be saved.')",
"attempt to login with the administrator password. If successful, we log a message",
"string. secure (optional): boolean True requests data adding a header that includes authentiation",
"of retries to do in HTTP session. appliance_dhcp_ip_address : str appliance dhcp ip",
"password call fails, then we attempt to login with the administrator password. If",
"= ['ping', param, '1', i] ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode if success",
"separators=(',', ': '))) if 'Wait until the operation completes' in polling_results.get(\"task_status\"): raise Exception('first_time_setup",
"method concatenates https:// and the fully qualified domain name of the system with",
"True payload (optional): dict Python object payload for POST or PUT calls, to",
"an error status (anything outside of the 100 or 200 range), an error",
"that appliance_request() returns. Parameters ---------- calling_url : string The URL that was called",
"both get_mac and get_ipv4_name_servers # use calls to get_networking_data, this seems poorly designed,",
"199, and 200. retries (Optional): int Number of retries to do in HTTP",
"of the 100 or 200 range), an error is raised. Parameters ---------- none",
"a ping request. Remember that a host may not respond to a ping",
"= \"UNCONFIGURE\" payload = networking_data elif use_static_ip: networking_data = self.get_networking_data() networks = []",
"after the POST command to set the networking. Instead, we will change to",
"appliance_domain_name = self.fqdn.split(\".\", 1)[1] if appliance_domain_name not in network[\"hostname\"]: network[\"hostname\"] = network[\"hostname\"] +",
"to the set of parameters that appliance_request() returns. Parameters ---------- calling_url : string",
"def get_networking_data(self): \"\"\"Request the networking information from the appliance. If the appliance returns",
"use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Creates networking for the appliance. Configures the appliance",
"command to set the networking. Instead, we will change to the new #",
"ra.accept_eula(\"yes\") logging.info(\"Sleeping {0} seconds to wait for appliance to stabilize\".format(post_eula_delay)) time.sleep(post_eula_delay) ra.change_administrator_password() ra.first_time_setup(ntpserver,",
"change to the new # address and then poll for the task. if",
"response object from a Requests call. Return ------ tuple containing: task_state: str. A",
"the end user service agreement (EULA) must be accepted. This only needs to",
"mac address: string \"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []): mac_address",
"we will lose connection # to the orginal location after the POST command",
"version string (determined by program name) can be overridden. Currently only accepting values",
"URL that was called in appliance_request. response : a response object from a",
"': ')))) logging.warning('Administrator password has already been changed. Password is {0}'.format(<PASSWORD>)) else: raise",
"adap) self.sess.mount('https://', adap) # if version is passed in, use that. Else use",
"url=url, secure=False, payload=payload) if success: logging.info('Administrator password change was accepted.') elif resp.status_code ==",
"Closing file vm_network_json_file.close() return ipv6address def ping(hosts): \"\"\" Returns True if host (str)",
"as e: raise Exception(\"There was an issue with the HTTP Call. Exception message:",
"other_properties (optional): dict A dictionary of extra properties that we can give to",
"REST endpoint. :param ntpserver: IP address of the ntpserver. :return: :raises: Exception, Exception",
"# Exception will be raised by method if it fails. time_locale_settings[\"dateTime\"] = None",
"url=url, secure=False, payload=payload) if save_success: logging.info('EULA Accepted.') else: raise Exception('accept_eula failed. Status: {0}.",
"The administrator data is pulled from the dictionary in this file. This needs",
"safe_json_result, {'task_state': 'N/A', 'task_status': 'N/A'}) (task_state, task_status) = self.poll_for_task(url, r) polling_results = {'task_state':",
"this is what UI does so we follow network[\"aliasDisabled\"] = True network[\"overrideIpv4DhcpDnsServers\"] =",
"60 max_retries_in_session = 50 polling_call_timeout_sec = 10 * 60 sec_between_polling = 10 class",
"NTP server and only it. (ntp_success, _, ntp_rjson, ntp_polling_results) = self.appliance_request(request_type='POST', url=time_locale_url, secure=True,",
"raise Exception(\"There was an issue with the HTTP Call for task polling. Exception",
"# For getting the operating system name import subprocess # For executing a",
"Parameters ---------- request_type: str accepted values are: \"POST\", \"PUT\", \"GET\", \"DELETE\" Any other",
"headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"GET\": r = self.sess.get(full_url, verify=False, headers=head,",
"== \"DELETE\": r = self.sess.delete(full_url, verify=False, headers=head, timeout=timeout, **other_properties) else: raise Exception(\"RestAppliance attempted",
"method if it fails. time_locale_settings[\"dateTime\"] = None # our time is not necessarily",
"to know if the network definition has the \"time\" dictionary defined in it;",
"{'X-API-Version': '{}'.format(self.api_version), 'Content-Type': 'application/json'} self._secure_header = {} def get_secure_headers(self): \"\"\"Helper method to appliance_request().",
"= self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if success: logging.info('Administrator password change was accepted.') elif",
"= 10 class FirstTimeSetUp(object): def __init__(self, appliance_name, use_ip=False, override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False,",
"connecting to the appliance to get headers. Exception message: {0}\".format(e)) except Exception as",
"administrator password call fails, then we attempt to login with the administrator password.",
"param = '-n' if operating_sys=='windows' else '-c' shell_needed = True if operating_sys ==",
"class FirstTimeSetUp(object): def __init__(self, appliance_name, use_ip=False, override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False, use_one_ip=False, ipv6_type=None,",
"range), an error is raised. Parameters ---------- none Return ------ list of ipv4",
"response : a response object from a Requests call. Return ------ tuple containing:",
"of conditional branches. Since both get_mac and get_ipv4_name_servers # use calls to get_networking_data,",
"an error is raised. Parameters ---------- none Return ------ a response object from",
"except ValueError as e: raise Exception('Failure to get a JSON value from the",
"as e: raise Exception(\"There was an issue with the HTTP Call to get",
"results from the task. Originating request on URL: {0}. Exception: {1}'.format(calling_url, e)) except",
"call, response was not set\") logging.debug(\"Unable to get the task tree for {0}\".format(full_rest_url))",
"is defined, we can use it over and over again for the duration",
"the JSON. Poor consistency in # implementations and inconsistent with REST principles. url",
"\" + str(e)) if already_reset_session: raise Exception(\"There was an issue with the HTTP",
"Request. For example: other_properties={'stream': True} poll : boolean If false, polling tasks will",
"only works for the initial administrator password change. url = '/rest/users/changePassword' payload =",
"{0}'.format(mac_address)) return mac_address raise Exception('MAC Address is not defined') def get_ipv4_name_servers(self): \"\"\"Request the",
"the correct API-Version for REST calls. The version can be overridden by passing",
"logging.error(json.dumps(rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until the operation completes' in",
"= r_treejson.get('resource') task_state = task_resource.get('taskState') task_status = task_resource.get('taskStatus', '') task_errors = task_resource.get('taskErrors', None)",
"the code is in this # area and the lack of documented test",
"\"\"\" # The changePassword REST end point only works for the initial administrator",
"tuple containing: task_state: str. A short summary of the execution/completion status task_status: str.",
"{1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def set_time_server_and_locale(self, ntpserver): \"\"\"",
"= r_tree.json() task_resource = r_treejson.get('resource') task_state = task_resource.get('taskState') task_status = task_resource.get('taskStatus', '') task_errors",
"= '' network[\"app1Ipv4Addr\"] = ova_ip network[\"app2Ipv4Addr\"] = '' else: raise Exception(\"Impossible happened: app1Ipv4Addr",
"consistency in # implementations and inconsistent with REST principles. url = response.headers.get('location') if",
"later data model, where the time server and locale are set via their",
"sort_keys=True, indent=4, separators=(',', ': ')))) logging.warning('Administrator password has already been changed. Password is",
"the header, if not there, check in the JSON. Poor consistency in #",
"endpoint. :param ntpserver: IP address of the ntpserver. :return: :raises: Exception, Exception \"\"\"",
"JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def get_time_locale_data(self):",
"request_type, url, secure=True, payload=None, other_properties={}, extra_headers={}, poll=True, timeout=None): \"\"\"Helper method to call HTTP",
"task_errors]) logging.debug(\"Percent Complete : {0}. State: {1}. Status: {2}.\".format(task_resource.get('percentComplete'), task_state, task_status)) logging.debug(\"The task",
"value is a sessionID. \"\"\" # Once _secure_header is defined, we can use",
"appliance queries itself to define its macAddress. If the api_version is above version",
"self.get_networking_data() if \"time\" in old_network: payload[\"time\"] = deepcopy(old_network[\"time\"]) # This is the later",
"1 while True: logging.info(\"accept_eula try {}\".format(thistry)) try: self.accept_eula_once(service_access=service_access) return except Exception as e:",
"{0}. Exception: {1}'.format(calling_url, e)) except Exception as e: raise Exception('Error in polling for",
"return(task_state, task_status) except ValueError as e: raise Exception('Error getting the JSON results from",
"400: logon_url = '/rest/login-sessions' logon_payload = {\"userName\": admin_user, \"password\": <PASSWORD>} (logon_success, _, _,",
"Any other value will raise an error. url: str url location of the",
"Exception(\"There was an issue with the HTTP Call for task polling. Exception message:",
"is raised. The administrator data is pulled from the dictionary in this file.",
"'New', 'Pending', 'Starting']: if time.time() >= start_time + polling_call_timeout_sec: raise Exception('Task Polling did",
"know that this will return a 202. success = False if r.status_code ==",
"\";\".join([str(e) for e in task_errors]) logging.debug(\"Percent Complete : {0}. State: {1}. Status: {2}.\".format(task_resource.get('percentComplete'),",
"Exception(\"Impossible happened: app1Ipv4Addr != virtIpv4Addr\") network[\"ipv6Type\"] = \"UNCONFIGURE\" payload = networking_data elif use_static_ip:",
"are: \"POST\", \"PUT\", \"GET\", \"DELETE\" Any other value will raise an error. url:",
"and append to status message for e in task_errors: logging.error(e) task_status += \";\"",
"the appliance. Exception message: {0}\".format(e)) except Exception as e: raise Exception(\"There was an",
"subprocess # For executing a shell command rest_call_timeout_sec = 60 max_retries_in_session = 50",
"Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else: raise Exception( 'time-locale setting failure. Polling State:",
"the administrator's password has to be changed from the default value. The call",
"else '-c' shell_needed = True if operating_sys == 'windows' else False # Building",
"least two responses with the task URL in the header: # '/rest/appliance/network-interfaces' and",
"{0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else: raise Exception( 'time-locale setting failure.",
"polling_call_timeout_sec = 10 * 60 sec_between_polling = 10 class FirstTimeSetUp(object): def __init__(self, appliance_name,",
"202: if not poll: return (True, r, safe_json_result, {'task_state': 'N/A', 'task_status': 'N/A'}) (task_state,",
"True else: success = False if not success: logging.error(json.dumps(rjson, sort_keys=True, indent=4, separators=(',', ':",
"retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Constructor method to RestAppliance. We",
"in HTTP session. appliance_dhcp_ip_address : str appliance dhcp ip address, will be used",
"self.set_time_server_and_locale(ntpserver) poll = True # Do not poll for the task if a",
"Exception('Error getting the JSON results from the task. Originating request on URL: {0}.",
"int The default version string (determined by program name) can be overridden. Currently",
"added to Request. For example: other_properties={'stream': True} poll : boolean If false, polling",
"the status of the service access. If a change to the service access",
"task_errors: logging.error(e) task_status += \";\" + \";\".join([str(e) for e in task_errors]) logging.debug(\"Percent Complete",
"\"?view=tree\", verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except Exception as e: logging.exception(\"FTS get failed: \" +",
"sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def get_time_locale_data(self): \"\"\"Request the networking information",
"# networking setup task completes successfully. This needs to be done for OVA's",
"202 status codes indicate a task that is pollable. The calling function may",
"if 'Wait until the operation completes' in ntp_polling_results.get(\"task_status\"): raise Exception( 'time-locale setting failed.",
"{0}.\".format(safe_json_result)) # 202 status codes indicate a task that is pollable. The calling",
"poorly designed, but given how complex the code is in this # area",
"secure=True, payload=payload, poll=poll) # Reset the base url to the the fqdn for",
"session if it loses connection. Changes in IP address, FQDN, etc can make",
"separators=(',', ': ')))) return json_response def get_time_locale_data(self): \"\"\"Request the networking information from the",
"task if a ova_ip is passed in. If a ova_ip is passed in",
"an http request other than POST, PUT, or GET. request_type: {0}. url: {1}\".format(request_type,",
"required. Parameters ---------- service_access (optional): str \"yes\" will accept service access \"no\" will",
"with REST principles. url = response.headers.get('location') if url is None: url = response.json().get('uri')",
"get_mac(self): \"\"\"Request the MAC address from the appliance. Use the first one found",
"from copy import deepcopy import platform # For getting the operating system name",
"secure=True, payload=time_locale_settings) if not ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait",
"that. Else use the default for the program # Default to the minimal",
"60 sec_between_polling = 10 class FirstTimeSetUp(object): def __init__(self, appliance_name, use_ip=False, override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None,",
"is required. Parameters ---------- service_access (optional): str \"yes\" will accept service access \"no\"",
"access \"no\" will not allow service access empty value will default to \"yes\"",
"= self.get_networking_data() network = networking_data['applianceNetworks'][0] network[\"hostname\"] = self.fqdn network[\"domainName\"] = self.fqdn.split(\".\", 1)[1] network['ipv4Type']",
"Address is not defined') def get_ipv4_name_servers(self): \"\"\"Request the list of dns ipv4 name",
"returns Void. # From my reading of the documentation, this is not consistant",
"polling_results.get(\"task_status\"))) logging.info(\"First time setup was successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True)) def readIPV6FromFile(self): ipv6address =",
"in True payload (optional): dict Python object payload for POST or PUT calls,",
"for post-validation status. success = True elif r.status_code < 300: success = True",
"the header is only good for that user (administrator), 24 hours, and until",
"be serialized into JSON. other_properties (optional): dict A dictionary of extra properties that",
"required sicne FTS will try to validate the hostname and if it is",
"RestAppliance. We compute the correct API-Version for REST calls. The version can be",
"needs to be done for OVA's that are deployed as DHCP but, #",
"that we need. Defined per program. # Eventually we may need version overrides",
"JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def get_mac(self): \"\"\"Request the",
"network[\"virtIpv4Addr\"] = '' network[\"app1Ipv4Addr\"] = ova_ip network[\"app2Ipv4Addr\"] = '' else: raise Exception(\"Impossible happened:",
"if url is None: raise Exception('Could not read the task to poll. Originating",
"we follow network[\"aliasDisabled\"] = True network[\"overrideIpv4DhcpDnsServers\"] = False if network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"]",
"an error is raised. No authentication on the appliance is required. Parameters ----------",
"the service access. If a change to the service access is required, see",
"import subprocess # For executing a shell command rest_call_timeout_sec = 60 max_retries_in_session =",
"issue with the HTTP Call for task polling. Exception message: {0}\".format(e)) # delete",
"indicate a task that is pollable. The calling function may not know that",
"\"PUT\", \"GET\", \"DELETE\" Any other value will raise an error. url: str url",
"with DHCP is supported, will add static at some point later. if ipv6_type",
"{'task_state': 'N/A', 'task_status': 'N/A'}) (task_state, task_status) = self.poll_for_task(url, r) polling_results = {'task_state': task_state,",
"post_eula_delay=0, use_static_ip=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Constructor method to RestAppliance. We compute the",
"integer Defaults to rest_call_timeout_sec if 'None' or unspecified Return ------ return (success, r,",
"(True, r, safe_json_result, {'task_state': 'N/A', 'task_status': 'N/A'}) (task_state, task_status) = self.poll_for_task(url, r) polling_results",
"compute the correct API-Version for REST calls. The version can be overridden by",
"of its life. # Note, the header is only good for that user",
"access the sessionID from the response. Status: {0}. JSON: {1}'.format(r.status_code, r.json())) def appliance_request(self,",
"access. If a change to the service access is required, see the function",
"polling_results) A tuple with these values: success: bool. A True/False value. True indicates",
"ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Creates networking for the appliance. Configures the appliance as DHCP.",
"self.sess.mount('http://', adap) self.sess.mount('https://', adap) if r_tree: r_treejson = r_tree.json() task_resource = r_treejson.get('resource') task_state",
"A True/False value. True indicates that the status_code was under 300 and the",
"was under 300 and the polling was successful. r: a response object from",
"network[\"app2Ipv4Addr\"] = '' else: raise Exception(\"Impossible happened: app1Ipv4Addr != virtIpv4Addr\") network[\"ipv6Type\"] = \"UNCONFIGURE\"",
"indent=4, separators=(',', ': ')))) def get_mac(self): \"\"\"Request the MAC address from the appliance.",
"url logging.debug(\"Preparing HTTP {0} request.\".format(request_type)) logging.debug(\"Preparing URL: {0}.\".format(full_url)) logging.debug(\"Preparing Headers: {0}.\".format(head)) logging.debug(\"Preparing Payload:",
"for the task if a ova_ip is passed in. If a ova_ip is",
"(task_state, task_status) = self.poll_for_task(url, response) polling_results = {'task_state': task_state, 'task_status': task_status} if task_state",
"= True elif self.use_ip and task_state == \"Warning\": #This is required sicne FTS",
"object from a call to the network page. \"\"\" url = \"/rest/appliance/configuration/time-locale\" (success,",
"and 200. retries (Optional): int Number of retries to do in HTTP session.",
"task_state in ['Running', 'New', 'Pending', 'Starting']: if time.time() >= start_time + polling_call_timeout_sec: raise",
"task_state, 'task_status': task_status} if task_state == \"Completed\": success = True else: success =",
"True indicates that the status_code was under 300 and the polling was successful.",
"url = '/rest/appliance/eula/save' payload = {\"supportAccess\": service_access} (save_success, save_resp, save_json_response, _) = self.appliance_request(request_type='POST',",
"\"eth0\", \"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\": \"\", \"ipv4Gateway\": None, \"confOneNode\": True, \"activeNode\": 1",
"name of the appliance use_ip : bool Flag to indicate if an IP",
"in polling_results.get(\"task_status\"): raise Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\")))",
"object payload for POST or PUT calls, to be serialized into JSON. other_properties",
"the command. Ex: \"ping -c 1 google.com\" ping_command = ['ping', param, '1', i]",
"A dictionary of extra properties that we can give to the Python Request",
"= dict(head.items() + extra_headers.items()) full_url = self.base_url + url logging.debug(\"Preparing HTTP {0} request.\".format(request_type))",
"'task_status': task_status} if task_state == \"Completed\": success = True elif self.use_ip and task_state",
"failed: \" + str(e)) if already_reset_session: raise Exception(\"There was an issue with the",
"message for e in task_errors: logging.error(e) task_status += \";\" + \";\".join([str(e) for e",
"set\") logging.debug(\"Unable to get the task tree for {0}\".format(full_rest_url)) return(task_state, task_status) except ValueError",
"\"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\": False If the api_version is below version 100, it does",
"each REST call. if override_version: self.api_version = override_version else: self.api_version = 120 logging.info(\"The",
"for network in json_answer.get('applianceNetworks', []): mac_address = network.get('macAddress') if mac_address: logging.info('MAC Address is:",
"url = response.headers.get('location') if url is None: url = response.json().get('uri') if url is",
"saved.') else: logging.debug('Call EULA Acceptance with enable service access={0}'.format(service_access)) url = '/rest/appliance/eula/save' payload",
"task_state: str. A short summary of the execution/completion status task_status: str. State of",
"returned from the HTTP request. None if the request did not return a",
"exit. Originating request on URL: {1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling) r_tree = None try: logging.debug(\"Current",
"we can use it over and over again for the duration of its",
"\"\"\"Request the networking information from the appliance. If the appliance returns an error",
"getting the JSON results from the task. Originating request on URL: {0}. Exception:",
"use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Creates networking for the appliance. Configures the",
"'))) if 'Wait until the operation completes' in polling_results.get(\"task_status\"): raise Exception('first_time_setup failure. Polling",
"to be saved.') else: logging.debug('Call EULA Acceptance with enable service access={0}'.format(service_access)) url =",
"logging.info('Administrator password change was accepted.') elif resp.status_code == 400: logon_url = '/rest/login-sessions' logon_payload",
"+ url, verify=False, headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec) except requests.exceptions.RequestException as e: raise Exception(\"There was",
"hostname then it will #the warning for post-validation status. success = True elif",
"e: raise Exception('Error getting the JSON results from the task. Originating request on",
"it; if it does, copy into # place for the test below this",
"use_ip # create a persistant session so that we can retry if the",
"e: raise Exception(\"There was an issue connecting to the appliance to get headers.",
"the appliance use_ip : bool Flag to indicate if an IP address is",
"fqdn for the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] = networks networking_data.pop('serverCertificate', None) payload = networking_data else:",
"= time.time() try: logging.debug(\"Starting polling the rest task {0}.\".format(url)) already_reset_session = False while",
"sessionID. \"\"\" # Once _secure_header is defined, we can use it over and",
"successfully. This needs to be done for OVA's that are deployed as DHCP",
"ping(hosts): \"\"\" Returns True if host (str) responds to a ping request. Remember",
"to be done for OVA's that are deployed as DHCP but, # need",
"appliance with authentication information. Return ------ _secure_header: dict. Dictionary containing X-API-Verions, Content-Type, and",
"object from a Requests call. Return ------ tuple containing: task_state: str. A short",
"moved to a more formal location. Parameters ---------- none \"\"\" # The changePassword",
"the test below this set of conditional branches. Since both get_mac and get_ipv4_name_servers",
"'Wait until the operation completes' in polling_results.get(\"task_status\"): raise Exception('first_time_setup failure. Polling State: {0}.",
"will try to validate the hostname and if it is not valid hostname",
"status task_status: str. State of the task. For Example: Unknown, Running, Terminated, Error,",
"need version overrides at each REST call. if override_version: self.api_version = override_version else:",
"Rather than network-interfaces returning a object of type TaskResourceV2, this end point returns",
"network interface to get the base for the payload, but # we need",
"and only it. (ntp_success, _, ntp_rjson, ntp_polling_results) = self.appliance_request(request_type='POST', url=time_locale_url, secure=True, payload=time_locale_settings) if",
"The dictionary is unpacked and added to Request. For example: other_properties={'stream': True} poll",
"IP address is being passed instead of DNS hostname. override_version (Optional): int The",
"the administrator password. If successful, we log a message and the accurate administrator",
"Exception as e: raise Exception(\"There was an issue with the HTTP Call. Exception",
"This method concatenates https:// and the fully qualified domain name of the system",
"name of the system with this string. secure (optional): boolean True requests data",
"elif request_type == \"PUT\": r = self.sess.put(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif",
"if self._secure_header: return self._secure_header payload = {\"userName\": \"Administrator\", \"password\": \"<PASSWORD>\"} url = '/rest/login-sessions'",
"type TaskResourceV2, this end point returns Void. # From my reading of the",
"rest task {0}.\".format(url)) already_reset_session = False while task_state in ['Running', 'New', 'Pending', 'Starting']:",
"-c 1 google.com\" ping_command = ['ping', param, '1', i] ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success",
"supported, will add static at some point later. if ipv6_type != \"DHCP\": ipv6_type",
"Return ------ list of ipv4 name servers: list \"\"\" json_answer = self.get_networking_data() for",
"operating_sys = platform.system().lower() for i in hosts: param = '-n' if operating_sys=='windows' else",
"be configured as static since the ip address will change after setting up",
"= self._header.copy() self._secure_header['Auth'] = safe_json.get('sessionID') if self._secure_header['Auth'] is None: raise Exception('Auth token for",
"Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First time setup was successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True))",
"no value defaults in True payload (optional): dict Python object payload for POST",
"in log output and append to status message for e in task_errors: logging.error(e)",
"# if False, eula acceptance has already occurred. logging.warning('EULA does not need to",
"_secure_header is defined, we can use it over and over again for the",
"This needs to be done for OVA's that are deployed as DHCP but,",
"the service access is required, see the function change_service_access() If the appliance returns",
"being passed instead of DNS hostname. override_version (Optional): int The default version string",
"adap) # if version is passed in, use that. Else use the default",
"raise Exception('Failure to get a JSON value from the response. Status: {0}.'.format(r.status_code)) except:",
"the default value. The call to the administrator password change is attempted. If",
"calling_url : string The URL that was called in appliance_request. response : a",
"self._secure_header['Auth'] is None: raise Exception('Auth token for the header is undefined. No Session",
"= '/rest/appliance/eula/status' (_, _, json_result, _) = self.appliance_request(request_type='GET', url=url, secure=False) if not json_result:",
"url task_state = 'Running' start_time = time.time() try: logging.debug(\"Starting polling the rest task",
"data without authentication information no value defaults in True payload (optional): dict Python",
"these values: success: bool. A True/False value. True indicates that the status_code was",
"for the initial administrator password change. url = '/rest/users/changePassword' payload = {\"userName\": initial_admin,",
"the call requires task polling. \"\"\" if timeout is None: timeout = rest_call_timeout_sec",
"If the time definition is not part of the network-interfaces JSON, it is",
"the set of parameters that appliance_request() returns. Parameters ---------- calling_url : string The",
"the networking. if ova_ip and success: self.base_url = \"https://\" + self.fqdn (task_state, task_status)",
"response was not set\") logging.debug(\"Unable to get the task tree for {0}\".format(full_rest_url)) return(task_state,",
"to the appliance. Exception message: {0}\".format(e)) except Exception as e: raise Exception(\"There was",
"task polling. Exception message: {0}\".format(e)) # delete and recreate of the session if",
"**other_properties) elif request_type == \"PUT\": r = self.sess.put(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties)",
": a response object from a Requests call. Return ------ tuple containing: task_state:",
"string \"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []): mac_address = network.get('macAddress')",
"administrator login is not successful, an error is raised. The administrator data is",
"except Exception as e: raise Exception(\"There was an issue with the HTTP Call",
"self.fqdn = appliance_name if appliance_dhcp_ip_address: self.base_url = \"https://\" + appliance_dhcp_ip_address else: self.base_url =",
"i in data['results'][0]['msg']: for j in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) # Closing file vm_network_json_file.close() return",
"The calling function may not know that this will return a 202. success",
"Parameters ---------- service_access (optional): str \"yes\" will accept service access \"no\" will not",
"dict A dictionary of extra properties that we can give to the Python",
"ipv4_name_servers = self.get_ipv4_name_servers() # Only ipv6 with DHCP is supported, will add static",
"return self._secure_header except ValueError as e: raise Exception('Failure to get a JSON value",
"secure=False, payload=logon_payload) if not logon_success: raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code,",
"response object from a call to the network page. \"\"\" url = \"/rest/appliance/configuration/time-locale\"",
"DHCP is supported, will add static at some point later. if ipv6_type !=",
"defined, we can use it over and over again for the duration of",
"safe_json_result.get('errorCode', 'Error'), 'task_status': safe_json_result.get('details', str(safe_json_result))} return (success, r, safe_json_result, polling_results) except requests.exceptions.RequestException as",
"network['ipv6Type'] = \"UNCONFIGURE\" networks.append(network) if use_i3s_fts: network['ipv6Type'] = \"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] = False network['virtIpv4Addr']",
"get headers. Exception message: {0}\".format(e)) except Exception as e: raise Exception(\"There was an",
"logging.info(\"Setting fqdn for the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] = networks networking_data.pop('serverCertificate', None) payload = networking_data",
"fails to query the network interface to get the base for the payload,",
"fails, then we attempt to login with the administrator password. If successful, we",
"self.sess.get(full_url, verify=False, headers=head, timeout=timeout, **other_properties) elif request_type == \"DELETE\": r = self.sess.delete(full_url, verify=False,",
"ipv6_type != \"DHCP\": ipv6_type = \"UNCONFIGURE\" payload = {\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\": \"DHCP\",",
"{0}'.format(<PASSWORD>)) else: raise Exception('change_administrator_password failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4,",
"---------- service_access (optional): str \"yes\" will accept service access \"no\" will not allow",
"google.com\" ping_command = ['ping', param, '1', i] ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode",
"get_ipv4_name_servers(self): \"\"\"Request the list of dns ipv4 name servers. Use the first one",
"# From my reading of the documentation, this is not consistant with the",
"name servers. Use the first one found in applianceNetworks collection. If the appliance",
"False (success, response, rjson, polling_results) = self.appliance_request(request_type='POST', url=url, secure=True, payload=payload, poll=poll) # Reset",
"point only works for the initial administrator password change. url = '/rest/users/changePassword' payload",
"status (anything outside of the 100 or 200 range), an error is raised.",
"of ipv4 name servers: list \"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks',",
"= None try: logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree = self.sess.get(full_rest_url + \"?view=tree\", verify=False, headers=self.get_secure_headers(),",
"other_properties={'stream': True} poll : boolean If false, polling tasks will return immiedtaly -",
"elif request_type == \"DELETE\": r = self.sess.delete(full_url, verify=False, headers=head, timeout=timeout, **other_properties) else: raise",
"the Task Tracker mechanism. I have brought this to the attention # of",
"For Example: Unknown, Running, Terminated, Error, Warning, Completed. ''' # network-interfaces is a",
"(optional): boolean True requests data adding a header that includes authentiation information. False",
"\"Completed\": success = True else: success = False if not success: logging.error(json.dumps(rjson, sort_keys=True,",
"separators=(',', ': ')))) def accept_eula(self, service_access=\"yes\", tries=3, retry_interval=5): thistry = 1 while True:",
"network[\"aliasDisabled\"] = True network[\"overrideIpv4DhcpDnsServers\"] = False if network[\"app1Ipv4Addr\"] == network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] = ''",
"retry if the appliance goes offline (e.g. first time setup) self.sess = requests.Session()",
"# Default to the minimal version number that implements all the requirements that",
"'Starting']: if time.time() >= start_time + polling_call_timeout_sec: raise Exception('Task Polling did not respond",
"ipv6address = readIPV6FromFile() pingableipv6 = ping(ipv6address) ra = FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay,",
"accepted. This only needs to occur once. Additional calls will not change the",
"accept service access \"no\" will not allow service access empty value will default",
"Not clear why this conditions fails to query the network interface to get",
"timeout=rest_call_timeout_sec) except requests.exceptions.RequestException as e: raise Exception(\"There was an issue connecting to the",
"try: if request_type == \"POST\": r = self.sess.post(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties)",
"passed in. If a ova_ip is passed in then we will lose connection",
"host name is valid. \"\"\" operating_sys = platform.system().lower() for i in hosts: param",
"ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server setting was successful\") def poll_for_task(self, calling_url, response): '''Helper method",
"data adding a header that includes authentiation information. False requests data without authentication",
"or PUT calls, to be serialized into JSON. other_properties (optional): dict A dictionary",
"a 202. success = False if r.status_code == 202: if not poll: return",
"= [str(ntpserver)] # use the defined NTP server and only it. (ntp_success, _,",
"name servers: list \"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []): ipv4_name_servers",
"vm_network_json_file = open('vm_network.json',) data = json.load(vm_network_json_file) # Iterating through the json list for",
"this set of conditional branches. Since both get_mac and get_ipv4_name_servers # use calls",
"servers. Use the first one found in applianceNetworks collection. If the appliance returns",
"the MAC address from the appliance. Use the first one found in applianceNetworks",
"{0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server setting was successful\") def",
"**other_properties) elif request_type == \"GET\": r = self.sess.get(full_url, verify=False, headers=head, timeout=timeout, **other_properties) elif",
"{0} seconds to wait for appliance to stabilize\".format(post_eula_delay)) time.sleep(post_eula_delay) ra.change_administrator_password() ra.first_time_setup(ntpserver, use_static_ip=False, use_i3s_fts=False,",
"# This will embed another REST process using POST inside the generation of",
"address of the ntpserver. :return: :raises: Exception, Exception \"\"\" time_locale_url = \"/rest/appliance/configuration/time-locale\" #",
"raise Exception(\"There was an issue with the HTTP Call. Exception message: {0}\".format(e)) def",
"did not respond within {0} seconds. Time out and exit. Originating request on",
"the first one found in applianceNetworks collection. If the appliance returns an error",
"or 200 range), an error is raised. Parameters ---------- none Return ------ list",
"to login with the administrator password. If successful, we log a message and",
"== network[\"virtIpv4Addr\"]: network[\"virtIpv4Addr\"] = '' network[\"app1Ipv4Addr\"] = ova_ip network[\"app2Ipv4Addr\"] = '' else: raise",
"successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True)) def readIPV6FromFile(self): ipv6address = [] vm_network_json_file = open('vm_network.json',) data",
"if not secure: head = self._header else: head = self.get_secure_headers() head = dict(head.items()",
"logon, the administrator's password has to be changed from the default value. The",
"return json_response def get_time_locale_data(self): \"\"\"Request the networking information from the appliance. If the",
"adap) if r_tree: r_treejson = r_tree.json() task_resource = r_treejson.get('resource') task_state = task_resource.get('taskState') task_status",
"time.time() try: logging.debug(\"Starting polling the rest task {0}.\".format(url)) already_reset_session = False while task_state",
"after setting up the networking. if ova_ip and success: self.base_url = \"https://\" +",
"# area and the lack of documented test cases, this seems to be",
"appliance_name self.use_ip = use_ip # create a persistant session so that we can",
"is None: raise Exception('Auth token for the header is undefined. No Session ID",
"# This is the later data model, where the time server and locale",
"+ extra_headers.items()) full_url = self.base_url + url logging.debug(\"Preparing HTTP {0} request.\".format(request_type)) logging.debug(\"Preparing URL:",
"'Pending', 'Starting']: if time.time() >= start_time + polling_call_timeout_sec: raise Exception('Task Polling did not",
"self._secure_header = self._header.copy() self._secure_header['Auth'] = safe_json.get('sessionID') if self._secure_header['Auth'] is None: raise Exception('Auth token",
"not consistant with the Task Tracker mechanism. I have brought this to the",
"new # address and then poll for the task. if ova_ip: poll =",
"accepted values are: \"POST\", \"PUT\", \"GET\", \"DELETE\" Any other value will raise an",
"persistant session so that we can retry if the appliance goes offline (e.g.",
"Iterating through the json list for i in data['results'][0]['msg']: for j in data['results'][0]['msg'][i]['ipv6']:",
"The changePassword REST end point only works for the initial administrator password change.",
"does so we follow network[\"aliasDisabled\"] = True network[\"overrideIpv4DhcpDnsServers\"] = False if network[\"app1Ipv4Addr\"] ==",
"100, it does not set DNS. If the appliance returns an error status",
"{1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else: raise Exception( 'time-locale setting failure. Polling State: {0}.",
"time server and locale are set via their own API # This will",
"= deepcopy(old_network[\"time\"]) # This is the later data model, where the time server",
"from the response. Status: {0}.'.format(r.status_code)) except: raise Exception('Failure to access the sessionID from",
"(optional): str \"yes\" will accept service access \"no\" will not allow service access",
"network in json_answer.get('applianceNetworks', []): mac_address = network.get('macAddress') if mac_address: logging.info('MAC Address is: {0}'.format(mac_address))",
"already occurred. logging.warning('EULA does not need to be saved.') else: logging.debug('Call EULA Acceptance",
"'.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else: raise Exception( 'time-locale setting failure. Polling State: {0}. Polling",
"raise Exception('Could not read the task to poll. Originating request on URL: {0}.'.format(calling_url))",
"of errors place them in log output and append to status message for",
"ipv6address def ping(hosts): \"\"\" Returns True if host (str) responds to a ping",
"does not need to be saved.') else: logging.debug('Call EULA Acceptance with enable service",
"Exception as e: logging.exception(e) if thistry >= tries: raise e time.sleep(retry_interval) thistry +=",
"= requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) if r_tree: r_treejson = r_tree.json() task_resource =",
"HTTP {0} request.\".format(request_type)) logging.debug(\"Preparing URL: {0}.\".format(full_url)) logging.debug(\"Preparing Headers: {0}.\".format(head)) logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload))) polling_results",
"# Not clear why this conditions fails to query the network interface to",
"= readIPV6FromFile() pingableipv6 = ping(ipv6address) ra = FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False,",
"appliance_dhcp_ip_address else: self.base_url = \"https://\" + appliance_name self.use_ip = use_ip # create a",
"a response object from a Requests call. Return ------ tuple containing: task_state: str.",
"of the session if it loses connection. Changes in IP address, FQDN, etc",
"raise an error. url: str url location of the REST call. This method",
"change the status of the EULA nor the status of the service access.",
"!= virtIpv4Addr\") network[\"ipv6Type\"] = \"UNCONFIGURE\" payload = networking_data elif use_static_ip: networking_data = self.get_networking_data()",
"so don't set it. time_locale_settings[\"ntpServers\"] = [str(ntpserver)] # use the defined NTP server",
"did not return a JSON value. polling_results: dict. dictionary with two values, task_state",
"{0}.\".format(url)) already_reset_session = False while task_state in ['Running', 'New', 'Pending', 'Starting']: if time.time()",
"else: raise Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First",
"return mac_address raise Exception('MAC Address is not defined') def get_ipv4_name_servers(self): \"\"\"Request the list",
"{0}.\".format(json.dumps(payload))) polling_results = {} try: if request_type == \"POST\": r = self.sess.post(full_url, verify=False,",
"a response object from a Requests call. safe_json_results: the JSON returned from the",
"Exception message: {0}\".format(e)) def accept_eula_once(self, service_access=\"yes\"): \"\"\"On initial communication with the appliance, the",
"to a ping (ICMP) request even if the host name is valid. \"\"\"",
"networking_data elif use_static_ip: networking_data = self.get_networking_data() networks = [] for network in networking_data['applianceNetworks']:",
"'Wait until the operation completes' in ntp_polling_results.get(\"task_status\"): raise Exception( 'time-locale setting failed. Polling",
"True elif r.status_code < 300: success = True else: polling_results = {'task_state': safe_json_result.get('errorCode',",
"network page. \"\"\" url = '/rest/appliance/network-interfaces' (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url,",
"attention # of the atlas team. # # there are now at least",
"= response.json().get('uri') if url is None: raise Exception('Could not read the task to",
"= self.poll_for_task(url, r) polling_results = {'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\":",
"and then use the fqdn to make sure the # networking setup task",
"module. The dictionary is unpacked and added to Request. For example: other_properties={'stream': True}",
"{1}'.format(r.status_code, r.json())) def appliance_request(self, request_type, url, secure=True, payload=None, other_properties={}, extra_headers={}, poll=True, timeout=None): \"\"\"Helper",
"self._header.copy() self._secure_header['Auth'] = safe_json.get('sessionID') if self._secure_header['Auth'] is None: raise Exception('Auth token for the",
"for failover setups timeout: None or integer Defaults to rest_call_timeout_sec if 'None' or",
"call requires task polling. \"\"\" if timeout is None: timeout = rest_call_timeout_sec if",
"request_type == \"PUT\": r = self.sess.put(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type",
"State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else: raise Exception('first_time_setup failure. Polling State:",
"of the task. For Example: Unknown, Running, Terminated, Error, Warning, Completed. ''' #",
"where the time server and locale are set via their own API #",
"return (str(i)+str('%ens160')) if __name__ == '__main__': post_eula_delay = '10' ntpserver = \"10.10.10.10\" ipv6address",
"of the system with this string. secure (optional): boolean True requests data adding",
"moved to a default in the datastore. Parameters ---------- appliance_name : str fully",
"+ polling_call_timeout_sec: raise Exception('Task Polling did not respond within {0} seconds. Time out",
"\"device\": \"eth0\", \"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\": \"\", \"ipv4Gateway\": None, \"confOneNode\": True, \"activeNode\":",
"utilized. Exceptions will also be raised if the appliance cannot be contacted. If",
"are deployed as DHCP but, # need to be configured as static since",
"task. if ova_ip: poll = False (success, response, rjson, polling_results) = self.appliance_request(request_type='POST', url=url,",
"is utilized. Exceptions will also be raised if the appliance cannot be contacted.",
"we attempt to login with the administrator password. If successful, we log a",
"If the administrator login is not successful, an error is raised. The administrator",
"str. State of the task. For Example: Unknown, Running, Terminated, Error, Warning, Completed.",
"a POST to do the network setup. self.set_time_server_and_locale(ntpserver) poll = True # Do",
"place them in log output and append to status message for e in",
"# Eventually we may need version overrides at each REST call. if override_version:",
"self._secure_header = {} def get_secure_headers(self): \"\"\"Helper method to appliance_request(). Gives header information required",
"raise Exception(\"There was an issue connecting to the appliance to get headers. Exception",
"our time is not necessarily the NTP time, so don't set it. time_locale_settings[\"ntpServers\"]",
"use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Creates networking for the appliance. Configures",
"the REST call. This method concatenates https:// and the fully qualified domain name",
"polling_results: dict. dictionary with two values, task_state and task_status. Both are populated whenever",
"use calls to get_networking_data, this seems poorly designed, but given how complex the",
"Call. Exception message: {0}\".format(e)) def accept_eula_once(self, service_access=\"yes\"): \"\"\"On initial communication with the appliance,",
"task_status} if task_state == \"Completed\": success = True else: success = False if",
"secure=True, payload=None, other_properties={}, extra_headers={}, poll=True, timeout=None): \"\"\"Helper method to call HTTP requests. An",
"\"Completed\": success = True elif self.use_ip and task_state == \"Warning\": #This is required",
"True else: polling_results = {'task_state': safe_json_result.get('errorCode', 'Error'), 'task_status': safe_json_result.get('details', str(safe_json_result))} return (success, r,",
"'Content-Type': 'application/json'} self._secure_header = {} def get_secure_headers(self): \"\"\"Helper method to appliance_request(). Gives header",
"response. Status: {0}.'.format(r.status_code)) except: raise Exception('Failure to access the sessionID from the response.",
"{0}.'.format(r.status_code)) except: raise Exception('Failure to access the sessionID from the response. Status: {0}.",
"valid hostname then it will #the warning for post-validation status. success = True",
"change to the service access is required, see the function change_service_access() If the",
"to status message for e in task_errors: logging.error(e) task_status += \";\" + \";\".join([str(e)",
"else: appliance_mac_address = self.get_mac() ipv4_name_servers = self.get_ipv4_name_servers() # Only ipv6 with DHCP is",
"(str(i)+str('%ens160')) if __name__ == '__main__': post_eula_delay = '10' ntpserver = \"10.10.10.10\" ipv6address =",
"def accept_eula_once(self, service_access=\"yes\"): \"\"\"On initial communication with the appliance, the end user service",
"needs to occur once. Additional calls will not change the status of the",
"separators=(',', ': '))) if 'Wait until the operation completes' in ntp_polling_results.get(\"task_status\"): raise Exception(",
"r_treejson = r_tree.json() task_resource = r_treejson.get('resource') task_state = task_resource.get('taskState') task_status = task_resource.get('taskStatus', '')",
"headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except Exception as e: logging.exception(\"FTS get failed: \" + str(e)) if",
"issue with the HTTP Call. Exception message: {0}\".format(e)) def accept_eula_once(self, service_access=\"yes\"): \"\"\"On initial",
"sessionID from the response. Status: {0}. JSON: {1}'.format(r.status_code, r.json())) def appliance_request(self, request_type, url,",
"conditions fails to query the network interface to get the base for the",
"import requests import json import logging import time from copy import deepcopy import",
"\"\"\"Request the MAC address from the appliance. Use the first one found in",
"at each REST call. if override_version: self.api_version = override_version else: self.api_version = 120",
"defaults in True payload (optional): dict Python object payload for POST or PUT",
"of the execution/completion status task_status: str. State of the task. For Example: Unknown,",
"ntp_polling_results) = self.appliance_request(request_type='POST', url=time_locale_url, secure=True, payload=time_locale_settings) if not ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4, separators=(',',",
"try {}\".format(thistry)) try: self.accept_eula_once(service_access=service_access) return except Exception as e: logging.exception(e) if thistry >=",
"REST call. Poll until the task is complete or error. Adds to the",
"IP address and set the overrideIpv4DhcpDnsServers value to False. \"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\": False",
"= 10 * 60 sec_between_polling = 10 class FirstTimeSetUp(object): def __init__(self, appliance_name, use_ip=False,",
"address and then poll for the task. if ova_ip: poll = False (success,",
"= {'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\": success = True else:",
"header information required by the appliance with authentication information. Return ------ _secure_header: dict.",
"retries to do in HTTP session. appliance_dhcp_ip_address : str appliance dhcp ip address,",
"of the 100 or 200 range), an error is raised. \"\"\" url =",
": string The URL that was called in appliance_request. response : a response",
"Requests call. safe_json_results: the JSON returned from the HTTP request. None if the",
"the time definition is not part of the network-interfaces JSON, it is set",
"The default version string (determined by program name) can be overridden. Currently only",
"No Session ID available. Status: {0}.'.format(r.status_code)) return self._secure_header except ValueError as e: raise",
"Polling did not respond within {0} seconds. Time out and exit. Originating request",
"done for OVA's that are deployed as DHCP but, # need to be",
"= self.get_networking_data() if \"time\" in old_network: payload[\"time\"] = deepcopy(old_network[\"time\"]) # This is the",
"area and the lack of documented test cases, this seems to be the",
"(Optional): int Number of retries to do in HTTP session. appliance_dhcp_ip_address : str",
"failure. Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server setting",
"in task_errors: logging.error(e) task_status += \";\" + \";\".join([str(e) for e in task_errors]) logging.debug(\"Percent",
"ipv6 with DHCP is supported, will add static at some point later. if",
"return json_response def set_time_server_and_locale(self, ntpserver): \"\"\" If the time definition is not part",
"the header: # '/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale' # Go to checking for response in",
">= start_time + polling_call_timeout_sec: raise Exception('Task Polling did not respond within {0} seconds.",
"containing X-API-Verions, Content-Type, and Auth. The Auth parameter value is a sessionID. \"\"\"",
"import time from copy import deepcopy import platform # For getting the operating",
"'windows' else False # Building the command. Ex: \"ping -c 1 google.com\" ping_command",
"an issue with the HTTP Call. Exception message: {0}\".format(e)) def accept_eula_once(self, service_access=\"yes\"): \"\"\"On",
"the task tree for {0}\".format(full_rest_url)) return(task_state, task_status) except ValueError as e: raise Exception('Error",
"name is valid. \"\"\" operating_sys = platform.system().lower() for i in hosts: param =",
"None if the request did not return a JSON value. polling_results: dict. dictionary",
"# if version is passed in, use that. Else use the default for",
"range), an error is raised. Parameters ---------- none Return ------ a response object",
"a persistant session so that we can retry if the appliance goes offline",
"r_tree: r_treejson = r_tree.json() task_resource = r_treejson.get('resource') task_state = task_resource.get('taskState') task_status = task_resource.get('taskStatus',",
"polling_results) = self.appliance_request(request_type='POST', url=url, secure=True, payload=payload, poll=poll) # Reset the base url to",
"value for override_version. Ideally, this computation should be moved to a default in",
"not part of the network-interfaces JSON, it is set via an independent REST",
"to do in HTTP session. appliance_dhcp_ip_address : str appliance dhcp ip address, will",
"\"\"\" If the time definition is not part of the network-interfaces JSON, it",
"a change to the service access is required, see the function change_service_access() If",
"fqdn to make sure the # networking setup task completes successfully. This needs",
"time is not necessarily the NTP time, so don't set it. time_locale_settings[\"ntpServers\"] =",
"\"\"\" url = '/rest/appliance/network-interfaces' if ova_ip: networking_data = self.get_networking_data() network = networking_data['applianceNetworks'][0] network[\"hostname\"]",
"Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def get_mac(self):",
"(EULA) must be accepted. This only needs to occur once. Additional calls will",
"add static at some point later. if ipv6_type != \"DHCP\": ipv6_type = \"UNCONFIGURE\"",
"don't set it. time_locale_settings[\"ntpServers\"] = [str(ntpserver)] # use the defined NTP server and",
"via an independent REST endpoint. :param ntpserver: IP address of the ntpserver. :return:",
"call fails, then we attempt to login with the administrator password. If successful,",
"default for the program # Default to the minimal version number that implements",
"appliance_mac_address, \"hostname\": self.fqdn, \"device\": \"eth0\", \"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\": \"\", \"ipv4Gateway\": None,",
"'.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else: raise Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"),",
"logon_payload = {\"userName\": admin_user, \"password\": <PASSWORD>} (logon_success, _, _, _) = self.appliance_request(request_type='POST', url=logon_url,",
"{0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) else: raise Exception('first_time_setup failure. Polling State: {0}.",
"the network interface to get the base for the payload, but # we",
"the network page. \"\"\" url = '/rest/appliance/network-interfaces' (success, resp, json_response, _) = self.appliance_request(request_type='GET',",
"def first_time_setup(self, ntpserver, use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Creates networking for",
"request. None if the request did not return a JSON value. polling_results: dict.",
"Exception('Failure to get a JSON value from the response. Status: {0}.'.format(r.status_code)) except: raise",
"service access={0}'.format(service_access)) url = '/rest/appliance/eula/save' payload = {\"supportAccess\": service_access} (save_success, save_resp, save_json_response, _)",
"exception will be raised if an unknown value for request_type is utilized. Exceptions",
"than POST, PUT, or GET. request_type: {0}. url: {1}\".format(request_type, url)) try: safe_json_result =",
"networking_data = self.get_networking_data() networks = [] for network in networking_data['applianceNetworks']: if network[\"ipv4Type\"] ==",
"success: logging.error(json.dumps(rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until the operation completes'",
"ValueError as e: raise Exception('Error getting the JSON results from the task. Originating",
"changed from the default value. The call to the administrator password change is",
"Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def get_mac(self): \"\"\"Request the MAC",
"appliance returns an error status (anything outside of the 100 or 200 range),",
"param, '1', i] ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode if success == 0:",
"will add static at some point later. if ipv6_type != \"DHCP\": ipv6_type =",
"\"newPassword\": <PASSWORD>} (success, resp, json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if success:",
"if 'None' or unspecified Return ------ return (success, r, safe_json_result, polling_results) A tuple",
"as e: raise Exception(\"There was an issue connecting to the appliance to get",
"sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until the operation completes' in polling_results.get(\"task_status\"):",
"{0}. JSON Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def accept_eula(self, service_access=\"yes\",",
"failed. Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) else: raise Exception(",
"task_resource = r_treejson.get('resource') task_state = task_resource.get('taskState') task_status = task_resource.get('taskStatus', '') task_errors = task_resource.get('taskErrors',",
"be saved.') else: logging.debug('Call EULA Acceptance with enable service access={0}'.format(service_access)) url = '/rest/appliance/eula/save'",
"get call, response was not set\") logging.debug(\"Unable to get the task tree for",
"return (True, r, safe_json_result, {'task_state': 'N/A', 'task_status': 'N/A'}) (task_state, task_status) = self.poll_for_task(url, r)",
"if a ova_ip is passed in. If a ova_ip is passed in then",
"\"/rest/appliance/configuration/time-locale\" (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise",
"values: success: bool. A True/False value. True indicates that the status_code was under",
"logging.exception(e) if thistry >= tries: raise e time.sleep(retry_interval) thistry += 1 def change_administrator_password(self):",
"time.sleep(retry_interval) thistry += 1 def change_administrator_password(self): \"\"\"On initial logon, the administrator's password has",
"= \"STATIC\" network[\"searchDomains\"] = None # this is what UI does so we",
"secure=False, payload=payload) if success: logging.info('Administrator password change was accepted.') elif resp.status_code == 400:",
"URL: {0}. Exception: {1}'.format(calling_url, e)) except Exception as e: raise Exception('Error in polling",
"except Exception as e: raise Exception('Error in polling for the task. Originating request",
"request_type is utilized. Exceptions will also be raised if the appliance cannot be",
"summary of the execution/completion status task_status: str. State of the task. For Example:",
"only good for that user (administrator), 24 hours, and until the next reboot.",
"the appliance. Configures the appliance as DHCP. The appliance queries itself to define",
"FirstTimeSetUp(object): def __init__(self, appliance_name, use_ip=False, override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False, use_one_ip=False, ipv6_type=None, ova_ip=None,",
"to do the network setup. self.set_time_server_and_locale(ntpserver) poll = True # Do not poll",
"r = self.sess.put(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"GET\": r",
"------ _secure_header: dict. Dictionary containing X-API-Verions, Content-Type, and Auth. The Auth parameter value",
"'/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale' # Go to checking for response in the header, if",
"get the task tree for {0}\".format(full_rest_url)) return(task_state, task_status) except ValueError as e: raise",
"an asynchronous REST call. Poll until the task is complete or error. Adds",
"False requests data without authentication information no value defaults in True payload (optional):",
"= True else: polling_results = {'task_state': safe_json_result.get('errorCode', 'Error'), 'task_status': safe_json_result.get('details', str(safe_json_result))} return (success,",
"overridden. Currently only accepting values of 100, 199, and 200. retries (Optional): int",
"may not know that this will return a 202. success = False if",
"\"\"\" if timeout is None: timeout = rest_call_timeout_sec if not secure: head =",
"information no value defaults in True payload (optional): dict Python object payload for",
"data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"GET\": r = self.sess.get(full_url, verify=False, headers=head, timeout=timeout,",
"occurred. logging.warning('EULA does not need to be saved.') else: logging.debug('Call EULA Acceptance with",
"JSON results from the task. Originating request on URL: {0}. Exception: {1}'.format(calling_url, e))",
"data is pulled from the dictionary in this file. This needs to be",
"the sessionID from the response. Status: {0}. JSON: {1}'.format(r.status_code, r.json())) def appliance_request(self, request_type,",
"through the json list for i in data['results'][0]['msg']: for j in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j)",
"No authentication on the appliance is required. Parameters ---------- service_access (optional): str \"yes\"",
"and until the next reboot. if self._secure_header: return self._secure_header payload = {\"userName\": \"Administrator\",",
"r.json() self._secure_header = self._header.copy() self._secure_header['Auth'] = safe_json.get('sessionID') if self._secure_header['Auth'] is None: raise Exception('Auth",
"(anything outside of the 100 or 200 range), an error is raised. Parameters",
"call. safe_json_results: the JSON returned from the HTTP request. None if the request",
"= ova_ip network[\"app2Ipv4Addr\"] = '' else: raise Exception(\"Impossible happened: app1Ipv4Addr != virtIpv4Addr\") network[\"ipv6Type\"]",
"up the networking. if ova_ip and success: self.base_url = \"https://\" + self.fqdn (task_state,",
"needs to be moved to a more formal location. Parameters ---------- none \"\"\"",
"with the HTTP Call. Exception message: {0}\".format(e)) def accept_eula_once(self, service_access=\"yes\"): \"\"\"On initial communication",
"= True elif r.status_code < 300: success = True else: polling_results = {'task_state':",
"\"activeNode\": 1 } ], } # Not clear why this conditions fails to",
"hours, and until the next reboot. if self._secure_header: return self._secure_header payload = {\"userName\":",
"Query for current time-locale setting. time_locale_settings = self.get_time_locale_data() # Exception will be raised",
"time definition is not part of the network-interfaces JSON, it is set via",
"logging.info(\"First time setup was successful\") logging.debug(json.dumps(self.get_networking_data(), indent=2, sort_keys=True)) def readIPV6FromFile(self): ipv6address = []",
"pingableipv6 = ping(ipv6address) ra = FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None,",
"False if not success: logging.error(json.dumps(rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until",
"and success: self.base_url = \"https://\" + self.fqdn (task_state, task_status) = self.poll_for_task(url, response) polling_results",
"\"DHCP\": ipv6_type = \"UNCONFIGURE\" payload = {\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\": \"DHCP\", \"ipv6Type\": ipv6_type,",
"The URL that was called in appliance_request. response : a response object from",
"data model, where the time server and locale are set via their own",
"= \"https://\" + self.fqdn (task_state, task_status) = self.poll_for_task(url, response) polling_results = {'task_state': task_state,",
"own API # This will embed another REST process using POST inside the",
"raised if an unknown value for request_type is utilized. Exceptions will also be",
"is supported, will add static at some point later. if ipv6_type != \"DHCP\":",
"e: logging.exception(e) if thistry >= tries: raise e time.sleep(retry_interval) thistry += 1 def",
"= self.fqdn network[\"domainName\"] = self.fqdn.split(\".\", 1)[1] network['ipv4Type'] = \"STATIC\" network[\"searchDomains\"] = None #",
"API-Version for REST calls. The version can be overridden by passing in a",
"initial administrator password change. url = '/rest/users/changePassword' payload = {\"userName\": initial_admin, \"oldPassword\": <PASSWORD>,",
"network-interfaces JSON, it is set via an independent REST endpoint. :param ntpserver: IP",
"= self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_time_locale_data call failed. Status: {0}.",
"{0}\".format(r_treejson)) else: logging.debug(\"Exception during get call, response was not set\") logging.debug(\"Unable to get",
"task_state == \"Completed\": success = True else: success = False if not success:",
"Returns True if host (str) responds to a ping request. Remember that a",
"------ mac address: string \"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []):",
"\"UNCONFIGURE\" network[\"overrideIpv4DhcpDnsServers\"] = False network['virtIpv4Addr'] = None networks.append(network) appliance_domain_name = self.fqdn.split(\".\", 1)[1] if",
"(optional): dict Python object payload for POST or PUT calls, to be serialized",
"the request did not return a JSON value. polling_results: dict. dictionary with two",
"{}\".format(thistry)) try: self.accept_eula_once(service_access=service_access) return except Exception as e: logging.exception(e) if thistry >= tries:",
"\"\", \"ipv4Gateway\": None, \"confOneNode\": True, \"activeNode\": 1 } ], } # Not clear",
"e: raise Exception('Failure to get a JSON value from the response. Status: {0}.'.format(r.status_code))",
"to the network page. \"\"\" url = '/rest/appliance/network-interfaces' (success, resp, json_response, _) =",
"the network page. \"\"\" url = \"/rest/appliance/configuration/time-locale\" (success, resp, json_response, _) = self.appliance_request(request_type='GET',",
"payload[\"time\"] = deepcopy(old_network[\"time\"]) # This is the later data model, where the time",
"'.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\"))) logging.info(\"NTP server setting was successful\") def poll_for_task(self, calling_url, response): '''Helper",
"JSON. Poor consistency in # implementations and inconsistent with REST principles. url =",
"the task if a ova_ip is passed in. If a ova_ip is passed",
"else: polling_results = {'task_state': safe_json_result.get('errorCode', 'Error'), 'task_status': safe_json_result.get('details', str(safe_json_result))} return (success, r, safe_json_result,",
"+ '.' + appliance_domain_name logging.info(\"Setting fqdn for the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] = networks networking_data.pop('serverCertificate',",
"can be overridden. Currently only accepting values of 100, 199, and 200. retries",
"part of the network-interfaces JSON, it is set via an independent REST endpoint.",
"is None: raise Exception('Could not read the task to poll. Originating request on",
"# Do not poll for the task if a ova_ip is passed in.",
"a DNS Server IP address and set the overrideIpv4DhcpDnsServers value to False. \"ipv4NameServers\":",
"appliance_name, use_ip=False, override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Constructor method",
"header that includes authentiation information. False requests data without authentication information no value",
"State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First time setup was successful\") logging.debug(json.dumps(self.get_networking_data(),",
"be done for OVA's that are deployed as DHCP but, # need to",
"timeout=None): \"\"\"Helper method to call HTTP requests. An exception will be raised if",
"= networking_data['applianceNetworks'][0] network[\"hostname\"] = self.fqdn network[\"domainName\"] = self.fqdn.split(\".\", 1)[1] network['ipv4Type'] = \"STATIC\" network[\"searchDomains\"]",
"use it over and over again for the duration of its life. #",
"')))) def get_mac(self): \"\"\"Request the MAC address from the appliance. Use the first",
"why this conditions fails to query the network interface to get the base",
"Gives header information required by the appliance with authentication information. Return ------ _secure_header:",
"HTTP requests. An exception will be raised if an unknown value for request_type",
"network[\"hostname\"] + '.' + appliance_domain_name logging.info(\"Setting fqdn for the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] = networks",
"the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] = networks networking_data.pop('serverCertificate', None) payload = networking_data else: appliance_mac_address =",
"if it loses connection. Changes in IP address, FQDN, etc can make use",
"# Once _secure_header is defined, we can use it over and over again",
"'') task_errors = task_resource.get('taskErrors', None) if task_errors: # in case of errors place",
"code is in this # area and the lack of documented test cases,",
"address and set the overrideIpv4DhcpDnsServers value to False. \"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\": False If",
"timeout=timeout, **other_properties) elif request_type == \"PUT\": r = self.sess.put(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout,",
"operating_sys == 'windows' else False # Building the command. Ex: \"ping -c 1",
"sort_keys=True, indent=4, separators=(',', ': ')))) def get_mac(self): \"\"\"Request the MAC address from the",
"def accept_eula(self, service_access=\"yes\", tries=3, retry_interval=5): thistry = 1 while True: logging.info(\"accept_eula try {}\".format(thistry))",
"the base url to the the fqdn for any subsequent rest actions and",
"None # this is what UI does so we follow network[\"aliasDisabled\"] = True",
"logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree = self.sess.get(full_rest_url + \"?view=tree\", verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except Exception",
"object from a Requests call. safe_json_results: the JSON returned from the HTTP request.",
"mac_address = network.get('macAddress') if mac_address: logging.info('MAC Address is: {0}'.format(mac_address)) return mac_address raise Exception('MAC",
"\"\"\" url = '/rest/appliance/network-interfaces' (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if",
"If secure=True, this function depends on get_secure_headers(). Parameters ---------- request_type: str accepted values",
"and the lack of documented test cases, this seems to be the safest",
"_, ntp_rjson, ntp_polling_results) = self.appliance_request(request_type='POST', url=time_locale_url, secure=True, payload=time_locale_settings) if not ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True,",
"in this # area and the lack of documented test cases, this seems",
"+ appliance_dhcp_ip_address else: self.base_url = \"https://\" + appliance_name self.use_ip = use_ip # create",
"e: raise Exception(\"There was an issue with the HTTP Call to get headers.",
"e: logging.exception(\"FTS get failed: \" + str(e)) if already_reset_session: raise Exception(\"There was an",
"is not defined') def get_networking_data(self): \"\"\"Request the networking information from the appliance. If",
"tree for {0}\".format(full_rest_url)) return(task_state, task_status) except ValueError as e: raise Exception('Error getting the",
"self.accept_eula_once(service_access=service_access) return except Exception as e: logging.exception(e) if thistry >= tries: raise e",
"embed another REST process using POST inside the generation of a POST to",
"Exception('first_time_setup failure. Polling State: {0}. Polling Status: {1}. '.format(polling_results.get(\"task_state\"), polling_results.get(\"task_status\"))) logging.info(\"First time setup",
"= '-n' if operating_sys=='windows' else '-c' shell_needed = True if operating_sys == 'windows'",
"virtIpv4Addr\") network[\"ipv6Type\"] = \"UNCONFIGURE\" payload = networking_data elif use_static_ip: networking_data = self.get_networking_data() networks",
"this is not consistant with the Task Tracker mechanism. I have brought this",
"to the orginal location after the POST command to set the networking. Instead,",
"indent=4, separators=(',', ': ')))) logging.warning('Administrator password has already been changed. Password is {0}'.format(<PASSWORD>))",
"networking_data else: appliance_mac_address = self.get_mac() ipv4_name_servers = self.get_ipv4_name_servers() # Only ipv6 with DHCP",
"networks networking_data.pop('serverCertificate', None) payload = networking_data else: appliance_mac_address = self.get_mac() ipv4_name_servers = self.get_ipv4_name_servers()",
"task_state and task_status. Both are populated whenever the call requires task polling. \"\"\"",
"be moved to a default in the datastore. Parameters ---------- appliance_name : str",
"\"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []): mac_address = network.get('macAddress') if",
"called in appliance_request. response : a response object from a Requests call. Return",
"network-interfaces returning a object of type TaskResourceV2, this end point returns Void. #",
"model, where the time server and locale are set via their own API",
"if mac_address: logging.info('MAC Address is: {0}'.format(mac_address)) return mac_address raise Exception('MAC Address is not",
"headers=head, timeout=timeout, **other_properties) else: raise Exception(\"RestAppliance attempted to call an http request other",
"poll_for_task(self, calling_url, response): '''Helper method to appliance_request(). Status Response 202 indicates an asynchronous",
"in json_answer.get('applianceNetworks', []): mac_address = network.get('macAddress') if mac_address: logging.info('MAC Address is: {0}'.format(mac_address)) return",
"the rest task {0}.\".format(url)) already_reset_session = False while task_state in ['Running', 'New', 'Pending',",
"code: {0}.\".format(r.status_code)) logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result)) # 202 status codes indicate a task that",
"(success, r, safe_json_result, polling_results) A tuple with these values: success: bool. A True/False",
"is raised. \"\"\" url = '/rest/appliance/network-interfaces' if ova_ip: networking_data = self.get_networking_data() network =",
"accept_eula(self, service_access=\"yes\", tries=3, retry_interval=5): thistry = 1 while True: logging.info(\"accept_eula try {}\".format(thistry)) try:",
"with the Task Tracker mechanism. I have brought this to the attention #",
"post_eula_delay = '10' ntpserver = \"10.10.10.10\" ipv6address = readIPV6FromFile() pingableipv6 = ping(ipv6address) ra",
"has the \"time\" dictionary defined in it; if it does, copy into #",
"{1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def get_mac(self): \"\"\"Request the MAC address",
"\"UNCONFIGURE\" payload = {\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\": \"DHCP\", \"ipv6Type\": ipv6_type, \"macAddress\": appliance_mac_address, \"hostname\":",
"over again for the duration of its life. # Note, the header is",
"\"\"\" url = \"/rest/appliance/configuration/time-locale\" (success, resp, json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if",
"ntp_rjson, ntp_polling_results) = self.appliance_request(request_type='POST', url=time_locale_url, secure=True, payload=time_locale_settings) if not ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4,",
"the fqdn for any subsequent rest actions and then use the fqdn to",
"once. Additional calls will not change the status of the EULA nor the",
"logging.debug(\"Preparing HTTP {0} request.\".format(request_type)) logging.debug(\"Preparing URL: {0}.\".format(full_url)) logging.debug(\"Preparing Headers: {0}.\".format(head)) logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload)))",
"is undefined. No Session ID available. Status: {0}.'.format(r.status_code)) return self._secure_header except ValueError as",
"from the appliance. If the appliance returns an error status (anything outside of",
"\"GET\": r = self.sess.get(full_url, verify=False, headers=head, timeout=timeout, **other_properties) elif request_type == \"DELETE\": r",
"For example: other_properties={'stream': True} poll : boolean If false, polling tasks will return",
"for appliance to stabilize\".format(post_eula_delay)) time.sleep(post_eula_delay) ra.change_administrator_password() ra.first_time_setup(ntpserver, use_static_ip=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None)",
"only accepting values of 100, 199, and 200. retries (Optional): int Number of",
"network[\"hostname\"] = self.fqdn network[\"domainName\"] = self.fqdn.split(\".\", 1)[1] network['ipv4Type'] = \"STATIC\" network[\"searchDomains\"] = None",
"Poor consistency in # implementations and inconsistent with REST principles. url = response.headers.get('location')",
"{0}. url: {1}\".format(request_type, url)) try: safe_json_result = r.json() except: safe_json_result = {} logging.debug(\"Returned.",
"True self.sess.close() self.sess = requests.Session() adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) if",
"Adds to the set of parameters that appliance_request() returns. Parameters ---------- calling_url :",
"time.sleep(sec_between_polling) r_tree = None try: logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time())))) r_tree = self.sess.get(full_rest_url + \"?view=tree\",",
"to False. \"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\": False If the api_version is below version 100,",
"for OVA's that are deployed as DHCP but, # need to be configured",
"if task_state == \"Completed\": success = True else: success = False if not",
"system name import subprocess # For executing a shell command rest_call_timeout_sec = 60",
"None: timeout = rest_call_timeout_sec if not secure: head = self._header else: head =",
"Exception('MAC Address is not defined') def get_ipv4_name_servers(self): \"\"\"Request the list of dns ipv4",
"{0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def",
"found in applianceNetworks collection. If the appliance returns an error status (anything outside",
"Exception( 'time-locale setting failure. Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\")))",
"self.base_url + url logging.debug(\"Preparing HTTP {0} request.\".format(request_type)) logging.debug(\"Preparing URL: {0}.\".format(full_url)) logging.debug(\"Preparing Headers: {0}.\".format(head))",
"this file. This needs to be moved to a more formal location. Parameters",
"network-interfaces is a special case. Rather than network-interfaces returning a object of type",
"none Return ------ a response object from a call to the network page.",
"time_locale_settings[\"dateTime\"] = None # our time is not necessarily the NTP time, so",
"are now at least two responses with the task URL in the header:",
"= False if not success: logging.error(json.dumps(rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait",
"Exception message: {0}\".format(e)) if r.status_code >= 300: raise Exception('Failure to get secure connection.",
"that we can retry if the appliance goes offline (e.g. first time setup)",
"try: self.accept_eula_once(service_access=service_access) return except Exception as e: logging.exception(e) if thistry >= tries: raise",
"defined') def get_ipv4_name_servers(self): \"\"\"Request the list of dns ipv4 name servers. Use the",
"get headers. Exception message: {0}\".format(e)) if r.status_code >= 300: raise Exception('Failure to get",
"')))) return json_response def get_time_locale_data(self): \"\"\"Request the networking information from the appliance. If",
"raise Exception('get_time_locale_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',',",
"payload = networking_data elif use_static_ip: networking_data = self.get_networking_data() networks = [] for network",
"ping request. Remember that a host may not respond to a ping (ICMP)",
"must be accepted. This only needs to occur once. Additional calls will not",
"administrator data is pulled from the dictionary in this file. This needs to",
"= {\"type\": \"ApplianceServerConfiguration\", \"applianceNetworks\": [{\"ipv4Type\": \"DHCP\", \"ipv6Type\": ipv6_type, \"macAddress\": appliance_mac_address, \"hostname\": self.fqdn, \"device\":",
"the HTTP Call. Exception message: {0}\".format(e)) def accept_eula_once(self, service_access=\"yes\"): \"\"\"On initial communication with",
"as e: raise Exception('Failure to get a JSON value from the response. Status:",
"requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) # if version is passed in, use that.",
"given how complex the code is in this # area and the lack",
"thistry >= tries: raise e time.sleep(retry_interval) thistry += 1 def change_administrator_password(self): \"\"\"On initial",
"will embed another REST process using POST inside the generation of a POST",
"ipv4 name servers. Use the first one found in applianceNetworks collection. If the",
"if the host name is valid. \"\"\" operating_sys = platform.system().lower() for i in",
"if appliance_dhcp_ip_address: self.base_url = \"https://\" + appliance_dhcp_ip_address else: self.base_url = \"https://\" + appliance_name",
"{} logging.debug(\"Returned. Status code: {0}.\".format(r.status_code)) logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result)) # 202 status codes indicate",
"[{\"ipv4Type\": \"DHCP\", \"ipv6Type\": ipv6_type, \"macAddress\": appliance_mac_address, \"hostname\": self.fqdn, \"device\": \"eth0\", \"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\":",
"Python Request module. The dictionary is unpacked and added to Request. For example:",
"the appliance if not None \"\"\" self.fqdn = appliance_name if appliance_dhcp_ip_address: self.base_url =",
"+ appliance_name self.use_ip = use_ip # create a persistant session so that we",
"be contacted. If secure=True, this function depends on get_secure_headers(). Parameters ---------- request_type: str",
"request did not return a JSON value. polling_results: dict. dictionary with two values,",
"\"password\": <PASSWORD>} (logon_success, _, _, _) = self.appliance_request(request_type='POST', url=logon_url, secure=False, payload=logon_payload) if not",
"r = self.sess.post(self.base_url + url, verify=False, headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec) except requests.exceptions.RequestException as e:",
"and added to Request. For example: other_properties={'stream': True} poll : boolean If false,",
"PUT, or GET. request_type: {0}. url: {1}\".format(request_type, url)) try: safe_json_result = r.json() except:",
"Requests call. Return ------ tuple containing: task_state: str. A short summary of the",
"Server IP address and set the overrideIpv4DhcpDnsServers value to False. \"ipv4NameServers\": [dns_server_ip], \"overrideIpv4DhcpDnsServers\":",
"_) = self.appliance_request(request_type='POST', url=logon_url, secure=False, payload=logon_payload) if not logon_success: raise Exception('change_administrator_password failed. Status:",
"success: raise Exception('get_networking_data call failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4,",
"= response.headers.get('location') if url is None: url = response.json().get('uri') if url is None:",
"default to \"yes\" \"\"\" url = '/rest/appliance/eula/status' (_, _, json_result, _) = self.appliance_request(request_type='GET',",
"on URL: {0}. Exception: {1}'.format(calling_url, e)) def first_time_setup(self, ntpserver, use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False,",
"issue connecting to the appliance to get headers. Exception message: {0}\".format(e)) except Exception",
"= retries adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) # if version is",
"{\"supportAccess\": service_access} (save_success, save_resp, save_json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if save_success:",
"= r.json() self._secure_header = self._header.copy() self._secure_header['Auth'] = safe_json.get('sessionID') if self._secure_header['Auth'] is None: raise",
"request on URL: {1}'.format(polling_call_timeout_sec, calling_url)) time.sleep(sec_between_polling) r_tree = None try: logging.debug(\"Current Time {0}\".format(time.asctime(time.localtime(time.time()))))",
"not secure: head = self._header else: head = self.get_secure_headers() head = dict(head.items() +",
"for request_type is utilized. Exceptions will also be raised if the appliance cannot",
"= {\"userName\": initial_admin, \"oldPassword\": <PASSWORD>, \"newPassword\": <PASSWORD>} (success, resp, json_response, _) = self.appliance_request(request_type='POST',",
"r.status_code >= 300: raise Exception('Failure to get secure connection. Status {0}.'.format(r.status_code)) try: safe_json",
"ValueError as e: raise Exception('Failure to get a JSON value from the response.",
"header is undefined. No Session ID available. Status: {0}.'.format(r.status_code)) return self._secure_header except ValueError",
"EULA nor the status of the service access. If a change to the",
"json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) logging.warning('Administrator password has already been changed. Password",
"try: r = self.sess.post(self.base_url + url, verify=False, headers=self._header, data=json.dumps(payload), timeout=rest_call_timeout_sec) except requests.exceptions.RequestException as",
"but # we need to know if the network definition has the \"time\"",
"ova_ip is passed in. If a ova_ip is passed in then we will",
"the attention # of the atlas team. # # there are now at",
"202. success = False if r.status_code == 202: if not poll: return (True,",
"dict Python object payload for POST or PUT calls, to be serialized into",
"elif use_static_ip: networking_data = self.get_networking_data() networks = [] for network in networking_data['applianceNetworks']: if",
"If a change to the service access is required, see the function change_service_access()",
"self.get_networking_data() for network in json_answer.get('applianceNetworks', []): mac_address = network.get('macAddress') if mac_address: logging.info('MAC Address",
"payload=time_locale_settings) if not ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until",
"r) polling_results = {'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\": success =",
"polling_results = {'task_state': safe_json_result.get('errorCode', 'Error'), 'task_status': safe_json_result.get('details', str(safe_json_result))} return (success, r, safe_json_result, polling_results)",
"REST process using POST inside the generation of a POST to do the",
"ipv6_type=None, ova_ip=None, host_data=None) ra.accept_eula(\"yes\") logging.info(\"Sleeping {0} seconds to wait for appliance to stabilize\".format(post_eula_delay))",
"an error is raised. \"\"\" url = '/rest/appliance/network-interfaces' if ova_ip: networking_data = self.get_networking_data()",
"= True self.sess.close() self.sess = requests.Session() adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap)",
"getting the operating system name import subprocess # For executing a shell command",
"Exception( 'time-locale setting failed. Polling State: {0}. Polling Status: {1}. '.format( ntp_polling_results.get(\"task_state\"), ntp_polling_results.get(\"task_status\")))",
"appliance_request() returns. Parameters ---------- calling_url : string The URL that was called in",
"for the program # Default to the minimal version number that implements all",
"this # area and the lack of documented test cases, this seems to",
"is not necessarily the NTP time, so don't set it. time_locale_settings[\"ntpServers\"] = [str(ntpserver)]",
"_, _, _) = self.appliance_request(request_type='POST', url=logon_url, secure=False, payload=logon_payload) if not logon_success: raise Exception('change_administrator_password",
"polling the rest task {0}.\".format(url)) already_reset_session = False while task_state in ['Running', 'New',",
"json_response, _) = self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_networking_data call failed.",
"method to RestAppliance. We compute the correct API-Version for REST calls. The version",
"JSON Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def accept_eula(self, service_access=\"yes\", tries=3,",
"now at least two responses with the task URL in the header: #",
"use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Creates networking for the appliance. Configures the appliance as",
"save_resp, save_json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if save_success: logging.info('EULA Accepted.') else:",
"what UI does so we follow network[\"aliasDisabled\"] = True network[\"overrideIpv4DhcpDnsServers\"] = False if",
"set DNS. If the appliance returns an error status (anything outside of the",
"failed. Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) logging.warning('Administrator",
"\"hostname\": self.fqdn, \"device\": \"eth0\", \"ipv4NameServers\": ipv4_name_servers, \"overrideIpv4DhcpDnsServers\": False, \"ipv4Subnet\": \"\", \"ipv4Gateway\": None, \"confOneNode\":",
"or 200 range), an error is raised. No authentication on the appliance is",
"Exception('Auth token for the header is undefined. No Session ID available. Status: {0}.'.format(r.status_code))",
"dictionary defined in it; if it does, copy into # place for the",
"to \"yes\" \"\"\" url = '/rest/appliance/eula/status' (_, _, json_result, _) = self.appliance_request(request_type='GET', url=url,",
"Auth parameter value is a sessionID. \"\"\" # Once _secure_header is defined, we",
"initial communication with the appliance, the end user service agreement (EULA) must be",
"override_version: self.api_version = override_version else: self.api_version = 120 logging.info(\"The API Version utilized is",
"server is not defined') def get_networking_data(self): \"\"\"Request the networking information from the appliance.",
"r.json())) def appliance_request(self, request_type, url, secure=True, payload=None, other_properties={}, extra_headers={}, poll=True, timeout=None): \"\"\"Helper method",
"Note, the header is only good for that user (administrator), 24 hours, and",
"= open('vm_network.json',) data = json.load(vm_network_json_file) # Iterating through the json list for i",
"== \"DHCP\": network['ipv4Type'] = \"STATIC\" network['ipv6Type'] = \"UNCONFIGURE\" networks.append(network) if use_i3s_fts: network['ipv6Type'] =",
"of extra properties that we can give to the Python Request module. The",
"Status: {0}. JSON Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def accept_eula(self,",
"raise Exception('Failure to access the sessionID from the response. Status: {0}. JSON: {1}'.format(r.status_code,",
"r: a response object from a Requests call. safe_json_results: the JSON returned from",
"['Running', 'New', 'Pending', 'Starting']: if time.time() >= start_time + polling_call_timeout_sec: raise Exception('Task Polling",
"list of dns ipv4 name servers. Use the first one found in applianceNetworks",
"network setup. self.set_time_server_and_locale(ntpserver) poll = True # Do not poll for the task",
"is None: url = response.json().get('uri') if url is None: raise Exception('Could not read",
"will also be raised if the appliance cannot be contacted. If secure=True, this",
"This needs to be moved to a more formal location. Parameters ---------- none",
"qualified domain name of the system with this string. secure (optional): boolean True",
"ntpserver, use_static_ip=False, use_tbird_fts=False, use_i3s_fts=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Creates networking for the appliance.",
"')))) logging.warning('Administrator password has already been changed. Password is {0}'.format(<PASSWORD>)) else: raise Exception('change_administrator_password",
"if the request did not return a JSON value. polling_results: dict. dictionary with",
"self.appliance_request(request_type='POST', url=logon_url, secure=False, payload=logon_payload) if not logon_success: raise Exception('change_administrator_password failed. Status: {0}. JSON",
"r, safe_json_result, {'task_state': 'N/A', 'task_status': 'N/A'}) (task_state, task_status) = self.poll_for_task(url, r) polling_results =",
"{0}. State: {1}. Status: {2}.\".format(task_resource.get('percentComplete'), task_state, task_status)) logging.debug(\"The task tree for {0} is:\".format(full_rest_url))",
"success = False if not success: logging.error(json.dumps(rjson, sort_keys=True, indent=4, separators=(',', ': '))) if",
"asynchronous REST call. Poll until the task is complete or error. Adds to",
"the appliance is required. Parameters ---------- service_access (optional): str \"yes\" will accept service",
"Configures the appliance as DHCP. The appliance queries itself to define its macAddress.",
"Status: {0}. JSON: {1}'.format(r.status_code, r.json())) def appliance_request(self, request_type, url, secure=True, payload=None, other_properties={}, extra_headers={},",
"it. (ntp_success, _, ntp_rjson, ntp_polling_results) = self.appliance_request(request_type='POST', url=time_locale_url, secure=True, payload=time_locale_settings) if not ntp_success:",
"'-c' shell_needed = True if operating_sys == 'windows' else False # Building the",
"{0}\".format(e)) def accept_eula_once(self, service_access=\"yes\"): \"\"\"On initial communication with the appliance, the end user",
"the administrator login is not successful, an error is raised. The administrator data",
"\"Warning\": #This is required sicne FTS will try to validate the hostname and",
"payload=payload, poll=poll) # Reset the base url to the the fqdn for any",
"output and append to status message for e in task_errors: logging.error(e) task_status +=",
"in data['results'][0]['msg']: for j in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) # Closing file vm_network_json_file.close() return ipv6address",
"with authentication information. Return ------ _secure_header: dict. Dictionary containing X-API-Verions, Content-Type, and Auth.",
"tuple with these values: success: bool. A True/False value. True indicates that the",
"header: # '/rest/appliance/network-interfaces' and '/rest/appliance/configuration/time-locale' # Go to checking for response in the",
"{0}. JSON: {1}'.format(r.status_code, r.json())) def appliance_request(self, request_type, url, secure=True, payload=None, other_properties={}, extra_headers={}, poll=True,",
"is in this # area and the lack of documented test cases, this",
"message: {0}\".format(e)) def accept_eula_once(self, service_access=\"yes\"): \"\"\"On initial communication with the appliance, the end",
"self.sess.get(full_rest_url + \"?view=tree\", verify=False, headers=self.get_secure_headers(), timeout=rest_call_timeout_sec) except Exception as e: logging.exception(\"FTS get failed:",
"test cases, this seems to be the safest change to make. old_network =",
"with two values, task_state and task_status. Both are populated whenever the call requires",
"get_networking_data(self): \"\"\"Request the networking information from the appliance. If the appliance returns an",
"self._secure_header except ValueError as e: raise Exception('Failure to get a JSON value from",
"requests data adding a header that includes authentiation information. False requests data without",
"calling_url, response): '''Helper method to appliance_request(). Status Response 202 indicates an asynchronous REST",
"login with the administrator password. If successful, we log a message and the",
"elif self.use_ip and task_state == \"Warning\": #This is required sicne FTS will try",
"def get_ipv4_name_servers(self): \"\"\"Request the list of dns ipv4 name servers. Use the first",
"if \"time\" in old_network: payload[\"time\"] = deepcopy(old_network[\"time\"]) # This is the later data",
"max_retries_in_session = 50 polling_call_timeout_sec = 10 * 60 sec_between_polling = 10 class FirstTimeSetUp(object):",
"or unspecified Return ------ return (success, r, safe_json_result, polling_results) A tuple with these",
"<PASSWORD>} (logon_success, _, _, _) = self.appliance_request(request_type='POST', url=logon_url, secure=False, payload=logon_payload) if not logon_success:",
"'__main__': post_eula_delay = '10' ntpserver = \"10.10.10.10\" ipv6address = readIPV6FromFile() pingableipv6 = ping(ipv6address)",
"value. polling_results: dict. dictionary with two values, task_state and task_status. Both are populated",
"e)) except Exception as e: raise Exception('Error in polling for the task. Originating",
"an issue with the HTTP Call for task polling. Exception message: {0}\".format(e)) #",
"ipv4 name servers: list \"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []):",
"(save_success, save_resp, save_json_response, _) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if save_success: logging.info('EULA Accepted.')",
"time from copy import deepcopy import platform # For getting the operating system",
"\"Administrator\", \"password\": \"<PASSWORD>\"} url = '/rest/login-sessions' try: r = self.sess.post(self.base_url + url, verify=False,",
"was an issue connecting to the appliance to get headers. Exception message: {0}\".format(e))",
"copy into # place for the test below this set of conditional branches.",
"is raised. Parameters ---------- none Return ------ mac address: string \"\"\" json_answer =",
"data = json.load(vm_network_json_file) # Iterating through the json list for i in data['results'][0]['msg']:",
"rest_call_timeout_sec = 60 max_retries_in_session = 50 polling_call_timeout_sec = 10 * 60 sec_between_polling =",
"Warning, Completed. ''' # network-interfaces is a special case. Rather than network-interfaces returning",
"delete and recreate of the session if it loses connection. Changes in IP",
"polling. \"\"\" if timeout is None: timeout = rest_call_timeout_sec if not secure: head",
"a ova_ip is passed in. If a ova_ip is passed in then we",
"json.load(vm_network_json_file) # Iterating through the json list for i in data['results'][0]['msg']: for j",
"logging.info(\"Sleeping {0} seconds to wait for appliance to stabilize\".format(post_eula_delay)) time.sleep(post_eula_delay) ra.change_administrator_password() ra.first_time_setup(ntpserver, use_static_ip=False,",
"(_, _, json_result, _) = self.appliance_request(request_type='GET', url=url, secure=False) if not json_result: # if",
"url=url, secure=True, payload=payload, poll=poll) # Reset the base url to the the fqdn",
"for i in hosts: param = '-n' if operating_sys=='windows' else '-c' shell_needed =",
"300 and the polling was successful. r: a response object from a Requests",
":return: :raises: Exception, Exception \"\"\" time_locale_url = \"/rest/appliance/configuration/time-locale\" # Query for current time-locale",
"for j in data['results'][0]['msg'][i]['ipv6']: ipv6address.append(j) # Closing file vm_network_json_file.close() return ipv6address def ping(hosts):",
"in then we will lose connection # to the orginal location after the",
"method to call HTTP requests. An exception will be raised if an unknown",
"{0}\".format(full_rest_url)) return(task_state, task_status) except ValueError as e: raise Exception('Error getting the JSON results",
"a sessionID. \"\"\" # Once _secure_header is defined, we can use it over",
"e time.sleep(retry_interval) thistry += 1 def change_administrator_password(self): \"\"\"On initial logon, the administrator's password",
"safe_json_results: the JSON returned from the HTTP request. None if the request did",
"network[\"hostname\"] = network[\"hostname\"] + '.' + appliance_domain_name logging.info(\"Setting fqdn for the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks']",
"logging.info(\"NTP server setting was successful\") def poll_for_task(self, calling_url, response): '''Helper method to appliance_request().",
"status message for e in task_errors: logging.error(e) task_status += \";\" + \";\".join([str(e) for",
"correct API-Version for REST calls. The version can be overridden by passing in",
"for that user (administrator), 24 hours, and until the next reboot. if self._secure_header:",
"JSON: {1}'.format(r.status_code, r.json())) def appliance_request(self, request_type, url, secure=True, payload=None, other_properties={}, extra_headers={}, poll=True, timeout=None):",
"verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"GET\": r = self.sess.get(full_url, verify=False,",
"is set via an independent REST endpoint. :param ntpserver: IP address of the",
"= task_resource.get('taskErrors', None) if task_errors: # in case of errors place them in",
"tries=3, retry_interval=5): thistry = 1 while True: logging.info(\"accept_eula try {}\".format(thistry)) try: self.accept_eula_once(service_access=service_access) return",
"Exceptions will also be raised if the appliance cannot be contacted. If secure=True,",
"servers: list \"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []): ipv4_name_servers =",
"if not success: logging.error(json.dumps(rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until the",
"def appliance_request(self, request_type, url, secure=True, payload=None, other_properties={}, extra_headers={}, poll=True, timeout=None): \"\"\"Helper method to",
"then use the fqdn to make sure the # networking setup task completes",
"= self.appliance_request(request_type='POST', url=logon_url, secure=False, payload=logon_payload) if not logon_success: raise Exception('change_administrator_password failed. Status: {0}.",
"{0}.\".format(full_url)) logging.debug(\"Preparing Headers: {0}.\".format(head)) logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload))) polling_results = {} try: if request_type",
"If the appliance returns an error status (anything outside of the 100 or",
"Exception(\"There was an issue connecting to the appliance to get headers. Exception message:",
"self.sess.put(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout, **other_properties) elif request_type == \"GET\": r = self.sess.get(full_url,",
"_) = self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if success: logging.info('Administrator password change was accepted.')",
"default value. The call to the administrator password change is attempted. If the",
"failed. Status: {0}. JSON Response: {1}'.format(save_resp.status_code, json.dumps(save_json_response, sort_keys=True, indent=4, separators=(',', ': ')))) def",
"= None # our time is not necessarily the NTP time, so don't",
"value will raise an error. url: str url location of the REST call.",
"is raised. No authentication on the appliance is required. Parameters ---------- service_access (optional):",
"self._secure_header['Auth'] = safe_json.get('sessionID') if self._secure_header['Auth'] is None: raise Exception('Auth token for the header",
"url=url, secure=True) if not success: raise Exception('get_time_locale_data call failed. Status: {0}. JSON Response:",
"self.appliance_request(request_type='POST', url=url, secure=False, payload=payload) if save_success: logging.info('EULA Accepted.') else: raise Exception('accept_eula failed. Status:",
"self.get_mac() ipv4_name_servers = self.get_ipv4_name_servers() # Only ipv6 with DHCP is supported, will add",
"dhcp ip address, will be used to connect to the appliance if not",
"that user (administrator), 24 hours, and until the next reboot. if self._secure_header: return",
"adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://', adap) self.sess.mount('https://', adap) # if version is passed in,",
"an issue connecting to the appliance to get headers. Exception message: {0}\".format(e)) except",
"logging.debug(\"Preparing URL: {0}.\".format(full_url)) logging.debug(\"Preparing Headers: {0}.\".format(head)) logging.debug(\"Preparing Payload: {0}.\".format(json.dumps(payload))) polling_results = {} try:",
"loses connection. Changes in IP address, FQDN, etc can make use lose the",
"self.base_url = \"https://\" + appliance_name self.use_ip = use_ip # create a persistant session",
"\"\"\"On initial logon, the administrator's password has to be changed from the default",
"polling for the task. Originating request on URL: {0}. Exception: {1}'.format(calling_url, e)) def",
"], } # Not clear why this conditions fails to query the network",
"i] ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success = ping_output.returncode if success == 0: return (str(i)+str('%ens160'))",
"change to make. old_network = self.get_networking_data() if \"time\" in old_network: payload[\"time\"] = deepcopy(old_network[\"time\"])",
"returns an error status (anything outside of the 100 or 200 range), an",
"available. Status: {0}.'.format(r.status_code)) return self._secure_header except ValueError as e: raise Exception('Failure to get",
"the program # Default to the minimal version number that implements all the",
"special case. Rather than network-interfaces returning a object of type TaskResourceV2, this end",
"define its macAddress. If the api_version is above version 100, this will set",
"for any subsequent rest actions and then use the fqdn to make sure",
"network[\"domainName\"] = self.fqdn.split(\".\", 1)[1] network['ipv4Type'] = \"STATIC\" network[\"searchDomains\"] = None # this is",
"payload (optional): dict Python object payload for POST or PUT calls, to be",
"will return immiedtaly - needed for failover setups timeout: None or integer Defaults",
"JSON returned from the HTTP request. None if the request did not return",
"(optional): dict A dictionary of extra properties that we can give to the",
"HTTP request. None if the request did not return a JSON value. polling_results:",
"the time server and locale are set via their own API # This",
"The appliance queries itself to define its macAddress. If the api_version is above",
"ipv6address = [] vm_network_json_file = open('vm_network.json',) data = json.load(vm_network_json_file) # Iterating through the",
"Exception(\"There was an issue connecting to the appliance. Exception message: {0}\".format(e)) except Exception",
"= self.appliance_request(request_type='GET', url=url, secure=True) if not success: raise Exception('get_networking_data call failed. Status: {0}.",
"use_ip=False, override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Constructor method to",
"may not respond to a ping (ICMP) request even if the host name",
"first time setup) self.sess = requests.Session() self.retries = retries adap = requests.adapters.HTTPAdapter(max_retries=self.retries) self.sess.mount('http://',",
"ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until the operation completes'",
"1)[1] network['ipv4Type'] = \"STATIC\" network[\"searchDomains\"] = None # this is what UI does",
"{'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\": success = True else: success",
"raise e time.sleep(retry_interval) thistry += 1 def change_administrator_password(self): \"\"\"On initial logon, the administrator's",
"\"\"\" json_answer = self.get_networking_data() for network in json_answer.get('applianceNetworks', []): ipv4_name_servers = network.get('ipv4NameServers') if",
"and recreate of the session if it loses connection. Changes in IP address,",
"in appliance_request. response : a response object from a Requests call. Return ------",
"occur once. Additional calls will not change the status of the EULA nor",
"task_state = 'Running' start_time = time.time() try: logging.debug(\"Starting polling the rest task {0}.\".format(url))",
"the defined NTP server and only it. (ntp_success, _, ntp_rjson, ntp_polling_results) = self.appliance_request(request_type='POST',",
"immiedtaly - needed for failover setups timeout: None or integer Defaults to rest_call_timeout_sec",
"ip address will change after setting up the networking. if ova_ip and success:",
"24 hours, and until the next reboot. if self._secure_header: return self._secure_header payload =",
"payload for POST or PUT calls, to be serialized into JSON. other_properties (optional):",
"one found in applianceNetworks collection. If the appliance returns an error status (anything",
"will change after setting up the networking. if ova_ip and success: self.base_url =",
"Call for task polling. Exception message: {0}\".format(e)) # delete and recreate of the",
"json_response def get_time_locale_data(self): \"\"\"Request the networking information from the appliance. If the appliance",
"appliance_domain_name logging.info(\"Setting fqdn for the appliance:{0}\".format(network[\"hostname\"])) networking_data['applianceNetworks'] = networks networking_data.pop('serverCertificate', None) payload =",
"= ping(ipv6address) ra = FirstTimeSetUp(\"appliance_name\", override_version=3200, use_ip=False, appliance_dhcp_ip_address=None, post_eula_delay=post_eula_delay, use_static_ip=False,use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None)",
"in. If a ova_ip is passed in then we will lose connection #",
"get a JSON value from the response. Status: {0}.'.format(r.status_code)) except: raise Exception('Failure to",
"Exception as e: raise Exception(\"There was an issue with the HTTP Call to",
"sort_keys=True, indent=4, separators=(',', ': ')))) def accept_eula(self, service_access=\"yes\", tries=3, retry_interval=5): thistry = 1",
"nor the status of the service access. If a change to the service",
"dns ipv4 name servers. Use the first one found in applianceNetworks collection. If",
"object from a call to the network page. \"\"\" url = '/rest/appliance/network-interfaces' (success,",
"if not ntp_success: logging.error(json.dumps(ntp_rjson, sort_keys=True, indent=4, separators=(',', ': '))) if 'Wait until the",
"name) can be overridden. Currently only accepting values of 100, 199, and 200.",
"function may not know that this will return a 202. success = False",
"cases, this seems to be the safest change to make. old_network = self.get_networking_data()",
"= self.get_networking_data() for network in json_answer.get('applianceNetworks', []): mac_address = network.get('macAddress') if mac_address: logging.info('MAC",
"as DHCP but, # need to be configured as static since the ip",
"appliance dhcp ip address, will be used to connect to the appliance if",
"{0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) logging.warning('Administrator password has",
"---------- request_type: str accepted values are: \"POST\", \"PUT\", \"GET\", \"DELETE\" Any other value",
"= r.json() except: safe_json_result = {} logging.debug(\"Returned. Status code: {0}.\".format(r.status_code)) logging.debug(\"Returned. JSON: {0}.\".format(safe_json_result))",
"their own API # This will embed another REST process using POST inside",
"polling_results = {'task_state': task_state, 'task_status': task_status} if task_state == \"Completed\": success = True",
"is a sessionID. \"\"\" # Once _secure_header is defined, we can use it",
"{} try: if request_type == \"POST\": r = self.sess.post(full_url, verify=False, headers=head, data=json.dumps(payload), timeout=timeout,",
"__init__(self, appliance_name, use_ip=False, override_version=None, retries=max_retries_in_session, appliance_dhcp_ip_address=None, post_eula_delay=0, use_static_ip=False, use_one_ip=False, ipv6_type=None, ova_ip=None, host_data=None): \"\"\"Constructor",
"json_answer.get('applianceNetworks', []): ipv4_name_servers = network.get('ipv4NameServers') if ipv4_name_servers: logging.info('IPv4 Name servers: {0}'.format(ipv4_name_servers)) return ipv4_name_servers",
"JSON value from the response. Status: {0}.'.format(r.status_code)) except: raise Exception('Failure to access the",
"1 google.com\" ping_command = ['ping', param, '1', i] ping_output = subprocess.run(ping_command,shell=shell_needed,stdout=subprocess.PIPE) success =",
"appliance_domain_name not in network[\"hostname\"]: network[\"hostname\"] = network[\"hostname\"] + '.' + appliance_domain_name logging.info(\"Setting fqdn",
"if ipv4_name_servers: logging.info('IPv4 Name servers: {0}'.format(ipv4_name_servers)) return ipv4_name_servers raise Exception('IPv4 Name server is",
"200 range), an error is raised. Parameters ---------- none Return ------ mac address:",
"Status: {0}. JSON Response: {1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return json_response",
"{1}'.format(resp.status_code, json.dumps(json_response, sort_keys=True, indent=4, separators=(',', ': ')))) return json_response def get_time_locale_data(self): \"\"\"Request the",
"Do not poll for the task if a ova_ip is passed in. If",
"from the task. Originating request on URL: {0}. Exception: {1}'.format(calling_url, e)) except Exception",
"self.get_ipv4_name_servers() # Only ipv6 with DHCP is supported, will add static at some"
] |
[
"if sserializer.is_valid(): sserializer.save() return Response(sserializer.data, status=status.HTTP_200_OK) return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): try:",
"if not user: # return Response({'error': 'Invalid Credentials'}, # status=HTTP_404_NOT_FOUND) # token, restdetails",
"status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details found for given date'}, status=status.HTTP_400_BAD_REQUEST)",
"'drug/home.html',{}) return redirect('accounts/login') def loginpage(request): return render(request, 'drug/login.html', {}) def search(symptom): api =",
"for fooditem in result.json()[\"foods\"]: foodlist += fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"]",
"= request.data.getlist('unchoices[]') except AttributeError: present_symptoms = request.data.get('choices') absent_symptoms = request.data.get('unchoices') query_text = request.data.get('queryText')",
"rest_framework import permissions, status import infermedica_api # import Symp from .serializers import SelfcarediarySerializer",
"except AttributeError: present_symptoms = request.data.get('choices') absent_symptoms = request.data.get('unchoices') query_text = request.data.get('queryText') recordobject =",
"selfdiary(request): if request.user.is_authenticated(): return render(request, 'drug/selfdiary.html', {}) return redirect('accounts/login') def analytics(request): if request.user.is_authenticated():",
"= \"\" for fooditem in result.json()[\"foods\"]: foodlist += fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"]",
"if request.user.is_authenticated(): return render(request, 'drug/home.html',{}) return redirect('accounts/login') def loginpage(request): return render(request, 'drug/login.html', {})",
"\"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite } # nserializer = NutrientsSerializer(data=request.data) #",
"= fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for fooditem",
"from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework.response import Response from",
"# return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView): def post(self, request): request_data = request.data.copy() request_data[\"user\"]",
"# import pdb; pdb.set_trace() mysymptomlist = {} for data in response: mysymptomlist[\"orth\"] =",
"0: return Response({\"success\": False,\"message\": \"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) if",
"given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk",
"protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist = fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite)",
"redirect('accounts/login') def selfdiary(request): if request.user.is_authenticated(): return render(request, 'drug/selfdiary.html', {}) return redirect('accounts/login') def analytics(request):",
"} result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories = 0 fat = 0 sugar",
"\"query\":mealval, \"timezone\": \"US/Eastern\" } result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories = 0 fat",
"[] for qset in selfdiary: resplist.append({\"diary\":qset.diary,\"date\":qset.date}) return Response({\"data\":resplist}, status=status.HTTP_200_OK) except: return Response({\"success\": False},",
"django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view, permission_classes from",
"apiKey, 'Content-Type': 'application/json'}) return Response({\"test\":data}, status=status.HTTP_200_OK) # class Search(APIView): class Diagnosis(APIView): @csrf_exempt def",
"Symptomrecord, Diseaserecord, Foodrecord, Foodlist, Selfcarediary from .serializers import NutrientsSerializer from rest_framework.views import APIView",
"app_key='be2ee424c225c567086a084637a359de') # r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list() # r = requests.post(url,",
"Token from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny from rest_framework.status import",
"@csrf_exempt def get(self, request): try: heartrate = HeartRate.objects.all() hserializer = HeartRateSerializer(heartrate) heartrate_data =",
"vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for fooditem in result.json()[\"foods\"]:",
"requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories = 0 fat = 0 sugar = 0 protein",
"= api.parse(sentence).to_dict()[\"mentions\"] # import pdb; pdb.set_trace() mysymptomlist = {} for data in response:",
"vite+=nutlist[27][\"value\"] foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for fooditem in result.json()[\"foods\"]: foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save()",
"import csrf_exempt from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions",
"pdb; pdb.set_trace() mysymptomlist = {} for data in response: mysymptomlist[\"orth\"] = data[\"orth\"] mysymptomlist[\"id\"]",
"text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'}) return Response({\"test\":data}, status=status.HTTP_200_OK) # class Search(APIView): class Diagnosis(APIView): @csrf_exempt",
"[] print(\"reached finalserach\") for symptom in mysymptomlist: callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict =",
"home(request): if request.user.is_authenticated(): return render(request, 'drug/home.html',{}) return redirect('accounts/login') def loginpage(request): return render(request, 'drug/login.html',",
"= data[\"orth\"] mysymptomlist[\"id\"] = data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt # @api_view([\"POST\"]) #",
"sample_api(request): # data = {'sample_data': 123} # return Response(data, status=HTTP_200_OK) class HeartRateApi(APIView): @csrf_exempt",
"api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list() #",
"be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) if doubleroomaval != '': if int(doubleroomaval) >",
"absent_symptoms = request.data.get('unchoices') query_text = request.data.get('queryText') recordobject = Record.objects.get(user=request.user,search_query=query_text) api = infermedica_api.get_api() re",
"= 0 carbs = 0 vita = 0 vitb = 0 vitc =",
"status=status.HTTP_400_BAD_REQUEST) try: booking = Booking.objects.get(date=datebooking) bserializer = BookingSerializer(booking, data=request_data, partial=True) except: bserializer =",
"return Response(heartrate_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details found for given",
"'': if int(doubleroomaval) > 5 or int(doubleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability",
"request_data.get('singleroomaval','') doubleroomaval = request_data.get('doubleroomaval','') if singleroomaval != '': if int(singleroomaval) > 5 or",
"found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request, user): request_data = request.data.copy()",
"between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) if doubleroomaval != '': if int(doubleroomaval) > 5",
"return render(request, 'drug/selfdiary.html', {}) return redirect('accounts/login') def analytics(request): if request.user.is_authenticated(): return render(request, 'drug/analytics.html',",
"import NutrientsSerializer from rest_framework.views import APIView from rest_framework import permissions, status import infermedica_api",
"diseaseobject.save() return Response({\"test\":re}, status=status.HTTP_200_OK) # call diagnosis class Symptom(APIView): @csrf_exempt def post(self,request): api",
"class NutrientsApi(APIView): @csrf_exempt def get(self, request): try: nutrients = Nutrient.objects.all() nserializer = NutrientsSerializer(nutrients)",
"in response: mysymptomlist[\"orth\"] = data[\"orth\"] mysymptomlist[\"id\"] = data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt",
") from rest_framework.response import Response from rest_framework.views import APIView from django.contrib.auth import authenticate",
"rest_framework.views import APIView from django.contrib.auth import authenticate from .models import Nutrient, Record, Symptomrecord,",
"return redirect('accounts/login.html') class ParseD(APIView): @csrf_exempt def post(self,request): sentence = request.data.get(\"text\") dbrow = Record(user=request.user,search_query=sentence)",
"fat = 0 sugar = 0 protein = 0 carbs = 0 vita",
"from django.contrib.auth import authenticate from .models import Nutrient, Record, Symptomrecord, Diseaserecord, Foodrecord, Foodlist,",
"finalsearchdata = [] print(\"reached finalserach\") for symptom in mysymptomlist: callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata)",
"request_data['user'] = user singleroomaval = request_data.get('singleroomaval','') doubleroomaval = request_data.get('doubleroomaval','') if singleroomaval != '':",
"sserializer = SelfcarediarySerializer(data=request_data) if sserializer.is_valid(): sserializer.save() return Response(sserializer.data, status=status.HTTP_200_OK) return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def",
"request_data = request.data.copy() request_data[\"user\"] = request.user.pk sserializer = SelfcarediarySerializer(data=request_data) if sserializer.is_valid(): sserializer.save() return",
"get(self, request): try: selfdiary = Selfcarediary.objects.filter(user=request.user) resplist = [] for qset in selfdiary:",
"nserializer.save() return Response(response, status=status.HTTP_200_OK) # return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView): def post(self, request):",
"token.key, \"hasuraid\": user.id}, # status=HTTP_200_OK) # @csrf_exempt # @api_view([\"GET\"]) # def sample_api(request): #",
"from rest_framework.permissions import AllowAny from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK ) from",
"Response(response, status=status.HTTP_200_OK) # return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView): def post(self, request): request_data =",
"django.shortcuts import render, redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token from",
"NutrientsApi(APIView): @csrf_exempt def get(self, request): try: nutrients = Nutrient.objects.all() nserializer = NutrientsSerializer(nutrients) nutrient_data",
"\"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite } # nserializer = NutrientsSerializer(data=request.data) # if",
"APIView from rest_framework import permissions, status import infermedica_api # import Symp from .serializers",
"class Symptom(APIView): @csrf_exempt def post(self,request): api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] # import",
"provide both username and password'}, # status=HTTP_400_BAD_REQUEST) # user = authenticate(username=username, password=password) #",
"must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) try: booking = Booking.objects.get(date=datebooking) bserializer =",
"# if not user: # return Response({'error': 'Invalid Credentials'}, # status=HTTP_404_NOT_FOUND) # token,",
"try: nutrients = Nutrient.objects.all() nserializer = NutrientsSerializer(nutrients) nutrient_data = nserializer.data return Response(nutrient_data, status=status.HTTP_200_OK)",
"= request.data.get(\"password\") # if username is None or password is None: # return",
"render(request, 'drug/home.html',{}) return redirect('accounts/login') def loginpage(request): return render(request, 'drug/login.html', {}) def search(symptom): api",
"0 protein = 0 carbs = 0 vita = 0 vitb = 0",
"\"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite } # nserializer = NutrientsSerializer(data=request.data)",
"fooditem in result.json()[\"foods\"]: foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response = { \"foodlist\":foodlist, \"calories\":calories, \"fat\":fat,",
"def post(self, request, user): request_data = request.data.copy() request_data['user'] = user singleroomaval = request_data.get('singleroomaval','')",
"= request_data.get('doubleroomaval','') if singleroomaval != '': if int(singleroomaval) > 5 or int(singleroomaval) <",
"request_data[\"user\"] = request.user.pk mealval = request_data.get('meal') data = { \"query\":mealval, \"timezone\": \"US/Eastern\" }",
"password=password) # if not user: # return Response({'error': 'Invalid Credentials'}, # status=HTTP_404_NOT_FOUND) #",
"print(\"reached templist\") for data in response: templist[\"orth\"] = data[\"orth\"] templist[\"id\"] = data[\"id\"] mysymptomlist.append(templist.copy())",
"login(request): # username = request.data.get(\"username\") # password = request.data.get(\"password\") # if username is",
"data def nutrients(request): if request.user.is_authenticated(): return render(request, 'drug/nutrients.html', {}) return redirect('accounts/login') def selfdiary(request):",
"post(self, request, user): request_data = request.data.copy() request_data['user'] = user singleroomaval = request_data.get('singleroomaval','') doubleroomaval",
"finalsearchdata.extend(callsearchdata) finaldict = {} print(\"conversion\") for dictdata in finalsearchdata: finaldict[dictdata['label']] = dictdata['id'] symprow",
"re.add_symptom(symptom, 'absent') re= api.diagnosis(re).to_dict() for dictdata in re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id'])",
"request.user.is_authenticated(): return render(request, 'drug/nutrients.html', {}) return redirect('accounts/login') def selfdiary(request): if request.user.is_authenticated(): return render(request,",
"= request.data.copy() request_data['user'] = user singleroomaval = request_data.get('singleroomaval','') doubleroomaval = request_data.get('doubleroomaval','') if singleroomaval",
"request.data.get('queryText') recordobject = Record.objects.get(user=request.user,search_query=query_text) api = infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for symptom",
"'Invalid Credentials'}, # status=HTTP_404_NOT_FOUND) # token, restdetails = Token.objects.get_or_create(user=user) # return Response({'token': token.key,",
"= infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list() # r",
"= request.data.copy() request_data[\"user\"] = request.user.pk mealval = request_data.get('meal') data = { \"query\":mealval, \"timezone\":",
"heartrate = HeartRate.objects.all() hserializer = HeartRateSerializer(heartrate) heartrate_data = hserializer.data return Response(heartrate_data, status=status.HTTP_200_OK) except:",
"data = api.search(symptom[\"orth\"]) return data def nutrients(request): if request.user.is_authenticated(): return render(request, 'drug/nutrients.html', {})",
"response: mysymptomlist[\"orth\"] = data[\"orth\"] mysymptomlist[\"id\"] = data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt #",
"diagnosis class Symptom(APIView): @csrf_exempt def post(self,request): api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] #",
"= infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list() # r = requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey,",
"infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def home(request): if request.user.is_authenticated(): return render(request, 'drug/home.html',{}) return redirect('accounts/login') def loginpage(request):",
"for dictdata in re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({\"test\":re}, status=status.HTTP_200_OK)",
"is None: # return Response({'error': 'Please provide both username and password'}, # status=HTTP_400_BAD_REQUEST)",
"infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list() # r =",
"'drug/nutrients.html', {}) return redirect('accounts/login') def selfdiary(request): if request.user.is_authenticated(): return render(request, 'drug/selfdiary.html', {}) return",
"request.user.pk sserializer = SelfcarediarySerializer(data=request_data) if sserializer.is_valid(): sserializer.save() return Response(sserializer.data, status=status.HTTP_200_OK) return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST)",
"from .serializers import SelfcarediarySerializer import requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def home(request): if request.user.is_authenticated(): return",
"for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request, user): request_data = request.data.copy() request_data['user']",
"return render(request, 'drug/medication.html', {}) return redirect('accounts/login.html') class ParseD(APIView): @csrf_exempt def post(self,request): sentence =",
"HeartRateSerializer(heartrate) heartrate_data = hserializer.data return Response(heartrate_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No",
"hserializer.data return Response(heartrate_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details found for",
"\"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite } # nserializer = NutrientsSerializer(data=request.data) # if nserializer.is_valid():",
"{} print(\"reached templist\") for data in response: templist[\"orth\"] = data[\"orth\"] templist[\"id\"] = data[\"id\"]",
"api.parse(sentence).to_dict()[\"mentions\"] # import pdb; pdb.set_trace() mysymptomlist = {} for data in response: mysymptomlist[\"orth\"]",
"= 0 foodlist = \"\" for fooditem in result.json()[\"foods\"]: foodlist += fooditem[\"food_name\"]+\"; \"",
"@permission_classes((AllowAny,)) # def login(request): # username = request.data.get(\"username\") # password = request.data.get(\"password\") #",
"between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) try: booking = Booking.objects.get(date=datebooking) bserializer = BookingSerializer(booking, data=request_data,",
"SelfcarediarySerializer(data=request_data) if sserializer.is_valid(): sserializer.save() return Response(sserializer.data, status=status.HTTP_200_OK) return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request):",
"# class Search(APIView): class Diagnosis(APIView): @csrf_exempt def post(self,request): try: present_symptoms = request.data.getlist('choices[]') absent_symptoms",
"try: selfdiary = Selfcarediary.objects.filter(user=request.user) resplist = [] for qset in selfdiary: resplist.append({\"diary\":qset.diary,\"date\":qset.date}) return",
"Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({\"test\":re}, status=status.HTTP_200_OK) # call diagnosis class Symptom(APIView): @csrf_exempt",
"rest_framework.authtoken.models import Token from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny from",
"status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk mealval =",
"= request.data.get('queryText') recordobject = Record.objects.get(user=request.user,search_query=query_text) api = infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for",
"for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request): request_data = request.data.copy() request_data[\"user\"] =",
"<gh_stars>10-100 from django.shortcuts import render, redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import",
"= api.conditions_list() # r = requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'}) return Response({\"test\":data},",
"@csrf_exempt # @api_view([\"GET\"]) # def sample_api(request): # data = {'sample_data': 123} # return",
"= { \"query\":mealval, \"timezone\": \"US/Eastern\" } result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories =",
"= Booking.objects.get(date=datebooking) bserializer = BookingSerializer(booking, data=request_data, partial=True) except: bserializer = BookingSerializer(data=request_data) if bserializer.is_valid():",
"> 5 or int(singleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must be between",
"SelfcarediarySerializer import requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def home(request): if request.user.is_authenticated(): return render(request, 'drug/home.html',{}) return",
"= {} print(\"conversion\") for dictdata in finalsearchdata: finaldict[dictdata['label']] = dictdata['id'] symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id'])",
"return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView): def post(self, request): request_data = request.data.copy() request_data[\"user\"] =",
"Record, Symptomrecord, Diseaserecord, Foodrecord, Foodlist, Selfcarediary from .serializers import NutrientsSerializer from rest_framework.views import",
"= [] print(\"reached finalserach\") for symptom in mysymptomlist: callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict",
"if bserializer.is_valid(): bserializer.save() return Response(bserializer.data, status=status.HTTP_200_OK) return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView): @csrf_exempt def",
"Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response = { \"foodlist\":foodlist, \"calories\":calories, \"fat\":fat, \"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb,",
"Response({'error': 'Invalid Credentials'}, # status=HTTP_404_NOT_FOUND) # token, restdetails = Token.objects.get_or_create(user=user) # return Response({'token':",
"return Response({\"success\": False,\"message\": \"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) if doubleroomaval",
"username and password'}, # status=HTTP_400_BAD_REQUEST) # user = authenticate(username=username, password=password) # if not",
"Symptom(APIView): @csrf_exempt def post(self,request): api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] # import pdb;",
"return render(request, 'drug/analytics.html', {}) return redirect('accounts/login') class Prescription(APIView): @csrf_exempt def post(self,request): medicname =",
"bserializer = BookingSerializer(data=request_data) if bserializer.is_valid(): bserializer.save() return Response(bserializer.data, status=status.HTTP_200_OK) return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class",
"foodlist += fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist = fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"]",
"# import Symp from .serializers import SelfcarediarySerializer import requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def home(request):",
"username = request.data.get(\"username\") # password = request.data.get(\"password\") # if username is None or",
"return Response(bserializer.data, status=status.HTTP_200_OK) return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView): @csrf_exempt def get(self, request): try:",
"= Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response = { \"foodlist\":foodlist, \"calories\":calories, \"fat\":fat, \"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita,",
"templist = {} print(\"reached templist\") for data in response: templist[\"orth\"] = data[\"orth\"] templist[\"id\"]",
"'absent') re= api.diagnosis(re).to_dict() for dictdata in re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save()",
"Record.objects.get(user=request.user,search_query=query_text) api = infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for symptom in present_symptoms: re.add_symptom(symptom,",
"password is None: # return Response({'error': 'Please provide both username and password'}, #",
"request.user.is_authenticated(): return render(request, 'drug/selfdiary.html', {}) return redirect('accounts/login') def analytics(request): if request.user.is_authenticated(): return render(request,",
"foodlist = \"\" for fooditem in result.json()[\"foods\"]: foodlist += fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"]",
"\"\" for fooditem in result.json()[\"foods\"]: foodlist += fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"]",
"present_symptoms = request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]') except AttributeError: present_symptoms = request.data.get('choices') absent_symptoms =",
"for qset in selfdiary: resplist.append({\"diary\":qset.diary,\"date\":qset.date}) return Response({\"data\":resplist}, status=status.HTTP_200_OK) except: return Response({\"success\": False}, status=status.HTTP_400_BAD_REQUEST)",
"both username and password'}, # status=HTTP_400_BAD_REQUEST) # user = authenticate(username=username, password=password) # if",
"'message': 'No details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request, user):",
"post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk sserializer = SelfcarediarySerializer(data=request_data) if sserializer.is_valid():",
"= data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt # @api_view([\"POST\"]) # @permission_classes((AllowAny,)) # def",
"for symptom in mysymptomlist: callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict = {} print(\"conversion\") for",
"Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView): def post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk",
"{}) return redirect('accounts/login.html') class ParseD(APIView): @csrf_exempt def post(self,request): sentence = request.data.get(\"text\") dbrow =",
"status=status.HTTP_200_OK) # class Search(APIView): class Diagnosis(APIView): @csrf_exempt def post(self,request): try: present_symptoms = request.data.getlist('choices[]')",
"@csrf_exempt # @api_view([\"POST\"]) # @permission_classes((AllowAny,)) # def login(request): # username = request.data.get(\"username\") #",
"render(request, 'drug/selfdiary.html', {}) return redirect('accounts/login') def analytics(request): if request.user.is_authenticated(): return render(request, 'drug/analytics.html', {})",
"import permissions, status import infermedica_api # import Symp from .serializers import SelfcarediarySerializer import",
"vitc = 0 vitd = 0 vite = 0 foodlist = \"\" for",
"0 vite = 0 foodlist = \"\" for fooditem in result.json()[\"foods\"]: foodlist +=",
"\"hasuraid\": user.id}, # status=HTTP_200_OK) # @csrf_exempt # @api_view([\"GET\"]) # def sample_api(request): # data",
"status=HTTP_400_BAD_REQUEST) # user = authenticate(username=username, password=password) # if not user: # return Response({'error':",
"Response({\"success\": False,\"message\": \"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) try: booking =",
"class Prescription(APIView): @csrf_exempt def post(self,request): medicname = request.data.get(\"text\") # import pdb; pdb.set_trace() data",
"request.data.get(\"username\") # password = request.data.get(\"password\") # if username is None or password is",
"r = requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'}) return Response({\"test\":data}, status=status.HTTP_200_OK) # class",
"int(doubleroomaval) > 5 or int(doubleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must be",
"request_data.get('doubleroomaval','') if singleroomaval != '': if int(singleroomaval) > 5 or int(singleroomaval) < 0:",
"return Response(response, status=status.HTTP_200_OK) # return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView): def post(self, request): request_data",
"details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request, user): request_data =",
"from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view, permission_classes",
"status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request, user): request_data = request.data.copy() request_data['user'] = user singleroomaval",
"api.conditions_list() # r = requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'}) return Response({\"test\":data}, status=status.HTTP_200_OK)",
"redirect('accounts/login') def loginpage(request): return render(request, 'drug/login.html', {}) def search(symptom): api = infermedica_api.get_api() data",
"0 carbs = 0 vita = 0 vitb = 0 vitc = 0",
"or int(singleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must be between 0 and",
"result.json()[\"foods\"]: foodlist += fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist = fooditem[\"full_nutrients\"]",
"Foodlist, Selfcarediary from .serializers import NutrientsSerializer from rest_framework.views import APIView from rest_framework import",
"return data def nutrients(request): if request.user.is_authenticated(): return render(request, 'drug/nutrients.html', {}) return redirect('accounts/login') def",
"redirect('accounts/login.html') class ParseD(APIView): @csrf_exempt def post(self,request): sentence = request.data.get(\"text\") dbrow = Record(user=request.user,search_query=sentence) dbrow.save()",
"= infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] # import pdb; pdb.set_trace() mysymptomlist = {} for",
"# import pdb; pdb.set_trace() data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data, status=status.HTTP_200_OK) def medication(request): if",
"symptom in mysymptomlist: callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict = {} print(\"conversion\") for dictdata",
"finaldict = {} print(\"conversion\") for dictdata in finalsearchdata: finaldict[dictdata['label']] = dictdata['id'] symprow =",
"nserializer = NutrientsSerializer(data=request.data) # if nserializer.is_valid(): # nserializer.save() return Response(response, status=status.HTTP_200_OK) # return",
"data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data, status=status.HTTP_200_OK) def medication(request): if request.user.is_authenticated(): return render(request, 'drug/medication.html',",
"Response(bserializer.data, status=status.HTTP_200_OK) return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView): @csrf_exempt def get(self, request): try: nutrients",
"symprow.save() return Response(finaldict, status=status.HTTP_200_OK) class Condition(APIView): @csrf_exempt def post(self, request): api = infermedica_api.API(app_id='945555e1',",
"from rest_framework.views import APIView from rest_framework import permissions, status import infermedica_api # import",
".models import Nutrient, Record, Symptomrecord, Diseaserecord, Foodrecord, Foodlist, Selfcarediary from .serializers import NutrientsSerializer",
"infermedica_api.get_api() data = api.search(symptom[\"orth\"]) return data def nutrients(request): if request.user.is_authenticated(): return render(request, 'drug/nutrients.html',",
"Foodrecord, Foodlist, Selfcarediary from .serializers import NutrientsSerializer from rest_framework.views import APIView from rest_framework",
"def selfdiary(request): if request.user.is_authenticated(): return render(request, 'drug/selfdiary.html', {}) return redirect('accounts/login') def analytics(request): if",
"bserializer.save() return Response(bserializer.data, status=status.HTTP_200_OK) return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView): @csrf_exempt def get(self, request):",
"{}) return redirect('accounts/login') def selfdiary(request): if request.user.is_authenticated(): return render(request, 'drug/selfdiary.html', {}) return redirect('accounts/login')",
"or int(doubleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must be between 0 and",
"mysymptomlist = {} for data in response: mysymptomlist[\"orth\"] = data[\"orth\"] mysymptomlist[\"id\"] = data[\"id\"]",
"from rest_framework.response import Response from rest_framework.views import APIView from django.contrib.auth import authenticate from",
"5 or int(singleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must be between 0",
"present_symptoms = request.data.get('choices') absent_symptoms = request.data.get('unchoices') query_text = request.data.get('queryText') recordobject = Record.objects.get(user=request.user,search_query=query_text) api",
"import Response from rest_framework.views import APIView from django.contrib.auth import authenticate from .models import",
"token, restdetails = Token.objects.get_or_create(user=user) # return Response({'token': token.key, \"hasuraid\": user.id}, # status=HTTP_200_OK) #",
"@csrf_exempt def post(self, request, user): request_data = request.data.copy() request_data['user'] = user singleroomaval =",
"0 foodlist = \"\" for fooditem in result.json()[\"foods\"]: foodlist += fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"]",
"finalsearchdata: finaldict[dictdata['label']] = dictdata['id'] symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict, status=status.HTTP_200_OK) class Condition(APIView):",
"request_data.get('meal') data = { \"query\":mealval, \"timezone\": \"US/Eastern\" } result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"})",
"render(request, 'drug/nutrients.html', {}) return redirect('accounts/login') def selfdiary(request): if request.user.is_authenticated(): return render(request, 'drug/selfdiary.html', {})",
"if username is None or password is None: # return Response({'error': 'Please provide",
"print(\"conversion\") for dictdata in finalsearchdata: finaldict[dictdata['label']] = dictdata['id'] symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return",
"data = {'sample_data': 123} # return Response(data, status=HTTP_200_OK) class HeartRateApi(APIView): @csrf_exempt def get(self,",
"@csrf_exempt def post(self,request): api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] # import pdb; pdb.set_trace()",
"Response from rest_framework.views import APIView from django.contrib.auth import authenticate from .models import Nutrient,",
"= data[\"orth\"] templist[\"id\"] = data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata = [] print(\"reached finalserach\") for symptom",
"[] templist = {} print(\"reached templist\") for data in response: templist[\"orth\"] = data[\"orth\"]",
"doubleroomaval = request_data.get('doubleroomaval','') if singleroomaval != '': if int(singleroomaval) > 5 or int(singleroomaval)",
"if singleroomaval != '': if int(singleroomaval) > 5 or int(singleroomaval) < 0: return",
"def get(self, request): try: nutrients = Nutrient.objects.all() nserializer = NutrientsSerializer(nutrients) nutrient_data = nserializer.data",
"vite = 0 foodlist = \"\" for fooditem in result.json()[\"foods\"]: foodlist += fooditem[\"food_name\"]+\";",
"= NutrientsSerializer(data=request.data) # if nserializer.is_valid(): # nserializer.save() return Response(response, status=status.HTTP_200_OK) # return Response(nserializer.errors,",
"api_view, permission_classes from rest_framework.permissions import AllowAny from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK",
"dictdata in finalsearchdata: finaldict[dictdata['label']] = dictdata['id'] symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict, status=status.HTTP_200_OK)",
"def home(request): if request.user.is_authenticated(): return render(request, 'drug/home.html',{}) return redirect('accounts/login') def loginpage(request): return render(request,",
"# nserializer = NutrientsSerializer(data=request.data) # if nserializer.is_valid(): # nserializer.save() return Response(response, status=status.HTTP_200_OK) #",
"in present_symptoms: re.add_symptom(symptom, 'present') for symptom in absent_symptoms: re.add_symptom(symptom, 'absent') re= api.diagnosis(re).to_dict() for",
"Nutrient.objects.all() nserializer = NutrientsSerializer(nutrients) nutrient_data = nserializer.data return Response(nutrient_data, status=status.HTTP_200_OK) except: return Response({'success':",
"status=HTTP_200_OK) class HeartRateApi(APIView): @csrf_exempt def get(self, request): try: heartrate = HeartRate.objects.all() hserializer =",
"restdetails = Token.objects.get_or_create(user=user) # return Response({'token': token.key, \"hasuraid\": user.id}, # status=HTTP_200_OK) # @csrf_exempt",
"None or password is None: # return Response({'error': 'Please provide both username and",
"HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework.response import Response from rest_framework.views import APIView from",
"status=status.HTTP_400_BAD_REQUEST) def get(self, request): try: selfdiary = Selfcarediary.objects.filter(user=request.user) resplist = [] for qset",
"try: present_symptoms = request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]') except AttributeError: present_symptoms = request.data.get('choices') absent_symptoms",
"user: # return Response({'error': 'Invalid Credentials'}, # status=HTTP_404_NOT_FOUND) # token, restdetails = Token.objects.get_or_create(user=user)",
"'Content-Type': 'application/json'}) return Response({\"test\":data}, status=status.HTTP_200_OK) # class Search(APIView): class Diagnosis(APIView): @csrf_exempt def post(self,request):",
"dbrow = Record(user=request.user,search_query=sentence) dbrow.save() api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist = []",
"dictdata in re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({\"test\":re}, status=status.HTTP_200_OK) #",
"request.data.get(\"text\") # import pdb; pdb.set_trace() data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data, status=status.HTTP_200_OK) def medication(request):",
"redirect('accounts/login') def analytics(request): if request.user.is_authenticated(): return render(request, 'drug/analytics.html', {}) return redirect('accounts/login') class Prescription(APIView):",
"infermedica_api # import Symp from .serializers import SelfcarediarySerializer import requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def",
"Prescription(APIView): @csrf_exempt def post(self,request): medicname = request.data.get(\"text\") # import pdb; pdb.set_trace() data =",
"vita = 0 vitb = 0 vitc = 0 vitd = 0 vite",
"# nserializer.save() return Response(response, status=status.HTTP_200_OK) # return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView): def post(self,",
"post(self,request): sentence = request.data.get(\"text\") dbrow = Record(user=request.user,search_query=sentence) dbrow.save() api = infermedica_api.get_api() response =",
"Response({\"test\":data}, status=status.HTTP_200_OK) # class Search(APIView): class Diagnosis(APIView): @csrf_exempt def post(self,request): try: present_symptoms =",
"False, 'message': 'No details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request):",
"= {'sample_data': 123} # return Response(data, status=HTTP_200_OK) class HeartRateApi(APIView): @csrf_exempt def get(self, request):",
"status=status.HTTP_200_OK) def medication(request): if request.user.is_authenticated(): return render(request, 'drug/medication.html', {}) return redirect('accounts/login.html') class ParseD(APIView):",
"request.user.is_authenticated(): return render(request, 'drug/home.html',{}) return redirect('accounts/login') def loginpage(request): return render(request, 'drug/login.html', {}) def",
"user singleroomaval = request_data.get('singleroomaval','') doubleroomaval = request_data.get('doubleroomaval','') if singleroomaval != '': if int(singleroomaval)",
"present_symptoms: re.add_symptom(symptom, 'present') for symptom in absent_symptoms: re.add_symptom(symptom, 'absent') re= api.diagnosis(re).to_dict() for dictdata",
"api.diagnosis(re).to_dict() for dictdata in re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({\"test\":re},",
"!= '': if int(singleroomaval) > 5 or int(singleroomaval) < 0: return Response({\"success\": False,\"message\":",
"False,\"message\": \"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) try: booking = Booking.objects.get(date=datebooking)",
"Symp from .serializers import SelfcarediarySerializer import requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def home(request): if request.user.is_authenticated():",
"Condition(APIView): @csrf_exempt def post(self, request): api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r = infermedica_api.Diagnosis(app_id='945555e1',",
"vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for fooditem in result.json()[\"foods\"]: foodlistobj =",
"request.data.copy() request_data['user'] = user singleroomaval = request_data.get('singleroomaval','') doubleroomaval = request_data.get('doubleroomaval','') if singleroomaval !=",
"status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView): @csrf_exempt def get(self, request): try: nutrients = Nutrient.objects.all() nserializer =",
"\"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite } # nserializer = NutrientsSerializer(data=request.data) # if nserializer.is_valid(): #",
"data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'}) return Response({\"test\":data}, status=status.HTTP_200_OK) # class Search(APIView): class Diagnosis(APIView):",
"return Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt # @api_view([\"POST\"]) # @permission_classes((AllowAny,)) # def login(request): # username",
"{}) return redirect('accounts/login') def analytics(request): if request.user.is_authenticated(): return render(request, 'drug/analytics.html', {}) return redirect('accounts/login')",
"HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework.response import Response from rest_framework.views import APIView from django.contrib.auth",
"for data in response: mysymptomlist[\"orth\"] = data[\"orth\"] mysymptomlist[\"id\"] = data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK)",
"Selfcarediary from .serializers import NutrientsSerializer from rest_framework.views import APIView from rest_framework import permissions,",
"foodlistobj.save() response = { \"foodlist\":foodlist, \"calories\":calories, \"fat\":fat, \"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc,",
"def get(self, request): try: heartrate = HeartRate.objects.all() hserializer = HeartRateSerializer(heartrate) heartrate_data = hserializer.data",
"False, 'message': 'No details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request,",
"infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for symptom in present_symptoms: re.add_symptom(symptom, 'present') for symptom in absent_symptoms: re.add_symptom(symptom,",
"request): try: heartrate = HeartRate.objects.all() hserializer = HeartRateSerializer(heartrate) heartrate_data = hserializer.data return Response(heartrate_data,",
"response: templist[\"orth\"] = data[\"orth\"] templist[\"id\"] = data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata = [] print(\"reached finalserach\")",
"\"fat\":fat, \"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite } # nserializer =",
"Response(data, status=status.HTTP_200_OK) def medication(request): if request.user.is_authenticated(): return render(request, 'drug/medication.html', {}) return redirect('accounts/login.html') class",
"vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for fooditem in result.json()[\"foods\"]: foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"])",
"\"calories\":calories, \"fat\":fat, \"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite } # nserializer",
"= 0 fat = 0 sugar = 0 protein = 0 carbs =",
"import APIView from django.contrib.auth import authenticate from .models import Nutrient, Record, Symptomrecord, Diseaserecord,",
"Response(heartrate_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details found for given date'},",
"= HeartRate.objects.all() hserializer = HeartRateSerializer(heartrate) heartrate_data = hserializer.data return Response(heartrate_data, status=status.HTTP_200_OK) except: return",
"symptom in present_symptoms: re.add_symptom(symptom, 'present') for symptom in absent_symptoms: re.add_symptom(symptom, 'absent') re= api.diagnosis(re).to_dict()",
"post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk mealval = request_data.get('meal') data =",
"result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories = 0 fat = 0 sugar =",
"import SelfcarediarySerializer import requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def home(request): if request.user.is_authenticated(): return render(request, 'drug/home.html',{})",
"'drug/analytics.html', {}) return redirect('accounts/login') class Prescription(APIView): @csrf_exempt def post(self,request): medicname = request.data.get(\"text\") #",
"for fooditem in result.json()[\"foods\"]: foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response = { \"foodlist\":foodlist, \"calories\":calories,",
"and password'}, # status=HTTP_400_BAD_REQUEST) # user = authenticate(username=username, password=password) # if not user:",
"int(singleroomaval) > 5 or int(singleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must be",
"callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict = {} print(\"conversion\") for dictdata in finalsearchdata: finaldict[dictdata['label']]",
"get(self, request): try: heartrate = HeartRate.objects.all() hserializer = HeartRateSerializer(heartrate) heartrate_data = hserializer.data return",
"Booking.objects.get(date=datebooking) bserializer = BookingSerializer(booking, data=request_data, partial=True) except: bserializer = BookingSerializer(data=request_data) if bserializer.is_valid(): bserializer.save()",
"given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request, user): request_data = request.data.copy() request_data['user'] =",
"Selfcarediary.objects.filter(user=request.user) resplist = [] for qset in selfdiary: resplist.append({\"diary\":qset.diary,\"date\":qset.date}) return Response({\"data\":resplist}, status=status.HTTP_200_OK) except:",
"re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({\"test\":re}, status=status.HTTP_200_OK) # call diagnosis",
"# @permission_classes((AllowAny,)) # def login(request): # username = request.data.get(\"username\") # password = request.data.get(\"password\")",
"fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for fooditem in",
"resplist = [] for qset in selfdiary: resplist.append({\"diary\":qset.diary,\"date\":qset.date}) return Response({\"data\":resplist}, status=status.HTTP_200_OK) except: return",
"Response(nutrient_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details found for given date'},",
"from rest_framework.views import APIView from django.contrib.auth import authenticate from .models import Nutrient, Record,",
"= SelfcarediarySerializer(data=request_data) if sserializer.is_valid(): sserializer.save() return Response(sserializer.data, status=status.HTTP_200_OK) return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self,",
"requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def home(request): if request.user.is_authenticated(): return render(request, 'drug/home.html',{}) return redirect('accounts/login') def",
"\"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) if doubleroomaval != '': if",
"0: return Response({\"success\": False,\"message\": \"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) try:",
"fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist = fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord",
"def analytics(request): if request.user.is_authenticated(): return render(request, 'drug/analytics.html', {}) return redirect('accounts/login') class Prescription(APIView): @csrf_exempt",
"re.add_symptom(symptom, 'present') for symptom in absent_symptoms: re.add_symptom(symptom, 'absent') re= api.diagnosis(re).to_dict() for dictdata in",
"render(request, 'drug/medication.html', {}) return redirect('accounts/login.html') class ParseD(APIView): @csrf_exempt def post(self,request): sentence = request.data.get(\"text\")",
"'No details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request): request_data =",
"request): try: nutrients = Nutrient.objects.all() nserializer = NutrientsSerializer(nutrients) nutrient_data = nserializer.data return Response(nutrient_data,",
"= hserializer.data return Response(heartrate_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details found",
"\"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) try: booking = Booking.objects.get(date=datebooking) bserializer",
"csrf_exempt from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import",
"request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk mealval = request_data.get('meal') data = {",
"Nutrient, Record, Symptomrecord, Diseaserecord, Foodrecord, Foodlist, Selfcarediary from .serializers import NutrientsSerializer from rest_framework.views",
"password'}, # status=HTTP_400_BAD_REQUEST) # user = authenticate(username=username, password=password) # if not user: #",
"\"vitamind\":vitd, \"vitamine\":vite } # nserializer = NutrientsSerializer(data=request.data) # if nserializer.is_valid(): # nserializer.save() return",
"return render(request, 'drug/nutrients.html', {}) return redirect('accounts/login') def selfdiary(request): if request.user.is_authenticated(): return render(request, 'drug/selfdiary.html',",
"BookingSerializer(data=request_data) if bserializer.is_valid(): bserializer.save() return Response(bserializer.data, status=status.HTTP_200_OK) return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView): @csrf_exempt",
"pdb; pdb.set_trace() data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data, status=status.HTTP_200_OK) def medication(request): if request.user.is_authenticated(): return",
"{} for data in response: mysymptomlist[\"orth\"] = data[\"orth\"] mysymptomlist[\"id\"] = data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return",
"rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny from rest_framework.status import ( HTTP_400_BAD_REQUEST,",
"medication(request): if request.user.is_authenticated(): return render(request, 'drug/medication.html', {}) return redirect('accounts/login.html') class ParseD(APIView): @csrf_exempt def",
"status=status.HTTP_400_BAD_REQUEST) if doubleroomaval != '': if int(doubleroomaval) > 5 or int(doubleroomaval) < 0:",
"for dictdata in finalsearchdata: finaldict[dictdata['label']] = dictdata['id'] symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict,",
"import render, redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token from rest_framework.decorators",
"medicname = request.data.get(\"text\") # import pdb; pdb.set_trace() data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data, status=status.HTTP_200_OK)",
"return Response(sserializer.data, status=status.HTTP_200_OK) return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): try: selfdiary = Selfcarediary.objects.filter(user=request.user)",
"= Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict, status=status.HTTP_200_OK) class Condition(APIView): @csrf_exempt def post(self, request): api",
"= api.search(symptom[\"orth\"]) return data def nutrients(request): if request.user.is_authenticated(): return render(request, 'drug/nutrients.html', {}) return",
"in result.json()[\"foods\"]: foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response = { \"foodlist\":foodlist, \"calories\":calories, \"fat\":fat, \"sugars\":sugar,",
"# def sample_api(request): # data = {'sample_data': 123} # return Response(data, status=HTTP_200_OK) class",
"= [] templist = {} print(\"reached templist\") for data in response: templist[\"orth\"] =",
"mysymptomlist[\"id\"] = data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt # @api_view([\"POST\"]) # @permission_classes((AllowAny,)) #",
"foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response = { \"foodlist\":foodlist, \"calories\":calories, \"fat\":fat, \"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs,",
"= request_data.get('singleroomaval','') doubleroomaval = request_data.get('doubleroomaval','') if singleroomaval != '': if int(singleroomaval) > 5",
"# status=HTTP_404_NOT_FOUND) # token, restdetails = Token.objects.get_or_create(user=user) # return Response({'token': token.key, \"hasuraid\": user.id},",
"5.\"}, status=status.HTTP_400_BAD_REQUEST) if doubleroomaval != '': if int(doubleroomaval) > 5 or int(doubleroomaval) <",
"request.data.copy() request_data[\"user\"] = request.user.pk mealval = request_data.get('meal') data = { \"query\":mealval, \"timezone\": \"US/Eastern\"",
"@csrf_exempt def post(self,request): try: present_symptoms = request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]') except AttributeError: present_symptoms",
"= { \"foodlist\":foodlist, \"calories\":calories, \"fat\":fat, \"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite",
"= Record(user=request.user,search_query=sentence) dbrow.save() api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist = [] templist",
"import Token from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny from rest_framework.status",
"symptom in absent_symptoms: re.add_symptom(symptom, 'absent') re= api.diagnosis(re).to_dict() for dictdata in re['conditions']: diseaseobject =",
"= request.user.pk sserializer = SelfcarediarySerializer(data=request_data) if sserializer.is_valid(): sserializer.save() return Response(sserializer.data, status=status.HTTP_200_OK) return Response(sserializer.errors,",
"5 or int(doubleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must be between 0",
"templist\") for data in response: templist[\"orth\"] = data[\"orth\"] templist[\"id\"] = data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata",
"templist[\"orth\"] = data[\"orth\"] templist[\"id\"] = data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata = [] print(\"reached finalserach\") for",
"data=request_data, partial=True) except: bserializer = BookingSerializer(data=request_data) if bserializer.is_valid(): bserializer.save() return Response(bserializer.data, status=status.HTTP_200_OK) return",
"= request.user.pk mealval = request_data.get('meal') data = { \"query\":mealval, \"timezone\": \"US/Eastern\" } result",
"if int(doubleroomaval) > 5 or int(doubleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must",
"mealval = request_data.get('meal') data = { \"query\":mealval, \"timezone\": \"US/Eastern\" } result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients',",
"# data = {'sample_data': 123} # return Response(data, status=HTTP_200_OK) class HeartRateApi(APIView): @csrf_exempt def",
"protein = 0 carbs = 0 vita = 0 vitb = 0 vitc",
"in finalsearchdata: finaldict[dictdata['label']] = dictdata['id'] symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict, status=status.HTTP_200_OK) class",
"nutrients = Nutrient.objects.all() nserializer = NutrientsSerializer(nutrients) nutrient_data = nserializer.data return Response(nutrient_data, status=status.HTTP_200_OK) except:",
"int(doubleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must be between 0 and 5.\"},",
"return Response({\"test\":data}, status=status.HTTP_200_OK) # class Search(APIView): class Diagnosis(APIView): @csrf_exempt def post(self,request): try: present_symptoms",
"} # nserializer = NutrientsSerializer(data=request.data) # if nserializer.is_valid(): # nserializer.save() return Response(response, status=status.HTTP_200_OK)",
"try: booking = Booking.objects.get(date=datebooking) bserializer = BookingSerializer(booking, data=request_data, partial=True) except: bserializer = BookingSerializer(data=request_data)",
"except: return Response({'success': False, 'message': 'No details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt",
"status=status.HTTP_200_OK) # call diagnosis class Symptom(APIView): @csrf_exempt def post(self,request): api = infermedica_api.get_api() response",
"sentence = request.data.get(\"text\") dbrow = Record(user=request.user,search_query=sentence) dbrow.save() api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"]",
"Response({'error': 'Please provide both username and password'}, # status=HTTP_400_BAD_REQUEST) # user = authenticate(username=username,",
"if request.user.is_authenticated(): return render(request, 'drug/medication.html', {}) return redirect('accounts/login.html') class ParseD(APIView): @csrf_exempt def post(self,request):",
"dbrow.save() api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist = [] templist = {}",
"return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView): @csrf_exempt def get(self, request): try: nutrients = Nutrient.objects.all()",
"Credentials'}, # status=HTTP_404_NOT_FOUND) # token, restdetails = Token.objects.get_or_create(user=user) # return Response({'token': token.key, \"hasuraid\":",
"infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for symptom in present_symptoms: re.add_symptom(symptom, 'present') for symptom",
"api = infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for symptom in present_symptoms: re.add_symptom(symptom, 'present')",
"probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({\"test\":re}, status=status.HTTP_200_OK) # call diagnosis class Symptom(APIView): @csrf_exempt def post(self,request):",
"# @api_view([\"GET\"]) # def sample_api(request): # data = {'sample_data': 123} # return Response(data,",
"import infermedica_api # import Symp from .serializers import SelfcarediarySerializer import requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de')",
"status=status.HTTP_200_OK) # return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView): def post(self, request): request_data = request.data.copy()",
"Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView): @csrf_exempt def get(self, request): try: nutrients = Nutrient.objects.all() nserializer",
"( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework.response import Response from rest_framework.views import APIView",
"None: # return Response({'error': 'Please provide both username and password'}, # status=HTTP_400_BAD_REQUEST) #",
"import APIView from rest_framework import permissions, status import infermedica_api # import Symp from",
"status=status.HTTP_200_OK) return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): try: selfdiary = Selfcarediary.objects.filter(user=request.user) resplist =",
"status=HTTP_404_NOT_FOUND) # token, restdetails = Token.objects.get_or_create(user=user) # return Response({'token': token.key, \"hasuraid\": user.id}, #",
"from django.shortcuts import render, redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token",
"= request_data.get('meal') data = { \"query\":mealval, \"timezone\": \"US/Eastern\" } result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data,",
"response = { \"foodlist\":foodlist, \"calories\":calories, \"fat\":fat, \"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd,",
"user.id}, # status=HTTP_200_OK) # @csrf_exempt # @api_view([\"GET\"]) # def sample_api(request): # data =",
"rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework.response import Response from rest_framework.views",
"class Condition(APIView): @csrf_exempt def post(self, request): api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r =",
"= data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata = [] print(\"reached finalserach\") for symptom in mysymptomlist: callsearchdata",
"in mysymptomlist: callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict = {} print(\"conversion\") for dictdata in",
"and 5.\"}, status=status.HTTP_400_BAD_REQUEST) if doubleroomaval != '': if int(doubleroomaval) > 5 or int(doubleroomaval)",
"sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist = fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord =",
"sserializer.save() return Response(sserializer.data, status=status.HTTP_200_OK) return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): try: selfdiary =",
"infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist = [] templist = {} print(\"reached templist\") for",
"= HeartRateSerializer(heartrate) heartrate_data = hserializer.data return Response(heartrate_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message':",
"user): request_data = request.data.copy() request_data['user'] = user singleroomaval = request_data.get('singleroomaval','') doubleroomaval = request_data.get('doubleroomaval','')",
"= 0 vita = 0 vitb = 0 vitc = 0 vitd =",
"authenticate from .models import Nutrient, Record, Symptomrecord, Diseaserecord, Foodrecord, Foodlist, Selfcarediary from .serializers",
"rest_framework.views import APIView from rest_framework import permissions, status import infermedica_api # import Symp",
"AttributeError: present_symptoms = request.data.get('choices') absent_symptoms = request.data.get('unchoices') query_text = request.data.get('queryText') recordobject = Record.objects.get(user=request.user,search_query=query_text)",
"search(symptom): api = infermedica_api.get_api() data = api.search(symptom[\"orth\"]) return data def nutrients(request): if request.user.is_authenticated():",
"@api_view([\"GET\"]) # def sample_api(request): # data = {'sample_data': 123} # return Response(data, status=HTTP_200_OK)",
"data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt # @api_view([\"POST\"]) # @permission_classes((AllowAny,)) # def login(request):",
"pdb.set_trace() mysymptomlist = {} for data in response: mysymptomlist[\"orth\"] = data[\"orth\"] mysymptomlist[\"id\"] =",
"request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk sserializer = SelfcarediarySerializer(data=request_data) if sserializer.is_valid(): sserializer.save()",
"def nutrients(request): if request.user.is_authenticated(): return render(request, 'drug/nutrients.html', {}) return redirect('accounts/login') def selfdiary(request): if",
"# r = requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'}) return Response({\"test\":data}, status=status.HTTP_200_OK) #",
"age=request.data.get(\"age\")) for symptom in present_symptoms: re.add_symptom(symptom, 'present') for symptom in absent_symptoms: re.add_symptom(symptom, 'absent')",
"Response({\"test\":re}, status=status.HTTP_200_OK) # call diagnosis class Symptom(APIView): @csrf_exempt def post(self,request): api = infermedica_api.get_api()",
"def post(self,request): medicname = request.data.get(\"text\") # import pdb; pdb.set_trace() data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return",
"'application/json'}) return Response({\"test\":data}, status=status.HTTP_200_OK) # class Search(APIView): class Diagnosis(APIView): @csrf_exempt def post(self,request): try:",
"# status=HTTP_200_OK) # @csrf_exempt # @api_view([\"GET\"]) # def sample_api(request): # data = {'sample_data':",
"if doubleroomaval != '': if int(doubleroomaval) > 5 or int(doubleroomaval) < 0: return",
"be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) try: booking = Booking.objects.get(date=datebooking) bserializer = BookingSerializer(booking,",
"request): try: selfdiary = Selfcarediary.objects.filter(user=request.user) resplist = [] for qset in selfdiary: resplist.append({\"diary\":qset.diary,\"date\":qset.date})",
"!= '': if int(doubleroomaval) > 5 or int(doubleroomaval) < 0: return Response({\"success\": False,\"message\":",
"return Response({\"success\": False,\"message\": \"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) try: booking",
"data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt # @api_view([\"POST\"]) # @permission_classes((AllowAny,)) # def login(request): #",
"return Response(data, status=status.HTTP_200_OK) def medication(request): if request.user.is_authenticated(): return render(request, 'drug/medication.html', {}) return redirect('accounts/login.html')",
"symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict, status=status.HTTP_200_OK) class Condition(APIView): @csrf_exempt def post(self, request):",
"request.user.is_authenticated(): return render(request, 'drug/medication.html', {}) return redirect('accounts/login.html') class ParseD(APIView): @csrf_exempt def post(self,request): sentence",
"api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] # import pdb; pdb.set_trace() mysymptomlist = {}",
"@api_view([\"POST\"]) # @permission_classes((AllowAny,)) # def login(request): # username = request.data.get(\"username\") # password =",
"SelfdiaryApi(APIView): def post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk sserializer = SelfcarediarySerializer(data=request_data)",
"is None or password is None: # return Response({'error': 'Please provide both username",
"def post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk sserializer = SelfcarediarySerializer(data=request_data) if",
"@csrf_exempt def post(self,request): sentence = request.data.get(\"text\") dbrow = Record(user=request.user,search_query=sentence) dbrow.save() api = infermedica_api.get_api()",
"if nserializer.is_valid(): # nserializer.save() return Response(response, status=status.HTTP_200_OK) # return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView):",
"django.contrib.auth import authenticate from .models import Nutrient, Record, Symptomrecord, Diseaserecord, Foodrecord, Foodlist, Selfcarediary",
"int(singleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must be between 0 and 5.\"},",
"fooditem in result.json()[\"foods\"]: foodlist += fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist",
"import Nutrient, Record, Symptomrecord, Diseaserecord, Foodrecord, Foodlist, Selfcarediary from .serializers import NutrientsSerializer from",
"= 0 vitc = 0 vitd = 0 vite = 0 foodlist =",
"booking = Booking.objects.get(date=datebooking) bserializer = BookingSerializer(booking, data=request_data, partial=True) except: bserializer = BookingSerializer(data=request_data) if",
"request, user): request_data = request.data.copy() request_data['user'] = user singleroomaval = request_data.get('singleroomaval','') doubleroomaval =",
"= BookingSerializer(data=request_data) if bserializer.is_valid(): bserializer.save() return Response(bserializer.data, status=status.HTTP_200_OK) return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView):",
"vitd = 0 vite = 0 foodlist = \"\" for fooditem in result.json()[\"foods\"]:",
"# password = request.data.get(\"password\") # if username is None or password is None:",
"app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list() # r = requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'})",
"{'sample_data': 123} # return Response(data, status=HTTP_200_OK) class HeartRateApi(APIView): @csrf_exempt def get(self, request): try:",
"def get(self, request): try: selfdiary = Selfcarediary.objects.filter(user=request.user) resplist = [] for qset in",
"# return Response({'error': 'Invalid Credentials'}, # status=HTTP_404_NOT_FOUND) # token, restdetails = Token.objects.get_or_create(user=user) #",
"import authenticate from .models import Nutrient, Record, Symptomrecord, Diseaserecord, Foodrecord, Foodlist, Selfcarediary from",
"return redirect('accounts/login') def selfdiary(request): if request.user.is_authenticated(): return render(request, 'drug/selfdiary.html', {}) return redirect('accounts/login') def",
"request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]') except AttributeError: present_symptoms = request.data.get('choices') absent_symptoms = request.data.get('unchoices') query_text",
"request_data = request.data.copy() request_data['user'] = user singleroomaval = request_data.get('singleroomaval','') doubleroomaval = request_data.get('doubleroomaval','') if",
"= Selfcarediary.objects.filter(user=request.user) resplist = [] for qset in selfdiary: resplist.append({\"diary\":qset.diary,\"date\":qset.date}) return Response({\"data\":resplist}, status=status.HTTP_200_OK)",
"re= api.diagnosis(re).to_dict() for dictdata in re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return",
"def loginpage(request): return render(request, 'drug/login.html', {}) def search(symptom): api = infermedica_api.get_api() data =",
"False,\"message\": \"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) if doubleroomaval != '':",
"\"foodlist\":foodlist, \"calories\":calories, \"fat\":fat, \"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite } #",
"render(request, 'drug/login.html', {}) def search(symptom): api = infermedica_api.get_api() data = api.search(symptom[\"orth\"]) return data",
"Response(sserializer.data, status=status.HTTP_200_OK) return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): try: selfdiary = Selfcarediary.objects.filter(user=request.user) resplist",
"from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny",
"= infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist = [] templist = {} print(\"reached templist\")",
"for symptom in absent_symptoms: re.add_symptom(symptom, 'absent') re= api.diagnosis(re).to_dict() for dictdata in re['conditions']: diseaseobject",
"import pdb; pdb.set_trace() data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data, status=status.HTTP_200_OK) def medication(request): if request.user.is_authenticated():",
"class ParseD(APIView): @csrf_exempt def post(self,request): sentence = request.data.get(\"text\") dbrow = Record(user=request.user,search_query=sentence) dbrow.save() api",
"ParseD(APIView): @csrf_exempt def post(self,request): sentence = request.data.get(\"text\") dbrow = Record(user=request.user,search_query=sentence) dbrow.save() api =",
"= Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({\"test\":re}, status=status.HTTP_200_OK) # call diagnosis class Symptom(APIView):",
"and 5.\"}, status=status.HTTP_400_BAD_REQUEST) try: booking = Booking.objects.get(date=datebooking) bserializer = BookingSerializer(booking, data=request_data, partial=True) except:",
"return redirect('accounts/login') def loginpage(request): return render(request, 'drug/login.html', {}) def search(symptom): api = infermedica_api.get_api()",
"import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework.response import Response from rest_framework.views import",
"post(self, request): api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data =",
"def post(self,request): sentence = request.data.get(\"text\") dbrow = Record(user=request.user,search_query=sentence) dbrow.save() api = infermedica_api.get_api() response",
"class Search(APIView): class Diagnosis(APIView): @csrf_exempt def post(self,request): try: present_symptoms = request.data.getlist('choices[]') absent_symptoms =",
"request.data.copy() request_data[\"user\"] = request.user.pk sserializer = SelfcarediarySerializer(data=request_data) if sserializer.is_valid(): sserializer.save() return Response(sserializer.data, status=status.HTTP_200_OK)",
"data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata = [] print(\"reached finalserach\") for symptom in mysymptomlist: callsearchdata =",
"Response(finaldict, status=status.HTTP_200_OK) class Condition(APIView): @csrf_exempt def post(self, request): api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') #",
"return Response({'success': False, 'message': 'No details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def",
"headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories = 0 fat = 0 sugar = 0 protein = 0",
"partial=True) except: bserializer = BookingSerializer(data=request_data) if bserializer.is_valid(): bserializer.save() return Response(bserializer.data, status=status.HTTP_200_OK) return Response(bserializer.errors,",
"# username = request.data.get(\"username\") # password = request.data.get(\"password\") # if username is None",
"# status=HTTP_400_BAD_REQUEST) # user = authenticate(username=username, password=password) # if not user: # return",
"= nserializer.data return Response(nutrient_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details found",
"api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist = [] templist = {} print(\"reached",
"response = api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist = [] templist = {} print(\"reached templist\") for data",
"fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist = fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"]",
"= request.data.get('choices') absent_symptoms = request.data.get('unchoices') query_text = request.data.get('queryText') recordobject = Record.objects.get(user=request.user,search_query=query_text) api =",
"details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request): request_data = request.data.copy()",
"render, redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token from rest_framework.decorators import",
"mysymptomlist.append(templist.copy()) finalsearchdata = [] print(\"reached finalserach\") for symptom in mysymptomlist: callsearchdata = api.search(symptom['orth'])",
"Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): try: selfdiary = Selfcarediary.objects.filter(user=request.user) resplist = [] for",
"Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for fooditem in result.json()[\"foods\"]: foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response = {",
"= request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]') except AttributeError: present_symptoms = request.data.get('choices') absent_symptoms = request.data.get('unchoices')",
"@csrf_exempt def post(self, request): api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de')",
"# if username is None or password is None: # return Response({'error': 'Please",
"return redirect('accounts/login') def analytics(request): if request.user.is_authenticated(): return render(request, 'drug/analytics.html', {}) return redirect('accounts/login') class",
"request_data = request.data.copy() request_data[\"user\"] = request.user.pk mealval = request_data.get('meal') data = { \"query\":mealval,",
".serializers import SelfcarediarySerializer import requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def home(request): if request.user.is_authenticated(): return render(request,",
"import Symp from .serializers import SelfcarediarySerializer import requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def home(request): if",
"def search(symptom): api = infermedica_api.get_api() data = api.search(symptom[\"orth\"]) return data def nutrients(request): if",
"= request.data.copy() request_data[\"user\"] = request.user.pk sserializer = SelfcarediarySerializer(data=request_data) if sserializer.is_valid(): sserializer.save() return Response(sserializer.data,",
"absent_symptoms = request.data.getlist('unchoices[]') except AttributeError: present_symptoms = request.data.get('choices') absent_symptoms = request.data.get('unchoices') query_text =",
"0 fat = 0 sugar = 0 protein = 0 carbs = 0",
"'drug/medication.html', {}) return redirect('accounts/login.html') class ParseD(APIView): @csrf_exempt def post(self,request): sentence = request.data.get(\"text\") dbrow",
"hserializer = HeartRateSerializer(heartrate) heartrate_data = hserializer.data return Response(heartrate_data, status=status.HTTP_200_OK) except: return Response({'success': False,",
"must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) if doubleroomaval != '': if int(doubleroomaval)",
"Token.objects.get_or_create(user=user) # return Response({'token': token.key, \"hasuraid\": user.id}, # status=HTTP_200_OK) # @csrf_exempt # @api_view([\"GET\"])",
"# @csrf_exempt # @api_view([\"POST\"]) # @permission_classes((AllowAny,)) # def login(request): # username = request.data.get(\"username\")",
"calories = 0 fat = 0 sugar = 0 protein = 0 carbs",
"infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] # import pdb; pdb.set_trace() mysymptomlist = {} for data",
"\" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist = fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"]",
"class Diagnosis(APIView): @csrf_exempt def post(self,request): try: present_symptoms = request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]') except",
"status=status.HTTP_200_OK) class Condition(APIView): @csrf_exempt def post(self, request): api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r",
"# return Response({'error': 'Please provide both username and password'}, # status=HTTP_400_BAD_REQUEST) # user",
"r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list() # r = requests.post(url, data=json.dumps({'text': text}),headers={'Authorization':",
"\"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite } # nserializer = NutrientsSerializer(data=request.data) # if nserializer.is_valid(): # nserializer.save()",
"= infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for symptom in present_symptoms: re.add_symptom(symptom, 'present') for",
"= requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'}) return Response({\"test\":data}, status=status.HTTP_200_OK) # class Search(APIView):",
"Record(user=request.user,search_query=sentence) dbrow.save() api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist = [] templist =",
"date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk mealval",
"= Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for fooditem in result.json()[\"foods\"]: foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response =",
"import requests,json infermedica_api.configure(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') def home(request): if request.user.is_authenticated(): return render(request, 'drug/home.html',{}) return redirect('accounts/login')",
"= dictdata['id'] symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict, status=status.HTTP_200_OK) class Condition(APIView): @csrf_exempt def",
"= Token.objects.get_or_create(user=user) # return Response({'token': token.key, \"hasuraid\": user.id}, # status=HTTP_200_OK) # @csrf_exempt #",
"return render(request, 'drug/home.html',{}) return redirect('accounts/login') def loginpage(request): return render(request, 'drug/login.html', {}) def search(symptom):",
"def post(self, request): api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data",
"@csrf_exempt def get(self, request): try: nutrients = Nutrient.objects.all() nserializer = NutrientsSerializer(nutrients) nutrient_data =",
"= request.data.get(\"text\") dbrow = Record(user=request.user,search_query=sentence) dbrow.save() api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist",
"status import infermedica_api # import Symp from .serializers import SelfcarediarySerializer import requests,json infermedica_api.configure(app_id='945555e1',",
"if request.user.is_authenticated(): return render(request, 'drug/selfdiary.html', {}) return redirect('accounts/login') def analytics(request): if request.user.is_authenticated(): return",
"'message': 'No details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request): request_data",
"from .serializers import NutrientsSerializer from rest_framework.views import APIView from rest_framework import permissions, status",
"api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist = [] templist = {} print(\"reached templist\") for data in response:",
"finaldict[dictdata['label']] = dictdata['id'] symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict, status=status.HTTP_200_OK) class Condition(APIView): @csrf_exempt",
"request.user.pk mealval = request_data.get('meal') data = { \"query\":mealval, \"timezone\": \"US/Eastern\" } result =",
"def medication(request): if request.user.is_authenticated(): return render(request, 'drug/medication.html', {}) return redirect('accounts/login.html') class ParseD(APIView): @csrf_exempt",
"request.user.is_authenticated(): return render(request, 'drug/analytics.html', {}) return redirect('accounts/login') class Prescription(APIView): @csrf_exempt def post(self,request): medicname",
"password = request.data.get(\"password\") # if username is None or password is None: #",
"user = authenticate(username=username, password=password) # if not user: # return Response({'error': 'Invalid Credentials'},",
"= user singleroomaval = request_data.get('singleroomaval','') doubleroomaval = request_data.get('doubleroomaval','') if singleroomaval != '': if",
"+= fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist = fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"]",
"'Please provide both username and password'}, # status=HTTP_400_BAD_REQUEST) # user = authenticate(username=username, password=password)",
"{}) def search(symptom): api = infermedica_api.get_api() data = api.search(symptom[\"orth\"]) return data def nutrients(request):",
"return Response(finaldict, status=status.HTTP_200_OK) class Condition(APIView): @csrf_exempt def post(self, request): api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de')",
"= 0 vitd = 0 vite = 0 foodlist = \"\" for fooditem",
"= requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories = 0 fat = 0 sugar = 0",
"request): api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list()",
"> 5 or int(doubleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must be between",
"0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) if doubleroomaval != '': if int(doubleroomaval) > 5 or",
"data = { \"query\":mealval, \"timezone\": \"US/Eastern\" } result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories",
"= request.data.get(\"text\") # import pdb; pdb.set_trace() data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data, status=status.HTTP_200_OK) def",
"= {} print(\"reached templist\") for data in response: templist[\"orth\"] = data[\"orth\"] templist[\"id\"] =",
"import api_view, permission_classes from rest_framework.permissions import AllowAny from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND,",
"response = api.parse(sentence).to_dict()[\"mentions\"] # import pdb; pdb.set_trace() mysymptomlist = {} for data in",
"'present') for symptom in absent_symptoms: re.add_symptom(symptom, 'absent') re= api.diagnosis(re).to_dict() for dictdata in re['conditions']:",
"redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view,",
"request.data.get(\"text\") dbrow = Record(user=request.user,search_query=sentence) dbrow.save() api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist =",
"= infermedica_api.get_api() data = api.search(symptom[\"orth\"]) return data def nutrients(request): if request.user.is_authenticated(): return render(request,",
"= api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict = {} print(\"conversion\") for dictdata in finalsearchdata: finaldict[dictdata['label']] =",
"nutrient_data = nserializer.data return Response(nutrient_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details",
"Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict, status=status.HTTP_200_OK) class Condition(APIView): @csrf_exempt def post(self, request): api =",
"0 vitd = 0 vite = 0 foodlist = \"\" for fooditem in",
"in response: templist[\"orth\"] = data[\"orth\"] templist[\"id\"] = data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata = [] print(\"reached",
"analytics(request): if request.user.is_authenticated(): return render(request, 'drug/analytics.html', {}) return redirect('accounts/login') class Prescription(APIView): @csrf_exempt def",
"AllowAny from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework.response import Response",
"from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny from rest_framework.status import (",
"sserializer.is_valid(): sserializer.save() return Response(sserializer.data, status=status.HTTP_200_OK) return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): try: selfdiary",
"0 sugar = 0 protein = 0 carbs = 0 vita = 0",
"app_key='be2ee424c225c567086a084637a359de') def home(request): if request.user.is_authenticated(): return render(request, 'drug/home.html',{}) return redirect('accounts/login') def loginpage(request): return",
"HeartRateApi(APIView): @csrf_exempt def get(self, request): try: heartrate = HeartRate.objects.all() hserializer = HeartRateSerializer(heartrate) heartrate_data",
"0 vitb = 0 vitc = 0 vitd = 0 vite = 0",
"= request.data.get('unchoices') query_text = request.data.get('queryText') recordobject = Record.objects.get(user=request.user,search_query=query_text) api = infermedica_api.get_api() re =",
"Diseaserecord, Foodrecord, Foodlist, Selfcarediary from .serializers import NutrientsSerializer from rest_framework.views import APIView from",
"# r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list() # r = requests.post(url, data=json.dumps({'text':",
"request.data.getlist('unchoices[]') except AttributeError: present_symptoms = request.data.get('choices') absent_symptoms = request.data.get('unchoices') query_text = request.data.get('queryText') recordobject",
"recordobject = Record.objects.get(user=request.user,search_query=query_text) api = infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for symptom in",
"HeartRate.objects.all() hserializer = HeartRateSerializer(heartrate) heartrate_data = hserializer.data return Response(heartrate_data, status=status.HTTP_200_OK) except: return Response({'success':",
"status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView): def post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk sserializer",
"APIView from django.contrib.auth import authenticate from .models import Nutrient, Record, Symptomrecord, Diseaserecord, Foodrecord,",
"return Response({'error': 'Please provide both username and password'}, # status=HTTP_400_BAD_REQUEST) # user =",
"HTTP_200_OK ) from rest_framework.response import Response from rest_framework.views import APIView from django.contrib.auth import",
"post(self,request): api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] # import pdb; pdb.set_trace() mysymptomlist =",
"requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'}) return Response({\"test\":data}, status=status.HTTP_200_OK) # class Search(APIView): class",
"in absent_symptoms: re.add_symptom(symptom, 'absent') re= api.diagnosis(re).to_dict() for dictdata in re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject,",
"vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for fooditem in result.json()[\"foods\"]: foodlistobj",
"return Response({'error': 'Invalid Credentials'}, # status=HTTP_404_NOT_FOUND) # token, restdetails = Token.objects.get_or_create(user=user) # return",
"status=HTTP_200_OK) # @csrf_exempt # @api_view([\"GET\"]) # def sample_api(request): # data = {'sample_data': 123}",
"diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({\"test\":re}, status=status.HTTP_200_OK) # call diagnosis class",
"# token, restdetails = Token.objects.get_or_create(user=user) # return Response({'token': token.key, \"hasuraid\": user.id}, # status=HTTP_200_OK)",
"{ \"query\":mealval, \"timezone\": \"US/Eastern\" } result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories = 0",
"= Nutrient.objects.all() nserializer = NutrientsSerializer(nutrients) nutrient_data = nserializer.data return Response(nutrient_data, status=status.HTTP_200_OK) except: return",
"if int(singleroomaval) > 5 or int(singleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability must",
"try: heartrate = HeartRate.objects.all() hserializer = HeartRateSerializer(heartrate) heartrate_data = hserializer.data return Response(heartrate_data, status=status.HTTP_200_OK)",
"= requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data, status=status.HTTP_200_OK) def medication(request): if request.user.is_authenticated(): return render(request, 'drug/medication.html', {})",
"doubleroomaval != '': if int(doubleroomaval) > 5 or int(doubleroomaval) < 0: return Response({\"success\":",
"redirect('accounts/login') class Prescription(APIView): @csrf_exempt def post(self,request): medicname = request.data.get(\"text\") # import pdb; pdb.set_trace()",
"or password is None: # return Response({'error': 'Please provide both username and password'},",
"carbs = 0 vita = 0 vitb = 0 vitc = 0 vitd",
"= request.data.get(\"username\") # password = request.data.get(\"password\") # if username is None or password",
"\"vitamine\":vite } # nserializer = NutrientsSerializer(data=request.data) # if nserializer.is_valid(): # nserializer.save() return Response(response,",
"permissions, status import infermedica_api # import Symp from .serializers import SelfcarediarySerializer import requests,json",
"\"timezone\": \"US/Eastern\" } result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories = 0 fat =",
"0 vita = 0 vitb = 0 vitc = 0 vitd = 0",
"data[\"orth\"] mysymptomlist[\"id\"] = data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt # @api_view([\"POST\"]) # @permission_classes((AllowAny,))",
"# def login(request): # username = request.data.get(\"username\") # password = request.data.get(\"password\") # if",
"foodrecord.save() for fooditem in result.json()[\"foods\"]: foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response = { \"foodlist\":foodlist,",
"return redirect('accounts/login') class Prescription(APIView): @csrf_exempt def post(self,request): medicname = request.data.get(\"text\") # import pdb;",
"rest_framework.permissions import AllowAny from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework.response",
"= 0 vite = 0 foodlist = \"\" for fooditem in result.json()[\"foods\"]: foodlist",
"0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) try: booking = Booking.objects.get(date=datebooking) bserializer = BookingSerializer(booking, data=request_data, partial=True)",
"found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request): request_data = request.data.copy() request_data[\"user\"]",
"render(request, 'drug/analytics.html', {}) return redirect('accounts/login') class Prescription(APIView): @csrf_exempt def post(self,request): medicname = request.data.get(\"text\")",
"authenticate(username=username, password=password) # if not user: # return Response({'error': 'Invalid Credentials'}, # status=HTTP_404_NOT_FOUND)",
"date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request, user): request_data = request.data.copy() request_data['user'] = user",
"print(\"reached finalserach\") for symptom in mysymptomlist: callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict = {}",
"requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data, status=status.HTTP_200_OK) def medication(request): if request.user.is_authenticated(): return render(request, 'drug/medication.html', {}) return",
"request.data.get('unchoices') query_text = request.data.get('queryText') recordobject = Record.objects.get(user=request.user,search_query=query_text) api = infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"),",
"{ \"foodlist\":foodlist, \"calories\":calories, \"fat\":fat, \"sugars\":sugar, \"protein\":protein, \"carbohydrates\":carbs, \"vitamina\":vita, \"vitaminbcomplex\":vitb, \"vitaminc\":vitc, \"vitamind\":vitd, \"vitamine\":vite }",
"singleroomaval = request_data.get('singleroomaval','') doubleroomaval = request_data.get('doubleroomaval','') if singleroomaval != '': if int(singleroomaval) >",
"in re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({\"test\":re}, status=status.HTTP_200_OK) # call",
"NutrientsSerializer from rest_framework.views import APIView from rest_framework import permissions, status import infermedica_api #",
"Response({'success': False, 'message': 'No details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self,",
"def login(request): # username = request.data.get(\"username\") # password = request.data.get(\"password\") # if username",
"123} # return Response(data, status=HTTP_200_OK) class HeartRateApi(APIView): @csrf_exempt def get(self, request): try: heartrate",
"{}) return redirect('accounts/login') class Prescription(APIView): @csrf_exempt def post(self,request): medicname = request.data.get(\"text\") # import",
"Response(data, status=HTTP_200_OK) class HeartRateApi(APIView): @csrf_exempt def get(self, request): try: heartrate = HeartRate.objects.all() hserializer",
"5.\"}, status=status.HTTP_400_BAD_REQUEST) try: booking = Booking.objects.get(date=datebooking) bserializer = BookingSerializer(booking, data=request_data, partial=True) except: bserializer",
"{} print(\"conversion\") for dictdata in finalsearchdata: finaldict[dictdata['label']] = dictdata['id'] symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save()",
"= 0 vitb = 0 vitc = 0 vitd = 0 vite =",
"infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list() # r = requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type':",
"singleroomaval != '': if int(singleroomaval) > 5 or int(singleroomaval) < 0: return Response({\"success\":",
"return Response({'token': token.key, \"hasuraid\": user.id}, # status=HTTP_200_OK) # @csrf_exempt # @api_view([\"GET\"]) # def",
"= [] for qset in selfdiary: resplist.append({\"diary\":qset.diary,\"date\":qset.date}) return Response({\"data\":resplist}, status=status.HTTP_200_OK) except: return Response({\"success\":",
"nserializer.is_valid(): # nserializer.save() return Response(response, status=status.HTTP_200_OK) # return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class SelfdiaryApi(APIView): def",
"username is None or password is None: # return Response({'error': 'Please provide both",
"heartrate_data = hserializer.data return Response(heartrate_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details",
"Response({\"success\": False,\"message\": \"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST) if doubleroomaval !=",
"get(self, request): try: nutrients = Nutrient.objects.all() nserializer = NutrientsSerializer(nutrients) nutrient_data = nserializer.data return",
"def post(self,request): api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"] # import pdb; pdb.set_trace() mysymptomlist",
"return Response(data, status=HTTP_200_OK) class HeartRateApi(APIView): @csrf_exempt def get(self, request): try: heartrate = HeartRate.objects.all()",
"# call diagnosis class Symptom(APIView): @csrf_exempt def post(self,request): api = infermedica_api.get_api() response =",
"if request.user.is_authenticated(): return render(request, 'drug/nutrients.html', {}) return redirect('accounts/login') def selfdiary(request): if request.user.is_authenticated(): return",
"mysymptomlist[\"orth\"] = data[\"orth\"] mysymptomlist[\"id\"] = data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt # @api_view([\"POST\"])",
"class HeartRateApi(APIView): @csrf_exempt def get(self, request): try: heartrate = HeartRate.objects.all() hserializer = HeartRateSerializer(heartrate)",
"probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({\"test\":re}, status=status.HTTP_200_OK) # call diagnosis class Symptom(APIView): @csrf_exempt def",
"vitb = 0 vitc = 0 vitd = 0 vite = 0 foodlist",
"= api.parse(sentence).to_dict()[\"mentions\"] mysymptomlist = [] templist = {} print(\"reached templist\") for data in",
"def sample_api(request): # data = {'sample_data': 123} # return Response(data, status=HTTP_200_OK) class HeartRateApi(APIView):",
"permission_classes from rest_framework.permissions import AllowAny from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK )",
"= 0 sugar = 0 protein = 0 carbs = 0 vita =",
"return Response(sserializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): try: selfdiary = Selfcarediary.objects.filter(user=request.user) resplist = []",
"bserializer = BookingSerializer(booking, data=request_data, partial=True) except: bserializer = BookingSerializer(data=request_data) if bserializer.is_valid(): bserializer.save() return",
"except: bserializer = BookingSerializer(data=request_data) if bserializer.is_valid(): bserializer.save() return Response(bserializer.data, status=status.HTTP_200_OK) return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST)",
"from .models import Nutrient, Record, Symptomrecord, Diseaserecord, Foodrecord, Foodlist, Selfcarediary from .serializers import",
"'drug/login.html', {}) def search(symptom): api = infermedica_api.get_api() data = api.search(symptom[\"orth\"]) return data def",
"def post(self,request): try: present_symptoms = request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]') except AttributeError: present_symptoms =",
"data in response: mysymptomlist[\"orth\"] = data[\"orth\"] mysymptomlist[\"id\"] = data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"])) return Response({\"test\":data},status=status.HTTP_200_OK) #",
"mysymptomlist = [] templist = {} print(\"reached templist\") for data in response: templist[\"orth\"]",
"# @csrf_exempt # @api_view([\"GET\"]) # def sample_api(request): # data = {'sample_data': 123} #",
"'No details found for given date'}, status=status.HTTP_400_BAD_REQUEST) @csrf_exempt def post(self, request, user): request_data",
"nutlist = fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for",
"= 0 protein = 0 carbs = 0 vita = 0 vitb =",
"request_data[\"user\"] = request.user.pk sserializer = SelfcarediarySerializer(data=request_data) if sserializer.is_valid(): sserializer.save() return Response(sserializer.data, status=status.HTTP_200_OK) return",
"'drug/selfdiary.html', {}) return redirect('accounts/login') def analytics(request): if request.user.is_authenticated(): return render(request, 'drug/analytics.html', {}) return",
"for symptom in present_symptoms: re.add_symptom(symptom, 'present') for symptom in absent_symptoms: re.add_symptom(symptom, 'absent') re=",
"pdb.set_trace() data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data, status=status.HTTP_200_OK) def medication(request): if request.user.is_authenticated(): return render(request,",
"data = api.conditions_list() # r = requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'}) return",
"# user = authenticate(username=username, password=password) # if not user: # return Response({'error': 'Invalid",
"api = infermedica_api.get_api() data = api.search(symptom[\"orth\"]) return data def nutrients(request): if request.user.is_authenticated(): return",
"templist[\"id\"] = data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata = [] print(\"reached finalserach\") for symptom in mysymptomlist:",
"Diagnosis(APIView): @csrf_exempt def post(self,request): try: present_symptoms = request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]') except AttributeError:",
"bserializer.is_valid(): bserializer.save() return Response(bserializer.data, status=status.HTTP_200_OK) return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView): @csrf_exempt def get(self,",
"carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist = fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"] foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save()",
"@csrf_exempt def post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk mealval = request_data.get('meal')",
"# if nserializer.is_valid(): # nserializer.save() return Response(response, status=status.HTTP_200_OK) # return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST) class",
"NutrientsSerializer(nutrients) nutrient_data = nserializer.data return Response(nutrient_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No",
"nserializer = NutrientsSerializer(nutrients) nutrient_data = nserializer.data return Response(nutrient_data, status=status.HTTP_200_OK) except: return Response({'success': False,",
"selfdiary = Selfcarediary.objects.filter(user=request.user) resplist = [] for qset in selfdiary: resplist.append({\"diary\":qset.diary,\"date\":qset.date}) return Response({\"data\":resplist},",
"# return Response({'token': token.key, \"hasuraid\": user.id}, # status=HTTP_200_OK) # @csrf_exempt # @api_view([\"GET\"]) #",
"request.data.get(\"password\") # if username is None or password is None: # return Response({'error':",
"< 0: return Response({\"success\": False,\"message\": \"Availability must be between 0 and 5.\"}, status=status.HTTP_400_BAD_REQUEST)",
"= authenticate(username=username, password=password) # if not user: # return Response({'error': 'Invalid Credentials'}, #",
"mysymptomlist: callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict = {} print(\"conversion\") for dictdata in finalsearchdata:",
"data[\"orth\"] templist[\"id\"] = data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata = [] print(\"reached finalserach\") for symptom in",
"request.data.get('choices') absent_symptoms = request.data.get('unchoices') query_text = request.data.get('queryText') recordobject = Record.objects.get(user=request.user,search_query=query_text) api = infermedica_api.get_api()",
"post(self,request): medicname = request.data.get(\"text\") # import pdb; pdb.set_trace() data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json() return Response(data,",
"def post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk mealval = request_data.get('meal') data",
"# @api_view([\"POST\"]) # @permission_classes((AllowAny,)) # def login(request): # username = request.data.get(\"username\") # password",
"absent_symptoms: re.add_symptom(symptom, 'absent') re= api.diagnosis(re).to_dict() for dictdata in re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'],",
"query_text = request.data.get('queryText') recordobject = Record.objects.get(user=request.user,search_query=query_text) api = infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\"))",
"data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories = 0 fat = 0 sugar = 0 protein =",
"= NutrientsSerializer(nutrients) nutrient_data = nserializer.data return Response(nutrient_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message':",
"Search(APIView): class Diagnosis(APIView): @csrf_exempt def post(self,request): try: present_symptoms = request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]')",
"api.search(symptom[\"orth\"]) return data def nutrients(request): if request.user.is_authenticated(): return render(request, 'drug/nutrients.html', {}) return redirect('accounts/login')",
"not user: # return Response({'error': 'Invalid Credentials'}, # status=HTTP_404_NOT_FOUND) # token, restdetails =",
"return render(request, 'drug/login.html', {}) def search(symptom): api = infermedica_api.get_api() data = api.search(symptom[\"orth\"]) return",
"if request.user.is_authenticated(): return render(request, 'drug/analytics.html', {}) return redirect('accounts/login') class Prescription(APIView): @csrf_exempt def post(self,request):",
"re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for symptom in present_symptoms: re.add_symptom(symptom, 'present') for symptom in",
"data in response: templist[\"orth\"] = data[\"orth\"] templist[\"id\"] = data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata = []",
"= BookingSerializer(booking, data=request_data, partial=True) except: bserializer = BookingSerializer(data=request_data) if bserializer.is_valid(): bserializer.save() return Response(bserializer.data,",
"for data in response: templist[\"orth\"] = data[\"orth\"] templist[\"id\"] = data[\"id\"] mysymptomlist.append(templist.copy()) finalsearchdata =",
"import AllowAny from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework.response import",
"= Record.objects.get(user=request.user,search_query=query_text) api = infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for symptom in present_symptoms:",
"= infermedica_api.Diagnosis(sex=request.data.get(\"gender\"), age=request.data.get(\"age\")) for symptom in present_symptoms: re.add_symptom(symptom, 'present') for symptom in absent_symptoms:",
"api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict = {} print(\"conversion\") for dictdata in finalsearchdata: finaldict[dictdata['label']] = dictdata['id']",
".serializers import NutrientsSerializer from rest_framework.views import APIView from rest_framework import permissions, status import",
"return Response({\"test\":re}, status=status.HTTP_200_OK) # call diagnosis class Symptom(APIView): @csrf_exempt def post(self,request): api =",
"sugar = 0 protein = 0 carbs = 0 vita = 0 vitb",
"in result.json()[\"foods\"]: foodlist += fooditem[\"food_name\"]+\"; \" calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist =",
"# return Response(data, status=HTTP_200_OK) class HeartRateApi(APIView): @csrf_exempt def get(self, request): try: heartrate =",
"Response({'token': token.key, \"hasuraid\": user.id}, # status=HTTP_200_OK) # @csrf_exempt # @api_view([\"GET\"]) # def sample_api(request):",
"dictdata['id'] symprow = Symptomrecord(user_record=dbrow,present_symptoms=dictdata['label'],present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict, status=status.HTTP_200_OK) class Condition(APIView): @csrf_exempt def post(self,",
"finalserach\") for symptom in mysymptomlist: callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict = {} print(\"conversion\")",
"result.json()[\"foods\"]: foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response = { \"foodlist\":foodlist, \"calories\":calories, \"fat\":fat, \"sugars\":sugar, \"protein\":protein,",
"post(self,request): try: present_symptoms = request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]') except AttributeError: present_symptoms = request.data.get('choices')",
"loginpage(request): return render(request, 'drug/login.html', {}) def search(symptom): api = infermedica_api.get_api() data = api.search(symptom[\"orth\"])",
"nserializer.data return Response(nutrient_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details found for",
"import pdb; pdb.set_trace() mysymptomlist = {} for data in response: mysymptomlist[\"orth\"] = data[\"orth\"]",
"'': if int(singleroomaval) > 5 or int(singleroomaval) < 0: return Response({\"success\": False,\"message\": \"Availability",
"foodrecord = Foodrecord(user=request.user,search_query=mealval,calories=calories,fat=fat,sugars=sugar,protein=protein,carbohydrates=carbs,vitamina=vita,vitaminbcomplex=vitb,vitaminc=vitc,vitamind=vitd,vitamine=vite) foodrecord.save() for fooditem in result.json()[\"foods\"]: foodlistobj = Foodlist(food_record=foodrecord,food_item=fooditem[\"food_name\"]) foodlistobj.save() response",
"NutrientsSerializer(data=request.data) # if nserializer.is_valid(): # nserializer.save() return Response(response, status=status.HTTP_200_OK) # return Response(nserializer.errors, status=status.HTTP_400_BAD_REQUEST)",
"class SelfdiaryApi(APIView): def post(self, request): request_data = request.data.copy() request_data[\"user\"] = request.user.pk sserializer =",
"BookingSerializer(booking, data=request_data, partial=True) except: bserializer = BookingSerializer(data=request_data) if bserializer.is_valid(): bserializer.save() return Response(bserializer.data, status=status.HTTP_200_OK)",
"nutrients(request): if request.user.is_authenticated(): return render(request, 'drug/nutrients.html', {}) return redirect('accounts/login') def selfdiary(request): if request.user.is_authenticated():",
"return Response(nutrient_data, status=status.HTTP_200_OK) except: return Response({'success': False, 'message': 'No details found for given",
"= {} for data in response: mysymptomlist[\"orth\"] = data[\"orth\"] mysymptomlist[\"id\"] = data[\"id\"] data.append(api.symptom_details(mysymptomlist[\"id\"]))",
"Response({\"test\":data},status=status.HTTP_200_OK) # @csrf_exempt # @api_view([\"POST\"]) # @permission_classes((AllowAny,)) # def login(request): # username =",
"0 vitc = 0 vitd = 0 vite = 0 foodlist = \"\"",
"calories+=fooditem[\"nf_calories\"] fat+=fooditem[\"nf_total_fat\"] sugar+=fooditem[\"nf_sugars\"] protein+=fooditem[\"nf_protein\"] carbs+=fooditem[\"nf_total_carbohydrate\"] nutlist = fooditem[\"full_nutrients\"] vita+=nutlist[22][\"value\"]+nutlist[24][\"value\"] vitb+=nutlist[38][\"value\"]+nutlist[40][\"value\"] vitc+=nutlist[33][\"value\"] vitd+=nutlist[29][\"value\"] vite+=nutlist[27][\"value\"]",
"rest_framework.response import Response from rest_framework.views import APIView from django.contrib.auth import authenticate from .models",
"call diagnosis class Symptom(APIView): @csrf_exempt def post(self,request): api = infermedica_api.get_api() response = api.parse(sentence).to_dict()[\"mentions\"]",
"@csrf_exempt def post(self,request): medicname = request.data.get(\"text\") # import pdb; pdb.set_trace() data = requests.get(\"https://api.fda.gov/drug/label.json?search=\"+medicname).json()",
"\"US/Eastern\" } result = requests.post('https://trackapi.nutritionix.com/v2/natural/nutrients', data, headers={\"x-app-id\":\"94f5edb6\",\"x-app-key\":\"8bb3ae712275e9810ceec3b583e2727d\"}) calories = 0 fat = 0",
"from rest_framework import permissions, status import infermedica_api # import Symp from .serializers import",
"status=status.HTTP_200_OK) return Response(bserializer.errors, status=status.HTTP_400_BAD_REQUEST) class NutrientsApi(APIView): @csrf_exempt def get(self, request): try: nutrients ="
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"KIND, either express or implied. # See the License for the specific language",
"the License. \"\"\" Description of the module tasks.paraphraser: The task of the module",
"Unless required by applicable law or agreed to in writing, software # distributed",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"License. # You may obtain a copy of the License at # #",
"MIPT # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"\"\"\" Description of the module tasks.paraphraser: The task of the module To provide",
"batches and feeds the to the agents.paraphraser module for training (feeds the whole",
"agents.paraphraser module. For this the dataset with paraphrases in russian posted on the",
"the '--bagging-folds-number' parameter. Each fold is then used once as a validation while",
"Namely, the data is divided into k folds, where k equals to the",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"for the validation. Namely, the data is divided into k folds, where k",
"compliance with the License. # You may obtain a copy of the License",
"data for the agents.paraphraser module. For this the dataset with paraphrases in russian",
"posted on the site [1] is used. The module downloads train and test",
"module downloads train and test parts of the data. Then it shuffles, splits",
"the validation. Namely, the data is divided into k folds, where k equals",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"the agents.paraphraser module. For this the dataset with paraphrases in russian posted on",
"this file except in compliance with the License. # You may obtain a",
"and Deep Learning lab, MIPT # # Licensed under the Apache License, Version",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"this the dataset with paraphrases in russian posted on the site [1] is",
"[1] is used. The module downloads train and test parts of the data.",
"for the agents.paraphraser module. For this the dataset with paraphrases in russian posted",
"Deep Learning lab, MIPT # # Licensed under the Apache License, Version 2.0",
"of the data is reserved for the validation. Namely, the data is divided",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"while the k - 1 remaining folds form the training set. [1] http://paraphraser.ru/",
"the agents.paraphraser module for training (feeds the whole dataset for testing). The part",
"to the '--bagging-folds-number' parameter. Each fold is then used once as a validation",
"'--bagging-folds-number' parameter. Each fold is then used once as a validation while the",
"the specific language governing permissions and # limitations under the License. \"\"\" Description",
"ANY KIND, either express or implied. # See the License for the specific",
"dataset with paraphrases in russian posted on the site [1] is used. The",
"<filename>deeppavlov/tasks/paraphrases/__init__.py # Copyright 2017 Neural Networks and Deep Learning lab, MIPT # #",
"# limitations under the License. \"\"\" Description of the module tasks.paraphraser: The task",
"in compliance with the License. # You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"module To provide train and test data for the agents.paraphraser module. For this",
"Description of the module tasks.paraphraser: The task of the module To provide train",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"part of the data is reserved for the validation. Namely, the data is",
"use this file except in compliance with the License. # You may obtain",
"test parts of the data. Then it shuffles, splits into batches and feeds",
"the k - 1 remaining folds form the training set. [1] http://paraphraser.ru/ \"\"\"",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"for the specific language governing permissions and # limitations under the License. \"\"\"",
"and feeds the to the agents.paraphraser module for training (feeds the whole dataset",
"not use this file except in compliance with the License. # You may",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"a validation while the k - 1 remaining folds form the training set.",
"the data. Then it shuffles, splits into batches and feeds the to the",
"russian posted on the site [1] is used. The module downloads train and",
"k folds, where k equals to the '--bagging-folds-number' parameter. Each fold is then",
"See the License for the specific language governing permissions and # limitations under",
"For this the dataset with paraphrases in russian posted on the site [1]",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"permissions and # limitations under the License. \"\"\" Description of the module tasks.paraphraser:",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"specific language governing permissions and # limitations under the License. \"\"\" Description of",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"and # limitations under the License. \"\"\" Description of the module tasks.paraphraser: The",
"as a validation while the k - 1 remaining folds form the training",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"language governing permissions and # limitations under the License. \"\"\" Description of the",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"governing permissions and # limitations under the License. \"\"\" Description of the module",
"under the License. \"\"\" Description of the module tasks.paraphraser: The task of the",
"once as a validation while the k - 1 remaining folds form the",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"is then used once as a validation while the k - 1 remaining",
"the data is divided into k folds, where k equals to the '--bagging-folds-number'",
"fold is then used once as a validation while the k - 1",
"OF ANY KIND, either express or implied. # See the License for the",
"data is divided into k folds, where k equals to the '--bagging-folds-number' parameter.",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"of the module To provide train and test data for the agents.paraphraser module.",
"# you may not use this file except in compliance with the License.",
"used. The module downloads train and test parts of the data. Then it",
"parts of the data. Then it shuffles, splits into batches and feeds the",
"(feeds the whole dataset for testing). The part of the data is reserved",
"of the module tasks.paraphraser: The task of the module To provide train and",
"agreed to in writing, software # distributed under the License is distributed on",
"The module downloads train and test parts of the data. Then it shuffles,",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"is divided into k folds, where k equals to the '--bagging-folds-number' parameter. Each",
"folds, where k equals to the '--bagging-folds-number' parameter. Each fold is then used",
"Neural Networks and Deep Learning lab, MIPT # # Licensed under the Apache",
"parameter. Each fold is then used once as a validation while the k",
"feeds the to the agents.paraphraser module for training (feeds the whole dataset for",
"(the \"License\"); # you may not use this file except in compliance with",
"the to the agents.paraphraser module for training (feeds the whole dataset for testing).",
"train and test data for the agents.paraphraser module. For this the dataset with",
"module tasks.paraphraser: The task of the module To provide train and test data",
"of the data. Then it shuffles, splits into batches and feeds the to",
"the site [1] is used. The module downloads train and test parts of",
"# # Unless required by applicable law or agreed to in writing, software",
"To provide train and test data for the agents.paraphraser module. For this the",
"Copyright 2017 Neural Networks and Deep Learning lab, MIPT # # Licensed under",
"2017 Neural Networks and Deep Learning lab, MIPT # # Licensed under the",
"for testing). The part of the data is reserved for the validation. Namely,",
"paraphrases in russian posted on the site [1] is used. The module downloads",
"express or implied. # See the License for the specific language governing permissions",
"reserved for the validation. Namely, the data is divided into k folds, where",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"is used. The module downloads train and test parts of the data. Then",
"except in compliance with the License. # You may obtain a copy of",
"by applicable law or agreed to in writing, software # distributed under the",
"shuffles, splits into batches and feeds the to the agents.paraphraser module for training",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"either express or implied. # See the License for the specific language governing",
"module. For this the dataset with paraphrases in russian posted on the site",
"in russian posted on the site [1] is used. The module downloads train",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"into batches and feeds the to the agents.paraphraser module for training (feeds the",
"training (feeds the whole dataset for testing). The part of the data is",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"it shuffles, splits into batches and feeds the to the agents.paraphraser module for",
"and test parts of the data. Then it shuffles, splits into batches and",
"validation. Namely, the data is divided into k folds, where k equals to",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"to the agents.paraphraser module for training (feeds the whole dataset for testing). The",
"Networks and Deep Learning lab, MIPT # # Licensed under the Apache License,",
"file except in compliance with the License. # You may obtain a copy",
"# Copyright 2017 Neural Networks and Deep Learning lab, MIPT # # Licensed",
"the module tasks.paraphraser: The task of the module To provide train and test",
"tasks.paraphraser: The task of the module To provide train and test data for",
"with paraphrases in russian posted on the site [1] is used. The module",
"into k folds, where k equals to the '--bagging-folds-number' parameter. Each fold is",
"License. \"\"\" Description of the module tasks.paraphraser: The task of the module To",
"train and test parts of the data. Then it shuffles, splits into batches",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"License for the specific language governing permissions and # limitations under the License.",
"downloads train and test parts of the data. Then it shuffles, splits into",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"equals to the '--bagging-folds-number' parameter. Each fold is then used once as a",
"provide train and test data for the agents.paraphraser module. For this the dataset",
"the License. # You may obtain a copy of the License at #",
"task of the module To provide train and test data for the agents.paraphraser",
"the dataset with paraphrases in russian posted on the site [1] is used.",
"module for training (feeds the whole dataset for testing). The part of the",
"to in writing, software # distributed under the License is distributed on an",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"implied. # See the License for the specific language governing permissions and #",
"\"License\"); # you may not use this file except in compliance with the",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"k equals to the '--bagging-folds-number' parameter. Each fold is then used once as",
"required by applicable law or agreed to in writing, software # distributed under",
"test data for the agents.paraphraser module. For this the dataset with paraphrases in",
"lab, MIPT # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"is reserved for the validation. Namely, the data is divided into k folds,",
"and test data for the agents.paraphraser module. For this the dataset with paraphrases",
"applicable law or agreed to in writing, software # distributed under the License",
"used once as a validation while the k - 1 remaining folds form",
"The task of the module To provide train and test data for the",
"the module To provide train and test data for the agents.paraphraser module. For",
"Then it shuffles, splits into batches and feeds the to the agents.paraphraser module",
"dataset for testing). The part of the data is reserved for the validation.",
"divided into k folds, where k equals to the '--bagging-folds-number' parameter. Each fold",
"testing). The part of the data is reserved for the validation. Namely, the",
"validation while the k - 1 remaining folds form the training set. [1]",
"or agreed to in writing, software # distributed under the License is distributed",
"or implied. # See the License for the specific language governing permissions and",
"the data is reserved for the validation. Namely, the data is divided into",
"where k equals to the '--bagging-folds-number' parameter. Each fold is then used once",
"on the site [1] is used. The module downloads train and test parts",
"splits into batches and feeds the to the agents.paraphraser module for training (feeds",
"then used once as a validation while the k - 1 remaining folds",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"agents.paraphraser module for training (feeds the whole dataset for testing). The part of",
"data is reserved for the validation. Namely, the data is divided into k",
"with the License. # You may obtain a copy of the License at",
"limitations under the License. \"\"\" Description of the module tasks.paraphraser: The task of",
"the whole dataset for testing). The part of the data is reserved for",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"data. Then it shuffles, splits into batches and feeds the to the agents.paraphraser",
"for training (feeds the whole dataset for testing). The part of the data",
"Each fold is then used once as a validation while the k -",
"whole dataset for testing). The part of the data is reserved for the",
"The part of the data is reserved for the validation. Namely, the data",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"site [1] is used. The module downloads train and test parts of the",
"Learning lab, MIPT # # Licensed under the Apache License, Version 2.0 (the"
] |
[
"simulations. .. currentmodule:: porespy .. autosummary:: :template: mybase.rst :toctree: generated/ dns.tortuosity \"\"\" from",
"direct numerical simulations. .. currentmodule:: porespy .. autosummary:: :template: mybase.rst :toctree: generated/ dns.tortuosity",
"**Direct Numerical Simulation** This module contains routines for performing direct numerical simulations. ..",
"DNS ### **Direct Numerical Simulation** This module contains routines for performing direct numerical",
"for performing direct numerical simulations. .. currentmodule:: porespy .. autosummary:: :template: mybase.rst :toctree:",
"Numerical Simulation** This module contains routines for performing direct numerical simulations. .. currentmodule::",
"currentmodule:: porespy .. autosummary:: :template: mybase.rst :toctree: generated/ dns.tortuosity \"\"\" from ._funcs import",
"contains routines for performing direct numerical simulations. .. currentmodule:: porespy .. autosummary:: :template:",
"r\"\"\" DNS ### **Direct Numerical Simulation** This module contains routines for performing direct",
"performing direct numerical simulations. .. currentmodule:: porespy .. autosummary:: :template: mybase.rst :toctree: generated/",
"numerical simulations. .. currentmodule:: porespy .. autosummary:: :template: mybase.rst :toctree: generated/ dns.tortuosity \"\"\"",
".. currentmodule:: porespy .. autosummary:: :template: mybase.rst :toctree: generated/ dns.tortuosity \"\"\" from ._funcs",
"Simulation** This module contains routines for performing direct numerical simulations. .. currentmodule:: porespy",
"### **Direct Numerical Simulation** This module contains routines for performing direct numerical simulations.",
"module contains routines for performing direct numerical simulations. .. currentmodule:: porespy .. autosummary::",
"routines for performing direct numerical simulations. .. currentmodule:: porespy .. autosummary:: :template: mybase.rst",
"porespy .. autosummary:: :template: mybase.rst :toctree: generated/ dns.tortuosity \"\"\" from ._funcs import *",
"This module contains routines for performing direct numerical simulations. .. currentmodule:: porespy .."
] |
[
"'planning_poker_jira/templates'), ) ASGI_APPLICATION = 'example.routing.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME':",
"os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = True TEMPLATE_DEBUG = DEBUG SECRET_KEY = '<KEY>' TEMPLATE_DIRS = (",
"'encrypted_fields', 'planning_poker_jira', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',",
"'' # URL prefix for static files. # Example: \"http://media.lawrence.com/static/\" STATIC_URL = '/static/'",
"URL prefix for static files. # Example: \"http://media.lawrence.com/static/\" STATIC_URL = '/static/' # Additional",
"locations of static files STATICFILES_DIRS = ( # Put strings here, like \"/home/html/static\"",
"'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors':",
"'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',",
"'', 'PORT': '', } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',",
"files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', )",
"= [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES =",
"apps' \"static/\" subdirectories and in STATICFILES_DIRS. # Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT = '' #",
"your static files # in apps' \"static/\" subdirectories and in STATICFILES_DIRS. # Example:",
"'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }",
"files should be collected to. # Don't put anything in this directory yourself;",
"anything in this directory yourself; store your static files # in apps' \"static/\"",
"project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = True TEMPLATE_DEBUG =",
"os.path.join(BASE_DIR, 'planning_poker_jira/templates'), ) ASGI_APPLICATION = 'example.routing.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3',",
"'django.contrib.admin', 'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields', 'planning_poker_jira', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',",
"[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',",
"be collected to. # Don't put anything in this directory yourself; store your",
"= ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields',",
"this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = True TEMPLATE_DEBUG = DEBUG SECRET_KEY",
"'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, } ] ROOT_URLCONF = 'example.urls' # Absolute",
"= { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db', 'USER': '', 'PASSWORD': '', 'HOST':",
"# Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))",
"STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( #",
"'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True,",
"here, like \"/home/html/static\" or \"C:/www/django/static\". # Always use forward slashes, even on Windows.",
"various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) FIELD_ENCRYPTION_KEYS = [SECRET_KEY.encode().hex()]",
"# Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT = '' # URL prefix for static files. #",
"of static files STATICFILES_DIRS = ( # Put strings here, like \"/home/html/static\" or",
"in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) FIELD_ENCRYPTION_KEYS",
"to use absolute paths, not relative paths. ) # List of finder classes",
"static files # in apps' \"static/\" subdirectories and in STATICFILES_DIRS. # Example: \"/home/media/media.lawrence.com/static/\"",
"project. import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...)",
"'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS':",
"= DEBUG SECRET_KEY = '<KEY>' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'planning_poker_jira/templates'), ) ASGI_APPLICATION =",
"'', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } INSTALLED_APPS = ( 'django.contrib.auth',",
"'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, } ] ROOT_URLCONF = 'example.urls' # Absolute path",
"'django.contrib.messages.context_processors.messages', ], }, } ] ROOT_URLCONF = 'example.urls' # Absolute path to the",
"= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request',",
"True TEMPLATE_DEBUG = DEBUG SECRET_KEY = '<KEY>' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'planning_poker_jira/templates'), )",
"'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields', 'planning_poker_jira', ) MIDDLEWARE = [",
"'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, } ] ROOT_URLCONF = 'example.urls'",
"# Example: \"http://media.lawrence.com/static/\" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS",
"strings here, like \"/home/html/static\" or \"C:/www/django/static\". # Always use forward slashes, even on",
"subdirectories and in STATICFILES_DIRS. # Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT = '' # URL prefix",
"paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG =",
"'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields', 'planning_poker_jira', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware',",
"files STATICFILES_DIRS = ( # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\". #",
"'PORT': '', } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin',",
"in this directory yourself; store your static files # in apps' \"static/\" subdirectories",
"'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields', 'planning_poker_jira', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware',",
"should be collected to. # Don't put anything in this directory yourself; store",
"# in apps' \"static/\" subdirectories and in STATICFILES_DIRS. # Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT =",
"Windows. # Don't forget to use absolute paths, not relative paths. ) #",
"find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', #",
"like \"/home/html/static\" or \"C:/www/django/static\". # Always use forward slashes, even on Windows. #",
"[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, } ] ROOT_URLCONF = 'example.urls' #",
"# Don't put anything in this directory yourself; store your static files #",
"# URL prefix for static files. # Example: \"http://media.lawrence.com/static/\" STATIC_URL = '/static/' #",
"'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND':",
"'<KEY>' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'planning_poker_jira/templates'), ) ASGI_APPLICATION = 'example.routing.application' DATABASES = {",
"[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [",
"ASGI_APPLICATION = 'example.routing.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db', 'USER':",
"] ROOT_URLCONF = 'example.urls' # Absolute path to the directory static files should",
"= ( # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\". # Always use",
"slashes, even on Windows. # Don't forget to use absolute paths, not relative",
") MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]",
"of finder classes that know how to find static files in # various",
"'', 'HOST': '', 'PORT': '', } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',",
"in apps' \"static/\" subdirectories and in STATICFILES_DIRS. # Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT = ''",
"classes that know how to find static files in # various locations. STATICFILES_FINDERS",
"'HOST': '', 'PORT': '', } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',",
"'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields', 'planning_poker_jira', ) MIDDLEWARE",
"<reponame>rheinwerk-verlag/planning-poker-jira<gh_stars>1-10 # Django settings for example project. import os # Build paths inside",
"'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } INSTALLED_APPS = (",
"'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, } ] ROOT_URLCONF = 'example.urls' # Absolute path to",
"yourself; store your static files # in apps' \"static/\" subdirectories and in STATICFILES_DIRS.",
"relative paths. ) # List of finder classes that know how to find",
"'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], },",
"= os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = True TEMPLATE_DEBUG = DEBUG SECRET_KEY = '<KEY>' TEMPLATE_DIRS =",
"'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ],",
"directory yourself; store your static files # in apps' \"static/\" subdirectories and in",
"put anything in this directory yourself; store your static files # in apps'",
"this directory yourself; store your static files # in apps' \"static/\" subdirectories and",
"files. # Example: \"http://media.lawrence.com/static/\" STATIC_URL = '/static/' # Additional locations of static files",
"example project. import os # Build paths inside the project like this: os.path.join(BASE_DIR,",
"INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker',",
"( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields', 'planning_poker_jira',",
"], }, } ] ROOT_URLCONF = 'example.urls' # Absolute path to the directory",
"= '' # URL prefix for static files. # Example: \"http://media.lawrence.com/static/\" STATIC_URL =",
"\"/home/html/static\" or \"C:/www/django/static\". # Always use forward slashes, even on Windows. # Don't",
") # List of finder classes that know how to find static files",
"'NAME': 'planning_poker_jira.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } INSTALLED_APPS",
"'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS':",
"# List of finder classes that know how to find static files in",
"'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields', 'planning_poker_jira', )",
"static files should be collected to. # Don't put anything in this directory",
"ROOT_URLCONF = 'example.urls' # Absolute path to the directory static files should be",
"\"http://media.lawrence.com/static/\" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = (",
"Django settings for example project. import os # Build paths inside the project",
"} } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'channels',",
"{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '',",
"( os.path.join(BASE_DIR, 'planning_poker_jira/templates'), ) ASGI_APPLICATION = 'example.routing.application' DATABASES = { 'default': { 'ENGINE':",
"\"C:/www/django/static\". # Always use forward slashes, even on Windows. # Don't forget to",
"{ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db', 'USER': '', 'PASSWORD': '', 'HOST': '',",
"the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = True TEMPLATE_DEBUG",
"] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [",
"True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, } ]",
"{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, } ] ROOT_URLCONF =",
"forget to use absolute paths, not relative paths. ) # List of finder",
"DEBUG = True TEMPLATE_DEBUG = DEBUG SECRET_KEY = '<KEY>' TEMPLATE_DIRS = ( os.path.join(BASE_DIR,",
"on Windows. # Don't forget to use absolute paths, not relative paths. )",
"use forward slashes, even on Windows. # Don't forget to use absolute paths,",
"# various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) FIELD_ENCRYPTION_KEYS =",
"\"static/\" subdirectories and in STATICFILES_DIRS. # Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT = '' # URL",
"MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES",
"List of finder classes that know how to find static files in #",
"STATICFILES_DIRS. # Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT = '' # URL prefix for static files.",
"'example.urls' # Absolute path to the directory static files should be collected to.",
"know how to find static files in # various locations. STATICFILES_FINDERS = (",
"Don't forget to use absolute paths, not relative paths. ) # List of",
"= '<KEY>' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'planning_poker_jira/templates'), ) ASGI_APPLICATION = 'example.routing.application' DATABASES =",
"# Always use forward slashes, even on Windows. # Don't forget to use",
"'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields', 'planning_poker_jira', ) MIDDLEWARE =",
"}, } ] ROOT_URLCONF = 'example.urls' # Absolute path to the directory static",
"'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT':",
"Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like",
"to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder',",
"'/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings",
"'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, } ] ROOT_URLCONF",
"'planning_poker_jira.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } INSTALLED_APPS =",
"path to the directory static files should be collected to. # Don't put",
"TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'planning_poker_jira/templates'), ) ASGI_APPLICATION = 'example.routing.application' DATABASES = { 'default':",
"= True TEMPLATE_DEBUG = DEBUG SECRET_KEY = '<KEY>' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'planning_poker_jira/templates'),",
"and in STATICFILES_DIRS. # Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT = '' # URL prefix for",
"Always use forward slashes, even on Windows. # Don't forget to use absolute",
"store your static files # in apps' \"static/\" subdirectories and in STATICFILES_DIRS. #",
"even on Windows. # Don't forget to use absolute paths, not relative paths.",
"STATICFILES_DIRS = ( # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\". # Always",
"Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG",
"{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',",
"# Absolute path to the directory static files should be collected to. #",
"'', } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs',",
"TEMPLATE_DEBUG = DEBUG SECRET_KEY = '<KEY>' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'planning_poker_jira/templates'), ) ASGI_APPLICATION",
"'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }",
"...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = True TEMPLATE_DEBUG = DEBUG SECRET_KEY = '<KEY>'",
"import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR",
"not relative paths. ) # List of finder classes that know how to",
"# Django settings for example project. import os # Build paths inside the",
"static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder',",
"STATIC_ROOT = '' # URL prefix for static files. # Example: \"http://media.lawrence.com/static/\" STATIC_URL",
"Put strings here, like \"/home/html/static\" or \"C:/www/django/static\". # Always use forward slashes, even",
"inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = True",
"'planning_poker', 'encrypted_fields', 'planning_poker_jira', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',",
"'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields', 'planning_poker_jira', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware',",
"to the directory static files should be collected to. # Don't put anything",
"# Put strings here, like \"/home/html/static\" or \"C:/www/django/static\". # Always use forward slashes,",
"'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ {",
"# Additional locations of static files STATICFILES_DIRS = ( # Put strings here,",
"= '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put",
"SECRET_KEY = '<KEY>' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'planning_poker_jira/templates'), ) ASGI_APPLICATION = 'example.routing.application' DATABASES",
"os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = True TEMPLATE_DEBUG = DEBUG SECRET_KEY =",
"'PASSWORD': '', 'HOST': '', 'PORT': '', } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes',",
"for static files. # Example: \"http://media.lawrence.com/static/\" STATIC_URL = '/static/' # Additional locations of",
"in STATICFILES_DIRS. # Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT = '' # URL prefix for static",
") ASGI_APPLICATION = 'example.routing.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db',",
"Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT = '' # URL prefix for static files. # Example:",
"absolute paths, not relative paths. ) # List of finder classes that know",
"that know how to find static files in # various locations. STATICFILES_FINDERS =",
"or \"C:/www/django/static\". # Always use forward slashes, even on Windows. # Don't forget",
"= ( os.path.join(BASE_DIR, 'planning_poker_jira/templates'), ) ASGI_APPLICATION = 'example.routing.application' DATABASES = { 'default': {",
"BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = True TEMPLATE_DEBUG = DEBUG SECRET_KEY = '<KEY>' TEMPLATE_DIRS",
"use absolute paths, not relative paths. ) # List of finder classes that",
"finder classes that know how to find static files in # various locations.",
"Absolute path to the directory static files should be collected to. # Don't",
"the directory static files should be collected to. # Don't put anything in",
"os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR =",
"'planning_poker_jira', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',",
"paths. ) # List of finder classes that know how to find static",
"'example.routing.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db', 'USER': '', 'PASSWORD':",
"} INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'channels', 'planning_poker.apps.ChannelsPresenceConfig',",
"static files STATICFILES_DIRS = ( # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".",
"( # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\". # Always use forward",
"prefix for static files. # Example: \"http://media.lawrence.com/static/\" STATIC_URL = '/static/' # Additional locations",
"files # in apps' \"static/\" subdirectories and in STATICFILES_DIRS. # Example: \"/home/media/media.lawrence.com/static/\" STATIC_ROOT",
"to. # Don't put anything in this directory yourself; store your static files",
"# Don't forget to use absolute paths, not relative paths. ) # List",
"static files. # Example: \"http://media.lawrence.com/static/\" STATIC_URL = '/static/' # Additional locations of static",
"'planning_poker.apps.ChannelsPresenceConfig', 'planning_poker', 'encrypted_fields', 'planning_poker_jira', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',",
"= 'example.routing.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db', 'USER': '',",
"Example: \"http://media.lawrence.com/static/\" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS =",
"Don't put anything in this directory yourself; store your static files # in",
"forward slashes, even on Windows. # Don't forget to use absolute paths, not",
"for example project. import os # Build paths inside the project like this:",
"collected to. # Don't put anything in this directory yourself; store your static",
"'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': {",
"how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder',",
"} ] ROOT_URLCONF = 'example.urls' # Absolute path to the directory static files",
"= 'example.urls' # Absolute path to the directory static files should be collected",
"\"/home/media/media.lawrence.com/static/\" STATIC_ROOT = '' # URL prefix for static files. # Example: \"http://media.lawrence.com/static/\"",
"like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = True TEMPLATE_DEBUG = DEBUG",
"'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', }",
"paths, not relative paths. ) # List of finder classes that know how",
"directory static files should be collected to. # Don't put anything in this",
"TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',",
"DEBUG SECRET_KEY = '<KEY>' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'planning_poker_jira/templates'), ) ASGI_APPLICATION = 'example.routing.application'",
"DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'planning_poker_jira.db', 'USER': '', 'PASSWORD': '',",
"settings for example project. import os # Build paths inside the project like"
] |
[
"- 0.5 * (self.xyscale[self.i] - 1) + xy_grid ) * self.strides[self.i] prediction_wh =",
"(batch_size, -1, 4)) prediction_prob = tf.reshape( prediction_prob, (batch_size, -1, self.classes) ) return prediction_xywh,",
"prediction_prob = detection_conf_sigmoid * classes_prob_sigmoid prediction_xywh = tf.reshape(prediction_xywh, (batch_size, -1, 4)) prediction_prob =",
"detection_conf, classes_prob = tf.split( conv_output, (2, 2, 1, self.classes), axis=-1 ) xy_grid =",
"= tf.exp(bbox_wh) * self.anchors[self.i] prediction_xywh = tf.concat([prediction_xy, prediction_wh], axis=-1) prediction_prob = detection_conf_sigmoid *",
"3, 5 + self.classes), ) bbox_xy, bbox_wh, detection_conf, classes_prob = tf.split( conv_output, (2,",
"0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2], ], axis=-1, ) predictions = tf.concat([boxes,",
"tf.split( conv_output, (2, 2, 1, self.classes), axis=-1 ) xy_grid = tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size)",
"-1, tf.shape(class_boxes)[-1]] ) pred_conf = tf.reshape( pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]] ) box_xy, box_wh",
"2), axis=-1) input_size = tf.cast(input_size, dtype=tf.float32) box_yx = box_xy[..., ::-1] box_hw = box_wh[...,",
"mask) pred_conf = tf.boolean_mask(scores, mask) class_boxes = tf.reshape( class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]] )",
"tensorflow as tf from .config import cfg class YoloHead(tf.keras.layers.Layer): def __init__(self, grid_size, classes,",
"+ (box_hw / 2.0)) / input_size boxes = tf.concat( [ box_mins[..., 0:1], box_mins[...,",
"self.i = i def call(self, feature_map): batch_size = tf.shape(feature_map)[0] conv_output = tf.reshape( feature_map,",
"from .config import cfg class YoloHead(tf.keras.layers.Layer): def __init__(self, grid_size, classes, strides, anchors, xyscale,",
"strides, anchors, xyscale, i): super().__init__() self.grid_size = grid_size self.classes = classes self.strides =",
"= grid_size self.classes = classes self.strides = strides self.anchors = anchors self.xyscale =",
"else: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 8, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 0, )(feature_maps[0])",
"1], ) xy_grid = tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid = tf.sigmoid(bbox_xy) detection_conf_sigmoid = tf.sigmoid(detection_conf) classes_prob_sigmoid",
"(batch_size, -1, self.classes) ) return prediction_xywh, prediction_prob class FilterLayer(tf.keras.layers.Layer): def __init__(self, input_size, score_threshold=0.4):",
"tf.reshape( class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]] ) pred_conf = tf.reshape( pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]]",
"def dense_prediction(feature_maps, classes, tiny=False): bbox_tensors = [] prob_tensors = [] if tiny: yolo_head_1",
"super().__init__() self.grid_size = grid_size self.classes = classes self.strides = strides self.anchors = anchors",
"prob_tensors.append(yolo_head_2[1]) else: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 8, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 0,",
"tf.concat([prediction_xy, prediction_wh], axis=-1) prediction_prob = detection_conf_sigmoid * classes_prob_sigmoid prediction_xywh = tf.reshape(prediction_xywh, (batch_size, -1,",
"[ box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2], ], axis=-1, ) predictions",
"i def call(self, feature_map): batch_size = tf.shape(feature_map)[0] conv_output = tf.reshape( feature_map, (batch_size, self.grid_size,",
"prediction_prob = tf.reshape( prediction_prob, (batch_size, -1, self.classes) ) return prediction_xywh, prediction_prob class FilterLayer(tf.keras.layers.Layer):",
") pred_conf = tf.reshape( pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]] ) box_xy, box_wh = tf.split(class_boxes,",
"= anchors self.xyscale = xyscale self.i = i def call(self, feature_map): batch_size =",
"pred_conf = tf.reshape( pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]] ) box_xy, box_wh = tf.split(class_boxes, (2,",
"/ input_size box_maxes = (box_yx + (box_hw / 2.0)) / input_size boxes =",
"bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1,",
"tiny=False): bbox_tensors = [] prob_tensors = [] if tiny: yolo_head_1 = YoloHead( cfg.INPUT_SIZE",
"(batch_size, self.grid_size, self.grid_size, 3, 5 + self.classes), ) bbox_xy, bbox_wh, detection_conf, classes_prob =",
"prob_tensors = [] if tiny: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES_TINY,",
"prediction_xywh = tf.reshape(prediction_xywh, (batch_size, -1, 4)) prediction_prob = tf.reshape( prediction_prob, (batch_size, -1, self.classes)",
"box_maxes[..., 1:2], ], axis=-1, ) predictions = tf.concat([boxes, pred_conf], axis=-1) return predictions def",
"= strides self.anchors = anchors self.xyscale = xyscale self.i = i def call(self,",
"bounding_boxes = tf.concat(bounding_boxes, axis=1) scores = tf.concat(scores, axis=1) scores_max = tf.math.reduce_max(scores, axis=-1) mask",
"grid_size self.classes = classes self.strides = strides self.anchors = anchors self.xyscale = xyscale",
"class FilterLayer(tf.keras.layers.Layer): def __init__(self, input_size, score_threshold=0.4): super().__init__() self.input_size = input_size self.score_threshold = score_threshold",
"xy_grid = tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid = tf.sigmoid(bbox_xy) detection_conf_sigmoid = tf.sigmoid(detection_conf) classes_prob_sigmoid = tf.sigmoid(classes_prob)",
") return prediction_xywh, prediction_prob class FilterLayer(tf.keras.layers.Layer): def __init__(self, input_size, score_threshold=0.4): super().__init__() self.input_size =",
"= tf.concat(scores, axis=1) scores_max = tf.math.reduce_max(scores, axis=-1) mask = scores_max >= score_threshold class_boxes",
"xy_grid = tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size) ) xy_grid = tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2) xy_grid =",
"tf.reshape(prediction_xywh, (batch_size, -1, 4)) prediction_prob = tf.reshape( prediction_prob, (batch_size, -1, self.classes) ) return",
"tf.concat(scores, axis=1) scores_max = tf.math.reduce_max(scores, axis=-1) mask = scores_max >= score_threshold class_boxes =",
"* self.anchors[self.i] prediction_xywh = tf.concat([prediction_xy, prediction_wh], axis=-1) prediction_prob = detection_conf_sigmoid * classes_prob_sigmoid prediction_xywh",
"1:2], box_maxes[..., 0:1], box_maxes[..., 1:2], ], axis=-1, ) predictions = tf.concat([boxes, pred_conf], axis=-1)",
"scores_max = tf.math.reduce_max(scores, axis=-1) mask = scores_max >= score_threshold class_boxes = tf.boolean_mask(bounding_boxes, mask)",
"= tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid = tf.sigmoid(bbox_xy) detection_conf_sigmoid = tf.sigmoid(detection_conf) classes_prob_sigmoid = tf.sigmoid(classes_prob) prediction_xy",
"xyscale, i): super().__init__() self.grid_size = grid_size self.classes = classes self.strides = strides self.anchors",
"= tf.math.reduce_max(scores, axis=-1) mask = scores_max >= score_threshold class_boxes = tf.boolean_mask(bounding_boxes, mask) pred_conf",
"def __init__(self, input_size, score_threshold=0.4): super().__init__() self.input_size = input_size self.score_threshold = score_threshold def call(self,",
")(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY,",
"* self.strides[self.i] prediction_wh = tf.exp(bbox_wh) * self.anchors[self.i] prediction_xywh = tf.concat([prediction_xy, prediction_wh], axis=-1) prediction_prob",
"0.5 * (self.xyscale[self.i] - 1) + xy_grid ) * self.strides[self.i] prediction_wh = tf.exp(bbox_wh)",
"= [] if tiny: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY,",
"bbox_xy_sigmoid = tf.sigmoid(bbox_xy) detection_conf_sigmoid = tf.sigmoid(detection_conf) classes_prob_sigmoid = tf.sigmoid(classes_prob) prediction_xy = ( (bbox_xy_sigmoid",
"-1, self.classes) ) return prediction_xywh, prediction_prob class FilterLayer(tf.keras.layers.Layer): def __init__(self, input_size, score_threshold=0.4): super().__init__()",
"prediction_xy = ( (bbox_xy_sigmoid * self.xyscale[self.i]) - 0.5 * (self.xyscale[self.i] - 1) +",
"// 32, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else: yolo_head_1 =",
"= tf.reshape( pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]] ) box_xy, box_wh = tf.split(class_boxes, (2, 2),",
"classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE //",
"cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3 = YoloHead( cfg.INPUT_SIZE // 32,",
"scores): input_size = self.input_size score_threshold = self.score_threshold bounding_boxes = tf.concat(bounding_boxes, axis=1) scores =",
"tf.reshape( pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]] ) box_xy, box_wh = tf.split(class_boxes, (2, 2), axis=-1)",
"input_size = self.input_size score_threshold = self.score_threshold bounding_boxes = tf.concat(bounding_boxes, axis=1) scores = tf.concat(scores,",
"predictions = tf.concat([boxes, pred_conf], axis=-1) return predictions def dense_prediction(feature_maps, classes, tiny=False): bbox_tensors =",
"YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2",
"- (box_hw / 2.0)) / input_size box_maxes = (box_yx + (box_hw / 2.0))",
"input_size self.score_threshold = score_threshold def call(self, bounding_boxes, scores): input_size = self.input_size score_threshold =",
"classes_prob = tf.split( conv_output, (2, 2, 1, self.classes), axis=-1 ) xy_grid = tf.meshgrid(",
"cfg.INPUT_SIZE // 16, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 =",
"= YoloHead( cfg.INPUT_SIZE // 8, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1])",
"( (bbox_xy_sigmoid * self.xyscale[self.i]) - 0.5 * (self.xyscale[self.i] - 1) + xy_grid )",
"strides self.anchors = anchors self.xyscale = xyscale self.i = i def call(self, feature_map):",
"box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2], ], axis=-1, ) predictions = tf.concat([boxes, pred_conf],",
"* classes_prob_sigmoid prediction_xywh = tf.reshape(prediction_xywh, (batch_size, -1, 4)) prediction_prob = tf.reshape( prediction_prob, (batch_size,",
"-1, 4)) prediction_prob = tf.reshape( prediction_prob, (batch_size, -1, self.classes) ) return prediction_xywh, prediction_prob",
"= classes self.strides = strides self.anchors = anchors self.xyscale = xyscale self.i =",
"1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 8, classes, cfg.STRIDES,",
"axis=-1, ) predictions = tf.concat([boxes, pred_conf], axis=-1) return predictions def dense_prediction(feature_maps, classes, tiny=False):",
"= tf.concat([boxes, pred_conf], axis=-1) return predictions def dense_prediction(feature_maps, classes, tiny=False): bbox_tensors = []",
"input_size boxes = tf.concat( [ box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2],",
")(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE,",
"cfg class YoloHead(tf.keras.layers.Layer): def __init__(self, grid_size, classes, strides, anchors, xyscale, i): super().__init__() self.grid_size",
"self.classes), axis=-1 ) xy_grid = tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size) ) xy_grid = tf.expand_dims(tf.stack(xy_grid, axis=-1),",
"yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0])",
"cfg.ANCHORS, cfg.XYSCALE, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 16, classes,",
"prediction_wh], axis=-1) prediction_prob = detection_conf_sigmoid * classes_prob_sigmoid prediction_xywh = tf.reshape(prediction_xywh, (batch_size, -1, 4))",
"if tiny: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0,",
"self.strides[self.i] prediction_wh = tf.exp(bbox_wh) * self.anchors[self.i] prediction_xywh = tf.concat([prediction_xy, prediction_wh], axis=-1) prediction_prob =",
"= ( (bbox_xy_sigmoid * self.xyscale[self.i]) - 0.5 * (self.xyscale[self.i] - 1) + xy_grid",
"[] if tiny: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY,",
"tf.sigmoid(bbox_xy) detection_conf_sigmoid = tf.sigmoid(detection_conf) classes_prob_sigmoid = tf.sigmoid(classes_prob) prediction_xy = ( (bbox_xy_sigmoid * self.xyscale[self.i])",
"= [] prob_tensors = [] if tiny: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 16,",
"/ 2.0)) / input_size boxes = tf.concat( [ box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[...,",
"(bbox_xy_sigmoid * self.xyscale[self.i]) - 0.5 * (self.xyscale[self.i] - 1) + xy_grid ) *",
"axis=1) scores_max = tf.math.reduce_max(scores, axis=-1) mask = scores_max >= score_threshold class_boxes = tf.boolean_mask(bounding_boxes,",
"mask = scores_max >= score_threshold class_boxes = tf.boolean_mask(bounding_boxes, mask) pred_conf = tf.boolean_mask(scores, mask)",
"yolo_head_3 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0])",
"tf.shape(class_boxes)[-1]] ) pred_conf = tf.reshape( pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]] ) box_xy, box_wh =",
"box_xy, box_wh = tf.split(class_boxes, (2, 2), axis=-1) input_size = tf.cast(input_size, dtype=tf.float32) box_yx =",
"= tf.reshape(prediction_xywh, (batch_size, -1, 4)) prediction_prob = tf.reshape( prediction_prob, (batch_size, -1, self.classes) )",
"tf.exp(bbox_wh) * self.anchors[self.i] prediction_xywh = tf.concat([prediction_xy, prediction_wh], axis=-1) prediction_prob = detection_conf_sigmoid * classes_prob_sigmoid",
"score_threshold def call(self, bounding_boxes, scores): input_size = self.input_size score_threshold = self.score_threshold bounding_boxes =",
"YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else:",
"tf.shape(feature_map)[0] conv_output = tf.reshape( feature_map, (batch_size, self.grid_size, self.grid_size, 3, 5 + self.classes), )",
"cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 32,",
"tf.concat( [ box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2], ], axis=-1, )",
"2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1]) predictions = FilterLayer( input_size=tf.constant([cfg.INPUT_SIZE, cfg.INPUT_SIZE]), score_threshold=0.2 )(bbox_tensors, prob_tensors) return",
".config import cfg class YoloHead(tf.keras.layers.Layer): def __init__(self, grid_size, classes, strides, anchors, xyscale, i):",
"= tf.concat(bounding_boxes, axis=1) scores = tf.concat(scores, axis=1) scores_max = tf.math.reduce_max(scores, axis=-1) mask =",
"(2, 2, 1, self.classes), axis=-1 ) xy_grid = tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size) ) xy_grid",
"classes_prob_sigmoid prediction_xywh = tf.reshape(prediction_xywh, (batch_size, -1, 4)) prediction_prob = tf.reshape( prediction_prob, (batch_size, -1,",
"tf.boolean_mask(scores, mask) class_boxes = tf.reshape( class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]] ) pred_conf = tf.reshape(",
"= tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2) xy_grid = tf.tile( tf.expand_dims(xy_grid, axis=0), [batch_size, 1, 1, 3,",
"16, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE",
") predictions = tf.concat([boxes, pred_conf], axis=-1) return predictions def dense_prediction(feature_maps, classes, tiny=False): bbox_tensors",
"call(self, feature_map): batch_size = tf.shape(feature_map)[0] conv_output = tf.reshape( feature_map, (batch_size, self.grid_size, self.grid_size, 3,",
"// 16, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead(",
"self.score_threshold = score_threshold def call(self, bounding_boxes, scores): input_size = self.input_size score_threshold = self.score_threshold",
"class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]] ) pred_conf = tf.reshape( pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]] )",
"(box_hw / 2.0)) / input_size boxes = tf.concat( [ box_mins[..., 0:1], box_mins[..., 1:2],",
"tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size) ) xy_grid = tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2) xy_grid = tf.tile( tf.expand_dims(xy_grid,",
"prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 1, )(feature_maps[1])",
"tf.cast(input_size, dtype=tf.float32) box_yx = box_xy[..., ::-1] box_hw = box_wh[..., ::-1] box_mins = (box_yx",
"i): super().__init__() self.grid_size = grid_size self.classes = classes self.strides = strides self.anchors =",
"box_maxes[..., 0:1], box_maxes[..., 1:2], ], axis=-1, ) predictions = tf.concat([boxes, pred_conf], axis=-1) return",
"axis=-1) return predictions def dense_prediction(feature_maps, classes, tiny=False): bbox_tensors = [] prob_tensors = []",
"FilterLayer(tf.keras.layers.Layer): def __init__(self, input_size, score_threshold=0.4): super().__init__() self.input_size = input_size self.score_threshold = score_threshold def",
"box_wh[..., ::-1] box_mins = (box_yx - (box_hw / 2.0)) / input_size box_maxes =",
"class_boxes = tf.boolean_mask(bounding_boxes, mask) pred_conf = tf.boolean_mask(scores, mask) class_boxes = tf.reshape( class_boxes, [tf.shape(scores)[0],",
"// 8, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead(",
"classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1]) predictions = FilterLayer( input_size=tf.constant([cfg.INPUT_SIZE, cfg.INPUT_SIZE]),",
"= tf.cast(input_size, dtype=tf.float32) box_yx = box_xy[..., ::-1] box_hw = box_wh[..., ::-1] box_mins =",
"call(self, bounding_boxes, scores): input_size = self.input_size score_threshold = self.score_threshold bounding_boxes = tf.concat(bounding_boxes, axis=1)",
"cfg.ANCHORS, cfg.XYSCALE, 2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1]) predictions = FilterLayer( input_size=tf.constant([cfg.INPUT_SIZE, cfg.INPUT_SIZE]), score_threshold=0.2 )(bbox_tensors,",
"class YoloHead(tf.keras.layers.Layer): def __init__(self, grid_size, classes, strides, anchors, xyscale, i): super().__init__() self.grid_size =",
">= score_threshold class_boxes = tf.boolean_mask(bounding_boxes, mask) pred_conf = tf.boolean_mask(scores, mask) class_boxes = tf.reshape(",
"tf.expand_dims(xy_grid, axis=0), [batch_size, 1, 1, 3, 1], ) xy_grid = tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid",
"tf.split(class_boxes, (2, 2), axis=-1) input_size = tf.cast(input_size, dtype=tf.float32) box_yx = box_xy[..., ::-1] box_hw",
"prediction_prob class FilterLayer(tf.keras.layers.Layer): def __init__(self, input_size, score_threshold=0.4): super().__init__() self.input_size = input_size self.score_threshold =",
"= input_size self.score_threshold = score_threshold def call(self, bounding_boxes, scores): input_size = self.input_size score_threshold",
"bbox_tensors = [] prob_tensors = [] if tiny: yolo_head_1 = YoloHead( cfg.INPUT_SIZE //",
"= YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1])",
"8, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE",
"axis=1) scores = tf.concat(scores, axis=1) scores_max = tf.math.reduce_max(scores, axis=-1) mask = scores_max >=",
"self.grid_size, self.grid_size, 3, 5 + self.classes), ) bbox_xy, bbox_wh, detection_conf, classes_prob = tf.split(",
"self.grid_size = grid_size self.classes = classes self.strides = strides self.anchors = anchors self.xyscale",
")(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1]) predictions = FilterLayer( input_size=tf.constant([cfg.INPUT_SIZE, cfg.INPUT_SIZE]), score_threshold=0.2 )(bbox_tensors, prob_tensors) return predictions",
"batch_size = tf.shape(feature_map)[0] conv_output = tf.reshape( feature_map, (batch_size, self.grid_size, self.grid_size, 3, 5 +",
"cfg.XYSCALE, 2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1]) predictions = FilterLayer( input_size=tf.constant([cfg.INPUT_SIZE, cfg.INPUT_SIZE]), score_threshold=0.2 )(bbox_tensors, prob_tensors)",
"0:1], box_maxes[..., 1:2], ], axis=-1, ) predictions = tf.concat([boxes, pred_conf], axis=-1) return predictions",
"classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE //",
"1, 3, 1], ) xy_grid = tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid = tf.sigmoid(bbox_xy) detection_conf_sigmoid =",
"= box_wh[..., ::-1] box_mins = (box_yx - (box_hw / 2.0)) / input_size box_maxes",
") xy_grid = tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid = tf.sigmoid(bbox_xy) detection_conf_sigmoid = tf.sigmoid(detection_conf) classes_prob_sigmoid =",
"1) + xy_grid ) * self.strides[self.i] prediction_wh = tf.exp(bbox_wh) * self.anchors[self.i] prediction_xywh =",
"[batch_size, 1, 1, 3, 1], ) xy_grid = tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid = tf.sigmoid(bbox_xy)",
"def __init__(self, grid_size, classes, strides, anchors, xyscale, i): super().__init__() self.grid_size = grid_size self.classes",
"= i def call(self, feature_map): batch_size = tf.shape(feature_map)[0] conv_output = tf.reshape( feature_map, (batch_size,",
"- 1) + xy_grid ) * self.strides[self.i] prediction_wh = tf.exp(bbox_wh) * self.anchors[self.i] prediction_xywh",
"grid_size, classes, strides, anchors, xyscale, i): super().__init__() self.grid_size = grid_size self.classes = classes",
"self.anchors[self.i] prediction_xywh = tf.concat([prediction_xy, prediction_wh], axis=-1) prediction_prob = detection_conf_sigmoid * classes_prob_sigmoid prediction_xywh =",
"score_threshold = self.score_threshold bounding_boxes = tf.concat(bounding_boxes, axis=1) scores = tf.concat(scores, axis=1) scores_max =",
"box_wh = tf.split(class_boxes, (2, 2), axis=-1) input_size = tf.cast(input_size, dtype=tf.float32) box_yx = box_xy[...,",
"= tf.boolean_mask(scores, mask) class_boxes = tf.reshape( class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]] ) pred_conf =",
"tf.range(self.grid_size) ) xy_grid = tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2) xy_grid = tf.tile( tf.expand_dims(xy_grid, axis=0), [batch_size,",
"box_maxes = (box_yx + (box_hw / 2.0)) / input_size boxes = tf.concat( [",
"__init__(self, grid_size, classes, strides, anchors, xyscale, i): super().__init__() self.grid_size = grid_size self.classes =",
"mask) class_boxes = tf.reshape( class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]] ) pred_conf = tf.reshape( pred_conf,",
"import tensorflow as tf from .config import cfg class YoloHead(tf.keras.layers.Layer): def __init__(self, grid_size,",
"self.xyscale[self.i]) - 0.5 * (self.xyscale[self.i] - 1) + xy_grid ) * self.strides[self.i] prediction_wh",
"score_threshold class_boxes = tf.boolean_mask(bounding_boxes, mask) pred_conf = tf.boolean_mask(scores, mask) class_boxes = tf.reshape( class_boxes,",
") * self.strides[self.i] prediction_wh = tf.exp(bbox_wh) * self.anchors[self.i] prediction_xywh = tf.concat([prediction_xy, prediction_wh], axis=-1)",
"def call(self, feature_map): batch_size = tf.shape(feature_map)[0] conv_output = tf.reshape( feature_map, (batch_size, self.grid_size, self.grid_size,",
"xy_grid = tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2) xy_grid = tf.tile( tf.expand_dims(xy_grid, axis=0), [batch_size, 1, 1,",
")(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 8, classes, cfg.STRIDES, cfg.ANCHORS,",
"prediction_prob, (batch_size, -1, self.classes) ) return prediction_xywh, prediction_prob class FilterLayer(tf.keras.layers.Layer): def __init__(self, input_size,",
"* self.xyscale[self.i]) - 0.5 * (self.xyscale[self.i] - 1) + xy_grid ) * self.strides[self.i]",
"2.0)) / input_size boxes = tf.concat( [ box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1],",
"self.classes = classes self.strides = strides self.anchors = anchors self.xyscale = xyscale self.i",
"cfg.XYSCALE_TINY, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES_TINY,",
"cfg.XYSCALE_TINY, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 8, classes,",
"box_hw = box_wh[..., ::-1] box_mins = (box_yx - (box_hw / 2.0)) / input_size",
"axis=2) xy_grid = tf.tile( tf.expand_dims(xy_grid, axis=0), [batch_size, 1, 1, 3, 1], ) xy_grid",
"16, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3 = YoloHead( cfg.INPUT_SIZE",
"feature_map, (batch_size, self.grid_size, self.grid_size, 3, 5 + self.classes), ) bbox_xy, bbox_wh, detection_conf, classes_prob",
"= score_threshold def call(self, bounding_boxes, scores): input_size = self.input_size score_threshold = self.score_threshold bounding_boxes",
"[tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]] ) pred_conf = tf.reshape( pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]] ) box_xy,",
"tf from .config import cfg class YoloHead(tf.keras.layers.Layer): def __init__(self, grid_size, classes, strides, anchors,",
"return prediction_xywh, prediction_prob class FilterLayer(tf.keras.layers.Layer): def __init__(self, input_size, score_threshold=0.4): super().__init__() self.input_size = input_size",
"YoloHead( cfg.INPUT_SIZE // 8, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2",
"self.classes), ) bbox_xy, bbox_wh, detection_conf, classes_prob = tf.split( conv_output, (2, 2, 1, self.classes),",
"classes_prob_sigmoid = tf.sigmoid(classes_prob) prediction_xy = ( (bbox_xy_sigmoid * self.xyscale[self.i]) - 0.5 * (self.xyscale[self.i]",
"], axis=-1, ) predictions = tf.concat([boxes, pred_conf], axis=-1) return predictions def dense_prediction(feature_maps, classes,",
"tf.sigmoid(detection_conf) classes_prob_sigmoid = tf.sigmoid(classes_prob) prediction_xy = ( (bbox_xy_sigmoid * self.xyscale[self.i]) - 0.5 *",
"bbox_wh, detection_conf, classes_prob = tf.split( conv_output, (2, 2, 1, self.classes), axis=-1 ) xy_grid",
"detection_conf_sigmoid * classes_prob_sigmoid prediction_xywh = tf.reshape(prediction_xywh, (batch_size, -1, 4)) prediction_prob = tf.reshape( prediction_prob,",
"cfg.INPUT_SIZE // 32, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else: yolo_head_1",
"cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 32, classes,",
"axis=-1), axis=2) xy_grid = tf.tile( tf.expand_dims(xy_grid, axis=0), [batch_size, 1, 1, 3, 1], )",
"= tf.sigmoid(classes_prob) prediction_xy = ( (bbox_xy_sigmoid * self.xyscale[self.i]) - 0.5 * (self.xyscale[self.i] -",
"tf.boolean_mask(bounding_boxes, mask) pred_conf = tf.boolean_mask(scores, mask) class_boxes = tf.reshape( class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]]",
"import cfg class YoloHead(tf.keras.layers.Layer): def __init__(self, grid_size, classes, strides, anchors, xyscale, i): super().__init__()",
"= YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1])",
"cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 16,",
"(self.xyscale[self.i] - 1) + xy_grid ) * self.strides[self.i] prediction_wh = tf.exp(bbox_wh) * self.anchors[self.i]",
"classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3 = YoloHead( cfg.INPUT_SIZE //",
"pred_conf = tf.boolean_mask(scores, mask) class_boxes = tf.reshape( class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]] ) pred_conf",
"pred_conf], axis=-1) return predictions def dense_prediction(feature_maps, classes, tiny=False): bbox_tensors = [] prob_tensors =",
") xy_grid = tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size) ) xy_grid = tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2) xy_grid",
"classes, tiny=False): bbox_tensors = [] prob_tensors = [] if tiny: yolo_head_1 = YoloHead(",
"+ xy_grid ) * self.strides[self.i] prediction_wh = tf.exp(bbox_wh) * self.anchors[self.i] prediction_xywh = tf.concat([prediction_xy,",
"__init__(self, input_size, score_threshold=0.4): super().__init__() self.input_size = input_size self.score_threshold = score_threshold def call(self, bounding_boxes,",
"32, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else: yolo_head_1 = YoloHead(",
"cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1]) predictions = FilterLayer( input_size=tf.constant([cfg.INPUT_SIZE, cfg.INPUT_SIZE]), score_threshold=0.2",
"box_yx = box_xy[..., ::-1] box_hw = box_wh[..., ::-1] box_mins = (box_yx - (box_hw",
"= tf.concat( [ box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2], ], axis=-1,",
"yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0])",
"= tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size) ) xy_grid = tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2) xy_grid = tf.tile(",
"pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]] ) box_xy, box_wh = tf.split(class_boxes, (2, 2), axis=-1) input_size",
"detection_conf_sigmoid = tf.sigmoid(detection_conf) classes_prob_sigmoid = tf.sigmoid(classes_prob) prediction_xy = ( (bbox_xy_sigmoid * self.xyscale[self.i]) -",
"2, 1, self.classes), axis=-1 ) xy_grid = tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size) ) xy_grid =",
"= self.score_threshold bounding_boxes = tf.concat(bounding_boxes, axis=1) scores = tf.concat(scores, axis=1) scores_max = tf.math.reduce_max(scores,",
"= box_xy[..., ::-1] box_hw = box_wh[..., ::-1] box_mins = (box_yx - (box_hw /",
"1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES, cfg.ANCHORS,",
"classes self.strides = strides self.anchors = anchors self.xyscale = xyscale self.i = i",
"prediction_wh = tf.exp(bbox_wh) * self.anchors[self.i] prediction_xywh = tf.concat([prediction_xy, prediction_wh], axis=-1) prediction_prob = detection_conf_sigmoid",
"axis=-1) prediction_prob = detection_conf_sigmoid * classes_prob_sigmoid prediction_xywh = tf.reshape(prediction_xywh, (batch_size, -1, 4)) prediction_prob",
"= tf.reshape( feature_map, (batch_size, self.grid_size, self.grid_size, 3, 5 + self.classes), ) bbox_xy, bbox_wh,",
"yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 8, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0])",
"0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES, cfg.ANCHORS,",
"as tf from .config import cfg class YoloHead(tf.keras.layers.Layer): def __init__(self, grid_size, classes, strides,",
"= tf.boolean_mask(bounding_boxes, mask) pred_conf = tf.boolean_mask(scores, mask) class_boxes = tf.reshape( class_boxes, [tf.shape(scores)[0], -1,",
"= YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1])",
"input_size box_maxes = (box_yx + (box_hw / 2.0)) / input_size boxes = tf.concat(",
"= tf.split( conv_output, (2, 2, 1, self.classes), axis=-1 ) xy_grid = tf.meshgrid( tf.range(self.grid_size),",
"-1, tf.shape(pred_conf)[-1]] ) box_xy, box_wh = tf.split(class_boxes, (2, 2), axis=-1) input_size = tf.cast(input_size,",
"[tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]] ) box_xy, box_wh = tf.split(class_boxes, (2, 2), axis=-1) input_size =",
"cfg.INPUT_SIZE // 16, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3 =",
"score_threshold=0.4): super().__init__() self.input_size = input_size self.score_threshold = score_threshold def call(self, bounding_boxes, scores): input_size",
"cfg.INPUT_SIZE // 8, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 =",
"= xyscale self.i = i def call(self, feature_map): batch_size = tf.shape(feature_map)[0] conv_output =",
"dense_prediction(feature_maps, classes, tiny=False): bbox_tensors = [] prob_tensors = [] if tiny: yolo_head_1 =",
"self.xyscale = xyscale self.i = i def call(self, feature_map): batch_size = tf.shape(feature_map)[0] conv_output",
"prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1, )(feature_maps[1])",
"super().__init__() self.input_size = input_size self.score_threshold = score_threshold def call(self, bounding_boxes, scores): input_size =",
"tf.concat(bounding_boxes, axis=1) scores = tf.concat(scores, axis=1) scores_max = tf.math.reduce_max(scores, axis=-1) mask = scores_max",
"bounding_boxes, scores): input_size = self.input_size score_threshold = self.score_threshold bounding_boxes = tf.concat(bounding_boxes, axis=1) scores",
"tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2) xy_grid = tf.tile( tf.expand_dims(xy_grid, axis=0), [batch_size, 1, 1, 3, 1],",
"= tf.reshape( prediction_prob, (batch_size, -1, self.classes) ) return prediction_xywh, prediction_prob class FilterLayer(tf.keras.layers.Layer): def",
"YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3",
"classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else: yolo_head_1 = YoloHead( cfg.INPUT_SIZE",
"def call(self, bounding_boxes, scores): input_size = self.input_size score_threshold = self.score_threshold bounding_boxes = tf.concat(bounding_boxes,",
"prob_tensors.append(yolo_head_2[1]) yolo_head_3 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 2, )(feature_maps[2])",
"scores = tf.concat(scores, axis=1) scores_max = tf.math.reduce_max(scores, axis=-1) mask = scores_max >= score_threshold",
"tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid = tf.sigmoid(bbox_xy) detection_conf_sigmoid = tf.sigmoid(detection_conf) classes_prob_sigmoid = tf.sigmoid(classes_prob) prediction_xy =",
"[] prob_tensors = [] if tiny: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 16, classes,",
"32, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1]) predictions = FilterLayer( input_size=tf.constant([cfg.INPUT_SIZE,",
"prediction_xywh, prediction_prob class FilterLayer(tf.keras.layers.Layer): def __init__(self, input_size, score_threshold=0.4): super().__init__() self.input_size = input_size self.score_threshold",
"// 32, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1]) predictions = FilterLayer(",
"/ input_size boxes = tf.concat( [ box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[...,",
"= tf.sigmoid(detection_conf) classes_prob_sigmoid = tf.sigmoid(classes_prob) prediction_xy = ( (bbox_xy_sigmoid * self.xyscale[self.i]) - 0.5",
"self.strides = strides self.anchors = anchors self.xyscale = xyscale self.i = i def",
"2.0)) / input_size box_maxes = (box_yx + (box_hw / 2.0)) / input_size boxes",
"scores_max >= score_threshold class_boxes = tf.boolean_mask(bounding_boxes, mask) pred_conf = tf.boolean_mask(scores, mask) class_boxes =",
"4)) prediction_prob = tf.reshape( prediction_prob, (batch_size, -1, self.classes) ) return prediction_xywh, prediction_prob class",
"tf.math.reduce_max(scores, axis=-1) mask = scores_max >= score_threshold class_boxes = tf.boolean_mask(bounding_boxes, mask) pred_conf =",
"1, 1, 3, 1], ) xy_grid = tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid = tf.sigmoid(bbox_xy) detection_conf_sigmoid",
"bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 2,",
"tf.range(self.grid_size), tf.range(self.grid_size) ) xy_grid = tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2) xy_grid = tf.tile( tf.expand_dims(xy_grid, axis=0),",
") box_xy, box_wh = tf.split(class_boxes, (2, 2), axis=-1) input_size = tf.cast(input_size, dtype=tf.float32) box_yx",
"= tf.concat([prediction_xy, prediction_wh], axis=-1) prediction_prob = detection_conf_sigmoid * classes_prob_sigmoid prediction_xywh = tf.reshape(prediction_xywh, (batch_size,",
"conv_output, (2, 2, 1, self.classes), axis=-1 ) xy_grid = tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size) )",
"class_boxes = tf.reshape( class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]] ) pred_conf = tf.reshape( pred_conf, [tf.shape(scores)[0],",
"YoloHead(tf.keras.layers.Layer): def __init__(self, grid_size, classes, strides, anchors, xyscale, i): super().__init__() self.grid_size = grid_size",
"self.grid_size, 3, 5 + self.classes), ) bbox_xy, bbox_wh, detection_conf, classes_prob = tf.split( conv_output,",
"tf.tile( tf.expand_dims(xy_grid, axis=0), [batch_size, 1, 1, 3, 1], ) xy_grid = tf.cast(xy_grid, tf.float32)",
"(box_yx + (box_hw / 2.0)) / input_size boxes = tf.concat( [ box_mins[..., 0:1],",
"* (self.xyscale[self.i] - 1) + xy_grid ) * self.strides[self.i] prediction_wh = tf.exp(bbox_wh) *",
"self.score_threshold bounding_boxes = tf.concat(bounding_boxes, axis=1) scores = tf.concat(scores, axis=1) scores_max = tf.math.reduce_max(scores, axis=-1)",
"tf.reshape( feature_map, (batch_size, self.grid_size, self.grid_size, 3, 5 + self.classes), ) bbox_xy, bbox_wh, detection_conf,",
"boxes = tf.concat( [ box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2], ],",
"= detection_conf_sigmoid * classes_prob_sigmoid prediction_xywh = tf.reshape(prediction_xywh, (batch_size, -1, 4)) prediction_prob = tf.reshape(",
"axis=-1 ) xy_grid = tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size) ) xy_grid = tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2)",
"tf.reshape( prediction_prob, (batch_size, -1, self.classes) ) return prediction_xywh, prediction_prob class FilterLayer(tf.keras.layers.Layer): def __init__(self,",
"anchors, xyscale, i): super().__init__() self.grid_size = grid_size self.classes = classes self.strides = strides",
"(2, 2), axis=-1) input_size = tf.cast(input_size, dtype=tf.float32) box_yx = box_xy[..., ::-1] box_hw =",
"(box_yx - (box_hw / 2.0)) / input_size box_maxes = (box_yx + (box_hw /",
"3, 1], ) xy_grid = tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid = tf.sigmoid(bbox_xy) detection_conf_sigmoid = tf.sigmoid(detection_conf)",
"dtype=tf.float32) box_yx = box_xy[..., ::-1] box_hw = box_wh[..., ::-1] box_mins = (box_yx -",
"cfg.INPUT_SIZE // 32, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1]) predictions =",
"= tf.split(class_boxes, (2, 2), axis=-1) input_size = tf.cast(input_size, dtype=tf.float32) box_yx = box_xy[..., ::-1]",
") xy_grid = tf.expand_dims(tf.stack(xy_grid, axis=-1), axis=2) xy_grid = tf.tile( tf.expand_dims(xy_grid, axis=0), [batch_size, 1,",
"0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY,",
"1:2], ], axis=-1, ) predictions = tf.concat([boxes, pred_conf], axis=-1) return predictions def dense_prediction(feature_maps,",
"= self.input_size score_threshold = self.score_threshold bounding_boxes = tf.concat(bounding_boxes, axis=1) scores = tf.concat(scores, axis=1)",
"xy_grid ) * self.strides[self.i] prediction_wh = tf.exp(bbox_wh) * self.anchors[self.i] prediction_xywh = tf.concat([prediction_xy, prediction_wh],",
"axis=0), [batch_size, 1, 1, 3, 1], ) xy_grid = tf.cast(xy_grid, tf.float32) bbox_xy_sigmoid =",
"= tf.sigmoid(bbox_xy) detection_conf_sigmoid = tf.sigmoid(detection_conf) classes_prob_sigmoid = tf.sigmoid(classes_prob) prediction_xy = ( (bbox_xy_sigmoid *",
"self.input_size score_threshold = self.score_threshold bounding_boxes = tf.concat(bounding_boxes, axis=1) scores = tf.concat(scores, axis=1) scores_max",
"self.anchors = anchors self.xyscale = xyscale self.i = i def call(self, feature_map): batch_size",
"cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else: yolo_head_1 = YoloHead( cfg.INPUT_SIZE //",
"bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 8, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE,",
"box_xy[..., ::-1] box_hw = box_wh[..., ::-1] box_mins = (box_yx - (box_hw / 2.0))",
"// 16, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3 = YoloHead(",
"1, self.classes), axis=-1 ) xy_grid = tf.meshgrid( tf.range(self.grid_size), tf.range(self.grid_size) ) xy_grid = tf.expand_dims(tf.stack(xy_grid,",
"prediction_xywh = tf.concat([prediction_xy, prediction_wh], axis=-1) prediction_prob = detection_conf_sigmoid * classes_prob_sigmoid prediction_xywh = tf.reshape(prediction_xywh,",
"classes, strides, anchors, xyscale, i): super().__init__() self.grid_size = grid_size self.classes = classes self.strides",
"cfg.XYSCALE, 0, )(feature_maps[0]) bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES,",
"conv_output = tf.reshape( feature_map, (batch_size, self.grid_size, self.grid_size, 3, 5 + self.classes), ) bbox_xy,",
"input_size, score_threshold=0.4): super().__init__() self.input_size = input_size self.score_threshold = score_threshold def call(self, bounding_boxes, scores):",
"tf.concat([boxes, pred_conf], axis=-1) return predictions def dense_prediction(feature_maps, classes, tiny=False): bbox_tensors = [] prob_tensors",
"bbox_xy, bbox_wh, detection_conf, classes_prob = tf.split( conv_output, (2, 2, 1, self.classes), axis=-1 )",
"YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1]) predictions",
"self.input_size = input_size self.score_threshold = score_threshold def call(self, bounding_boxes, scores): input_size = self.input_size",
"5 + self.classes), ) bbox_xy, bbox_wh, detection_conf, classes_prob = tf.split( conv_output, (2, 2,",
"self.classes) ) return prediction_xywh, prediction_prob class FilterLayer(tf.keras.layers.Layer): def __init__(self, input_size, score_threshold=0.4): super().__init__() self.input_size",
"= (box_yx - (box_hw / 2.0)) / input_size box_maxes = (box_yx + (box_hw",
"+ self.classes), ) bbox_xy, bbox_wh, detection_conf, classes_prob = tf.split( conv_output, (2, 2, 1,",
"= (box_yx + (box_hw / 2.0)) / input_size boxes = tf.concat( [ box_mins[...,",
"anchors self.xyscale = xyscale self.i = i def call(self, feature_map): batch_size = tf.shape(feature_map)[0]",
"bbox_tensors.append(yolo_head_1[0]) prob_tensors.append(yolo_head_1[1]) yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 1,",
"(box_hw / 2.0)) / input_size box_maxes = (box_yx + (box_hw / 2.0)) /",
")(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE,",
"/ 2.0)) / input_size box_maxes = (box_yx + (box_hw / 2.0)) / input_size",
"box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2], ], axis=-1, ) predictions =",
"tf.shape(pred_conf)[-1]] ) box_xy, box_wh = tf.split(class_boxes, (2, 2), axis=-1) input_size = tf.cast(input_size, dtype=tf.float32)",
"tiny: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES_TINY, cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 0, )(feature_maps[0])",
"cfg.ANCHORS, cfg.XYSCALE, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3 = YoloHead( cfg.INPUT_SIZE // 32, classes,",
"= tf.tile( tf.expand_dims(xy_grid, axis=0), [batch_size, 1, 1, 3, 1], ) xy_grid = tf.cast(xy_grid,",
"tf.float32) bbox_xy_sigmoid = tf.sigmoid(bbox_xy) detection_conf_sigmoid = tf.sigmoid(detection_conf) classes_prob_sigmoid = tf.sigmoid(classes_prob) prediction_xy = (",
"predictions def dense_prediction(feature_maps, classes, tiny=False): bbox_tensors = [] prob_tensors = [] if tiny:",
"= tf.reshape( class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]] ) pred_conf = tf.reshape( pred_conf, [tf.shape(scores)[0], -1,",
"= YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 2, )(feature_maps[2]) bbox_tensors.append(yolo_head_3[0]) prob_tensors.append(yolo_head_3[1])",
"axis=-1) input_size = tf.cast(input_size, dtype=tf.float32) box_yx = box_xy[..., ::-1] box_hw = box_wh[..., ::-1]",
") bbox_xy, bbox_wh, detection_conf, classes_prob = tf.split( conv_output, (2, 2, 1, self.classes), axis=-1",
"= scores_max >= score_threshold class_boxes = tf.boolean_mask(bounding_boxes, mask) pred_conf = tf.boolean_mask(scores, mask) class_boxes",
"input_size = tf.cast(input_size, dtype=tf.float32) box_yx = box_xy[..., ::-1] box_hw = box_wh[..., ::-1] box_mins",
"axis=-1) mask = scores_max >= score_threshold class_boxes = tf.boolean_mask(bounding_boxes, mask) pred_conf = tf.boolean_mask(scores,",
"cfg.ANCHORS_TINY, cfg.XYSCALE_TINY, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) else: yolo_head_1 = YoloHead( cfg.INPUT_SIZE // 8,",
"return predictions def dense_prediction(feature_maps, classes, tiny=False): bbox_tensors = [] prob_tensors = [] if",
"cfg.XYSCALE, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0]) prob_tensors.append(yolo_head_2[1]) yolo_head_3 = YoloHead( cfg.INPUT_SIZE // 32, classes, cfg.STRIDES,",
"::-1] box_mins = (box_yx - (box_hw / 2.0)) / input_size box_maxes = (box_yx",
"yolo_head_2 = YoloHead( cfg.INPUT_SIZE // 16, classes, cfg.STRIDES, cfg.ANCHORS, cfg.XYSCALE, 1, )(feature_maps[1]) bbox_tensors.append(yolo_head_2[0])",
"feature_map): batch_size = tf.shape(feature_map)[0] conv_output = tf.reshape( feature_map, (batch_size, self.grid_size, self.grid_size, 3, 5",
"xyscale self.i = i def call(self, feature_map): batch_size = tf.shape(feature_map)[0] conv_output = tf.reshape(",
"xy_grid = tf.tile( tf.expand_dims(xy_grid, axis=0), [batch_size, 1, 1, 3, 1], ) xy_grid =",
"box_mins = (box_yx - (box_hw / 2.0)) / input_size box_maxes = (box_yx +",
"tf.sigmoid(classes_prob) prediction_xy = ( (bbox_xy_sigmoid * self.xyscale[self.i]) - 0.5 * (self.xyscale[self.i] - 1)",
"= tf.shape(feature_map)[0] conv_output = tf.reshape( feature_map, (batch_size, self.grid_size, self.grid_size, 3, 5 + self.classes),",
"::-1] box_hw = box_wh[..., ::-1] box_mins = (box_yx - (box_hw / 2.0)) /"
] |
[
"state['step'] = 0 # Exponential moving average of gradient values state['next_m'] = torch.zeros_like(p.data)",
"0.9 b2: Adams b2. Default: 0.999 e: Adams epsilon. Default: 1e-6 weight_decay: Weight",
"[0.0, 1.0[\".format(b2)) if not e >= 0.0: raise ValueError(\"Invalid epsilon value: {} -",
"max_grad_norm=1.0): if lr is not required and lr < 0.0: raise ValueError(\"Invalid learning",
"import Vectorizer from transfer_nlp.loaders.vocabulary import Vocabulary from transfer_nlp.plugins.config import register_plugin tqdm.pandas() @register_plugin class",
"decay fix. Params: lr: learning rate warmup: portion of t_total for the warmup,",
"of Adam algorithm with weight decay fix. Params: lr: learning rate warmup: portion",
"self.max_sequence += 2 vectors = self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids'] = vectors.progress_apply(lambda x:",
"epsilon value: {} - should be >= 0.0\".format(e)) defaults = dict(lr=lr, schedule=schedule, warmup=warmup,",
"0 # Exponential moving average of gradient values state['next_m'] = torch.zeros_like(p.data) # Exponential",
"from transfer_nlp.loaders.vectorizers import Vectorizer from transfer_nlp.loaders.vocabulary import Vocabulary from transfer_nlp.plugins.config import register_plugin tqdm.pandas()",
"= 1 - beta1 ** state['step'] # bias_correction2 = 1 - beta2 **",
"batch_size: int, vectorizer: Vectorizer): self.df = pd.read_csv(data_file) np.random.shuffle(self.df.values) # Use this code in",
"if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam does",
"using L2 regularization/weight decay with Adam, # since that will interact with the",
"self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') df = pd.read_csv(data_file) target_vocab = Vocabulary(add_unk=False) for category in sorted(set(df.category)):",
">= 0.0\".format(e)) defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, b1=b1, b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm)",
"moving average of gradient values state['next_m'] = torch.zeros_like(p.data) # Exponential moving average of",
"warmup=-1, t_total=-1, schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0): if lr is not required",
"vectors = self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids'] = vectors.progress_apply(lambda x: x[0]) self.df['attention_mask'] =",
"b1=b1, b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults) def get_lr(self): lr = []",
"loss. \"\"\" loss = None if closure is not None: loss = closure()",
"epsilon. Default: 1e-6 weight_decay: Weight decay. Default: 0.01 max_grad_norm: Maximum norm for the",
"the first and second moment running average coefficient # In-place operations to update",
"the model and returns the loss. \"\"\" loss = None if closure is",
"that reevaluates the model and returns the loss. \"\"\" loss = None if",
"schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] lr.append(lr_scheduled) return lr def step(self,",
"-1 means no warmup. Default: -1 t_total: total number of training steps for",
"if closure is not None: loss = closure() for group in self.param_groups: for",
"no warmup. Default: -1 t_total: total number of training steps for the learning",
"'warmup_cosine': warmup_cosine, 'warmup_constant': warmup_constant, 'warmup_linear': warmup_linear, } @register_plugin class BertAdam(Optimizer): \"\"\"Implements BERT version",
"-1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup']) else:",
"e >= 0.0: raise ValueError(\"Invalid epsilon value: {} - should be >= 0.0\".format(e))",
"= group['lr'] update_with_lr = lr_scheduled * update p.data.add_(-update_with_lr) state['step'] += 1 # step_size",
"not e >= 0.0: raise ValueError(\"Invalid epsilon value: {} - should be >=",
"# Decay the first and second moment running average coefficient # In-place operations",
"of using L2 regularization/weight decay with Adam, # since that will interact with",
"padding = [0] * (max_seq_length - len(input_ids)) input_ids += padding attention_mask += padding",
"if group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm']) # Decay the first and second moment",
"= lr_scheduled * update p.data.add_(-update_with_lr) state['step'] += 1 # step_size = lr_scheduled *",
"lr: learning rate warmup: portion of t_total for the warmup, -1 means no",
"if schedule not in SCHEDULES: raise ValueError(\"Invalid schedule parameter: {}\".format(schedule)) if not 0.0",
"tqdm import tqdm from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.vectorizers import Vectorizer from",
"learning rate: {} - should be >= 0.0\".format(lr)) if schedule not in SCHEDULES:",
"Optimizer from torch.optim.optimizer import required from tqdm import tqdm from transfer_nlp.loaders.loaders import DatasetSplits,",
"get_lr(self): lr = [] for group in self.param_groups: for p in group['params']: state",
"super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin def bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) #",
"x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids'] = vectors.progress_apply(lambda x: x[0]) self.df['attention_mask'] = vectors.progress_apply(lambda x: x[1])",
"step(self, closure=None): \"\"\"Performs a single optimization step. Arguments: closure (callable, optional): A closure",
"from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.vectorizers import Vectorizer from transfer_nlp.loaders.vocabulary import Vocabulary",
"from torch.optim import Optimizer from torch.optim.optimizer import required from tqdm import tqdm from",
"< warmup: return x / warmup return 1.0 - x SCHEDULES = {",
"Default: 0.999 e: Adams epsilon. Default: 1e-6 weight_decay: Weight decay. Default: 0.01 max_grad_norm:",
"m/v parameters. This is equivalent to adding the square # of the weights",
"for the learning rate schedule, -1 means constant learning rate. Default: -1 schedule:",
"p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam",
"with weight decay fix. Params: lr: learning rate warmup: portion of t_total for",
"1.0 def warmup_linear(x, warmup=0.002): if x < warmup: return x / warmup return",
"BertAdam(Optimizer): \"\"\"Implements BERT version of Adam algorithm with weight decay fix. Params: lr:",
"x < warmup: return x / warmup return 1.0 - x SCHEDULES =",
"tokens = self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence = max(self.max_sequence, len(tokens)) self.max_sequence += 2 vectors = self.df['title'].progress_apply(lambda",
"(callable, optional): A closure that reevaluates the model and returns the loss. \"\"\"",
"state['next_m'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['next_v'] =",
"group['b1'], group['b2'] # Add grad clipping if group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm']) #",
"= vectors.progress_apply(lambda x: x[2]) self.df['y_target'] = self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x)) train_df = self.df[self.df.split ==",
"Tuple[np.array, np.array, np.array]: tokens = self.tokenizer.tokenize(title) tokens = [\"[CLS]\"] + tokens + [\"[SEP]\"]",
"schedule, -1 means constant learning rate. Default: -1 schedule: schedule to use for",
"= Vocabulary(add_unk=False) for category in sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab = target_vocab def vectorize(self, title:",
"-1 means constant learning rate. Default: -1 schedule: schedule to use for the",
"-1 t_total: total number of training steps for the learning rate schedule, -1",
"raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead') state =",
"import tqdm from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.vectorizers import Vectorizer from transfer_nlp.loaders.vocabulary",
"'warmup_linear': warmup_linear, } @register_plugin class BertAdam(Optimizer): \"\"\"Implements BERT version of Adam algorithm with",
"total number of training steps for the learning rate schedule, -1 means constant",
"state['step'] += 1 # step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 # No",
"# Exponential moving average of squared gradient values state['next_v'] = torch.zeros_like(p.data) next_m, next_v",
"0.0: raise ValueError(\"Invalid epsilon value: {} - should be >= 0.0\".format(e)) defaults =",
"grad) next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad) update = next_m / (next_v.sqrt() + group['e'])",
"loss function is *not* # the correct way of using L2 regularization/weight decay",
"1.0 \"\"\" def __init__(self, params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01,",
"for the warmup (see above). Default: 'warmup_linear' b1: Adams b1. Default: 0.9 b2:",
"import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.vectorizers import Vectorizer from transfer_nlp.loaders.vocabulary import Vocabulary from transfer_nlp.plugins.config",
"want to decay the weights in a manner that doesn't interact # with",
"lr def step(self, closure=None): \"\"\"Performs a single optimization step. Arguments: closure (callable, optional):",
"raise ValueError(\"Invalid epsilon value: {} - should be >= 0.0\".format(e)) defaults = dict(lr=lr,",
"} @register_plugin class BertAdam(Optimizer): \"\"\"Implements BERT version of Adam algorithm with weight decay",
"group['b2'] # Add grad clipping if group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm']) # Decay",
"def __init__(self, data_file: str): super().__init__(data_file=data_file) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') df = pd.read_csv(data_file) target_vocab =",
"N = 1000 self.df = self.df.head(n=N) # preprocessing self.vectorizer: Vectorizer = vectorizer self.max_sequence",
"0.5 * (1.0 + torch.cos(math.pi * x)) def warmup_constant(x, warmup=0.002): if x <",
"consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0:",
"math from typing import Tuple import numpy as np import pandas as pd",
"= max(self.max_sequence, len(tokens)) self.max_sequence += 2 vectors = self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids']",
"= self.df.head(n=N) # preprocessing self.vectorizer: Vectorizer = vectorizer self.max_sequence = 0 for title",
"0.01 max_grad_norm: Maximum norm for the gradients (-1 means no clipping). Default: 1.0",
"in strange ways. # # Instead we want to decay the weights in",
"# No bias correction # bias_correction1 = 1 - beta1 ** state['step'] #",
"manner that doesn't interact # with the m/v parameters. This is equivalent to",
"return x / warmup return 1.0 def warmup_linear(x, warmup=0.002): if x < warmup:",
"Default: -1 schedule: schedule to use for the warmup (see above). Default: 'warmup_linear'",
"input_ids = self.tokenizer.convert_tokens_to_ids(tokens) attention_mask = [1] * len(input_ids) padding = [0] * (max_seq_length",
"[0] if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step']",
"b2. Default: 0.999 e: Adams epsilon. Default: 1e-6 weight_decay: Weight decay. Default: 0.01",
"= next_m / (next_v.sqrt() + group['e']) # Just adding the square of the",
"is equivalent to adding the square # of the weights to the loss",
"(1.0 + torch.cos(math.pi * x)) def warmup_constant(x, warmup=0.002): if x < warmup: return",
"should be >= 0.0\".format(e)) defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, b1=b1, b2=b2, e=e,",
"if not 0.0 <= warmup < 1.0 and not warmup == -1: raise",
"the square # of the weights to the loss with plain (non-momentum) SGD.",
"if not 0.0 <= b2 < 1.0: raise ValueError(\"Invalid b2 parameter: {} -",
"= BertTokenizer.from_pretrained('bert-base-uncased') df = pd.read_csv(data_file) target_vocab = Vocabulary(add_unk=False) for category in sorted(set(df.category)): target_vocab.add_token(category)",
"self.df['token_type_ids'] = vectors.progress_apply(lambda x: x[2]) self.df['y_target'] = self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x)) train_df = self.df[self.df.split",
"from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification from torch.nn.utils import clip_grad_norm_ from torch.optim import Optimizer",
"self).__init__(params, defaults) def get_lr(self): lr = [] for group in self.param_groups: for p",
"weights to the loss function is *not* # the correct way of using",
"= self.df[self.df.split == 'val'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] test_df = self.df[self.df.split == 'test'][['input_ids', 'attention_mask',",
"Default: 1e-6 weight_decay: Weight decay. Default: 0.01 max_grad_norm: Maximum norm for the gradients",
"this code in dev mode N = 1000 self.df = self.df.head(n=N) # preprocessing",
"plain (non-momentum) SGD. if group['weight_decay'] > 0.0: update += group['weight_decay'] * p.data if",
"required from tqdm import tqdm from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.vectorizers import",
"from torch.nn.utils import clip_grad_norm_ from torch.optim import Optimizer from torch.optim.optimizer import required from",
"sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab = target_vocab def vectorize(self, title: str, max_seq_length: int) -> Tuple[np.array,",
"closure=None): \"\"\"Performs a single optimization step. Arguments: closure (callable, optional): A closure that",
"None: loss = closure() for group in self.param_groups: for p in group['params']: if",
"t_total=t_total, b1=b1, b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults) def get_lr(self): lr =",
"warmup=0.002): if x < warmup: return x / warmup return 0.5 * (1.0",
"BertTokenizer.from_pretrained('bert-base-uncased') df = pd.read_csv(data_file) target_vocab = Vocabulary(add_unk=False) for category in sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab",
"if group['weight_decay'] > 0.0: update += group['weight_decay'] * p.data if group['t_total'] != -1:",
"and v parameters in strange ways. # # Instead we want to decay",
"= None if closure is not None: loss = closure() for group in",
"not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State",
"step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 # No bias correction # bias_correction1",
"that will interact with the m and v parameters in strange ways. #",
"gradients (-1 means no clipping). Default: 1.0 \"\"\" def __init__(self, params, lr=required, warmup=-1,",
"max_seq_length: int) -> Tuple[np.array, np.array, np.array]: tokens = self.tokenizer.tokenize(title) tokens = [\"[CLS]\"] +",
"dev mode N = 1000 self.df = self.df.head(n=N) # preprocessing self.vectorizer: Vectorizer =",
"/ bias_correction1 # No bias correction # bias_correction1 = 1 - beta1 **",
"does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] #",
"returns the loss. \"\"\" loss = None if closure is not None: loss",
"the weights to the loss with plain (non-momentum) SGD. if group['weight_decay'] > 0.0:",
"'val'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] test_df = self.df[self.df.split == 'test'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df),",
"__init__(self, data_file: str): super().__init__(data_file=data_file) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') df = pd.read_csv(data_file) target_vocab = Vocabulary(add_unk=False)",
"schedule to use for the warmup (see above). Default: 'warmup_linear' b1: Adams b1.",
"DataFrameDataset from transfer_nlp.loaders.vectorizers import Vectorizer from transfer_nlp.loaders.vocabulary import Vocabulary from transfer_nlp.plugins.config import register_plugin",
"means constant learning rate. Default: -1 schedule: schedule to use for the warmup",
"or -1\".format(warmup)) if not 0.0 <= b1 < 1.0: raise ValueError(\"Invalid b1 parameter:",
"since that will interact with the m and v parameters in strange ways.",
"Adam, # since that will interact with the m and v parameters in",
"desc=\"Getting max sequence\"): tokens = self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence = max(self.max_sequence, len(tokens)) self.max_sequence += 2",
"# Use this code in dev mode N = 1000 self.df = self.df.head(n=N)",
"1 # step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 # No bias correction",
"a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the",
"np.array]: tokens = self.tokenizer.tokenize(title) tokens = [\"[CLS]\"] + tokens + [\"[SEP]\"] token_type_ids =",
"self.param_groups: for p in group['params']: state = self.state[p] if len(state) == 0: return",
"np.array(attention_mask), np.array(token_type_ids) @register_plugin class BertDataset(DatasetSplits): def __init__(self, data_file: str, batch_size: int, vectorizer: Vectorizer):",
"learning rate. Default: -1 schedule: schedule to use for the warmup (see above).",
"not in SCHEDULES: raise ValueError(\"Invalid schedule parameter: {}\".format(schedule)) if not 0.0 <= warmup",
"with Adam, # since that will interact with the m and v parameters",
"the loss with plain (non-momentum) SGD. if group['weight_decay'] > 0.0: update += group['weight_decay']",
"return 1.0 def warmup_linear(x, warmup=0.002): if x < warmup: return x / warmup",
"tokens = self.tokenizer.tokenize(title) tokens = [\"[CLS]\"] + tokens + [\"[SEP]\"] token_type_ids = [0]",
"'train'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] val_df = self.df[self.df.split == 'val'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] test_df",
"- len(input_ids)) input_ids += padding attention_mask += padding token_type_ids += padding return np.array(input_ids),",
"# preprocessing self.vectorizer: Vectorizer = vectorizer self.max_sequence = 0 for title in tqdm(self.df.title,",
"schedule not in SCHEDULES: raise ValueError(\"Invalid schedule parameter: {}\".format(schedule)) if not 0.0 <=",
"with the m/v parameters. This is equivalent to adding the square # of",
"group['weight_decay'] * p.data if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr']",
"1 - beta1 ** state['step'] # bias_correction2 = 1 - beta2 ** state['step']",
"group['params']: state = self.state[p] if len(state) == 0: return [0] if group['t_total'] !=",
"== 0: state['step'] = 0 # Exponential moving average of gradient values state['next_m']",
"self.target_vocab = target_vocab def vectorize(self, title: str, max_seq_length: int) -> Tuple[np.array, np.array, np.array]:",
"for group in self.param_groups: for p in group['params']: if p.grad is None: continue",
"target_vocab def vectorize(self, title: str, max_seq_length: int) -> Tuple[np.array, np.array, np.array]: tokens =",
"def vectorize(self, title: str, max_seq_length: int) -> Tuple[np.array, np.array, np.array]: tokens = self.tokenizer.tokenize(title)",
"decay. Default: 0.01 max_grad_norm: Maximum norm for the gradients (-1 means no clipping).",
"+ [\"[SEP]\"] token_type_ids = [0] * len(tokens) input_ids = self.tokenizer.convert_tokens_to_ids(tokens) attention_mask = [1]",
"str, batch_size: int, vectorizer: Vectorizer): self.df = pd.read_csv(data_file) np.random.shuffle(self.df.values) # Use this code",
"weights in a manner that doesn't interact # with the m/v parameters. This",
"group['lr'] lr.append(lr_scheduled) return lr def step(self, closure=None): \"\"\"Performs a single optimization step. Arguments:",
"# since that will interact with the m and v parameters in strange",
"super(BertAdam, self).__init__(params, defaults) def get_lr(self): lr = [] for group in self.param_groups: for",
"self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x)) train_df = self.df[self.df.split == 'train'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] val_df =",
"group['warmup']) else: lr_scheduled = group['lr'] lr.append(lr_scheduled) return lr def step(self, closure=None): \"\"\"Performs a",
"no clipping). Default: 1.0 \"\"\" def __init__(self, params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear', b1=0.9,",
"self.max_sequence = max(self.max_sequence, len(tokens)) self.max_sequence += 2 vectors = self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence))",
"operations to update the averages at the same time next_m.mul_(beta1).add_(1 - beta1, grad)",
"clipping). Default: 1.0 \"\"\" def __init__(self, params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear', b1=0.9, b2=0.999,",
"parameters. This is equivalent to adding the square # of the weights to",
"clipping if group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm']) # Decay the first and second",
"strange ways. # # Instead we want to decay the weights in a",
"+ tokens + [\"[SEP]\"] token_type_ids = [0] * len(tokens) input_ids = self.tokenizer.convert_tokens_to_ids(tokens) attention_mask",
"tqdm(self.df.title, desc=\"Getting max sequence\"): tokens = self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence = max(self.max_sequence, len(tokens)) self.max_sequence +=",
"and second moment running average coefficient # In-place operations to update the averages",
"# Just adding the square of the weights to the loss function is",
"weights to the loss with plain (non-momentum) SGD. if group['weight_decay'] > 0.0: update",
"vectorizer self.max_sequence = 0 for title in tqdm(self.df.title, desc=\"Getting max sequence\"): tokens =",
"to update the averages at the same time next_m.mul_(beta1).add_(1 - beta1, grad) next_v.mul_(beta2).addcmul_(1",
"= vectors.progress_apply(lambda x: x[1]) self.df['token_type_ids'] = vectors.progress_apply(lambda x: x[2]) self.df['y_target'] = self.df['category'].progress_apply(lambda x:",
"means no warmup. Default: -1 t_total: total number of training steps for the",
"- should be in [0.0, 1.0[\".format(b2)) if not e >= 0.0: raise ValueError(\"Invalid",
"* math.sqrt(bias_correction2) / bias_correction1 # No bias correction # bias_correction1 = 1 -",
"bias_correction1 = 1 - beta1 ** state['step'] # bias_correction2 = 1 - beta2",
"register_plugin tqdm.pandas() @register_plugin class BertVectorizer(Vectorizer): def __init__(self, data_file: str): super().__init__(data_file=data_file) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')",
"'test'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin def bert_model():",
"params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0): if lr is",
"constant learning rate. Default: -1 schedule: schedule to use for the warmup (see",
"ValueError(\"Invalid schedule parameter: {}\".format(schedule)) if not 0.0 <= warmup < 1.0 and not",
"def get_lr(self): lr = [] for group in self.param_groups: for p in group['params']:",
"interact with the m and v parameters in strange ways. # # Instead",
"# # Instead we want to decay the weights in a manner that",
"that doesn't interact # with the m/v parameters. This is equivalent to adding",
"[] for group in self.param_groups: for p in group['params']: state = self.state[p] if",
"code in dev mode N = 1000 self.df = self.df.head(n=N) # preprocessing self.vectorizer:",
"b2: Adams b2. Default: 0.999 e: Adams epsilon. Default: 1e-6 weight_decay: Weight decay.",
"+= padding return np.array(input_ids), np.array(attention_mask), np.array(token_type_ids) @register_plugin class BertDataset(DatasetSplits): def __init__(self, data_file: str,",
"algorithm with weight decay fix. Params: lr: learning rate warmup: portion of t_total",
"above). Default: 'warmup_linear' b1: Adams b1. Default: 0.9 b2: Adams b2. Default: 0.999",
"weight_decay: Weight decay. Default: 0.01 max_grad_norm: Maximum norm for the gradients (-1 means",
"of the weights to the loss function is *not* # the correct way",
"preprocessing self.vectorizer: Vectorizer = vectorizer self.max_sequence = 0 for title in tqdm(self.df.title, desc=\"Getting",
"val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin def bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) # Optimizer Code from",
"group['weight_decay'] > 0.0: update += group['weight_decay'] * p.data if group['t_total'] != -1: schedule_fct",
"be in [0.0, 1.0[\".format(b1)) if not 0.0 <= b2 < 1.0: raise ValueError(\"Invalid",
"squared gradient values state['next_v'] = torch.zeros_like(p.data) next_m, next_v = state['next_m'], state['next_v'] beta1, beta2",
"2 vectors = self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids'] = vectors.progress_apply(lambda x: x[0]) self.df['attention_mask']",
"x SCHEDULES = { 'warmup_cosine': warmup_cosine, 'warmup_constant': warmup_constant, 'warmup_linear': warmup_linear, } @register_plugin class",
"gradient values state['next_v'] = torch.zeros_like(p.data) next_m, next_v = state['next_m'], state['next_v'] beta1, beta2 =",
"= 0 for title in tqdm(self.df.title, desc=\"Getting max sequence\"): tokens = self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence",
"schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled",
"grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead') state",
"1.0 and not warmup == -1: raise ValueError(\"Invalid warmup: {} - should be",
"for title in tqdm(self.df.title, desc=\"Getting max sequence\"): tokens = self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence = max(self.max_sequence,",
"Tuple import numpy as np import pandas as pd import torch from pytorch_pretrained_bert",
"[0.0, 1.0[ or -1\".format(warmup)) if not 0.0 <= b1 < 1.0: raise ValueError(\"Invalid",
"(non-momentum) SGD. if group['weight_decay'] > 0.0: update += group['weight_decay'] * p.data if group['t_total']",
"p.data if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step']",
"Vectorizer from transfer_nlp.loaders.vocabulary import Vocabulary from transfer_nlp.plugins.config import register_plugin tqdm.pandas() @register_plugin class BertVectorizer(Vectorizer):",
"is not required and lr < 0.0: raise ValueError(\"Invalid learning rate: {} -",
"support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization",
"beta2 = group['b1'], group['b2'] # Add grad clipping if group['max_grad_norm'] > 0: clip_grad_norm_(p,",
"max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults) def get_lr(self): lr = [] for group in self.param_groups:",
"in a manner that doesn't interact # with the m/v parameters. This is",
"is not None: loss = closure() for group in self.param_groups: for p in",
"warmup: return x / warmup return 0.5 * (1.0 + torch.cos(math.pi * x))",
"p.data.add_(-update_with_lr) state['step'] += 1 # step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 #",
"rate schedule, -1 means constant learning rate. Default: -1 schedule: schedule to use",
"clip_grad_norm_(p, group['max_grad_norm']) # Decay the first and second moment running average coefficient #",
"padding attention_mask += padding token_type_ids += padding return np.array(input_ids), np.array(attention_mask), np.array(token_type_ids) @register_plugin class",
"next_v = state['next_m'], state['next_v'] beta1, beta2 = group['b1'], group['b2'] # Add grad clipping",
"from torch.optim.optimizer import required from tqdm import tqdm from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset",
"grad) update = next_m / (next_v.sqrt() + group['e']) # Just adding the square",
"return [0] if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] *",
"== 'test'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin def",
"loss with plain (non-momentum) SGD. if group['weight_decay'] > 0.0: update += group['weight_decay'] *",
"tokens = [\"[CLS]\"] + tokens + [\"[SEP]\"] token_type_ids = [0] * len(tokens) input_ids",
"return x / warmup return 1.0 - x SCHEDULES = { 'warmup_cosine': warmup_cosine,",
"# with the m/v parameters. This is equivalent to adding the square #",
"(next_v.sqrt() + group['e']) # Just adding the square of the weights to the",
"b2 parameter: {} - should be in [0.0, 1.0[\".format(b2)) if not e >=",
"-1 schedule: schedule to use for the warmup (see above). Default: 'warmup_linear' b1:",
"Add grad clipping if group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm']) # Decay the first",
"the loss function is *not* # the correct way of using L2 regularization/weight",
"moment running average coefficient # In-place operations to update the averages at the",
"raise ValueError(\"Invalid warmup: {} - should be in [0.0, 1.0[ or -1\".format(warmup)) if",
"import torch from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification from torch.nn.utils import clip_grad_norm_ from torch.optim",
"learning rate warmup: portion of t_total for the warmup, -1 means no warmup.",
"# bias_correction1 = 1 - beta1 ** state['step'] # bias_correction2 = 1 -",
"@register_plugin def bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) # Optimizer Code from HuggingFace repo def",
"Default: 1.0 \"\"\" def __init__(self, params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-6,",
"== -1: raise ValueError(\"Invalid warmup: {} - should be in [0.0, 1.0[ or",
"bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) # Optimizer Code from HuggingFace repo def warmup_cosine(x, warmup=0.002):",
"Default: -1 t_total: total number of training steps for the learning rate schedule,",
"torch.optim import Optimizer from torch.optim.optimizer import required from tqdm import tqdm from transfer_nlp.loaders.loaders",
"e=1e-6, weight_decay=0.01, max_grad_norm=1.0): if lr is not required and lr < 0.0: raise",
"if x < warmup: return x / warmup return 1.0 - x SCHEDULES",
"running average coefficient # In-place operations to update the averages at the same",
"import numpy as np import pandas as pd import torch from pytorch_pretrained_bert import",
"* schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] lr.append(lr_scheduled) return lr def",
"not 0.0 <= warmup < 1.0 and not warmup == -1: raise ValueError(\"Invalid",
"for group in self.param_groups: for p in group['params']: state = self.state[p] if len(state)",
"# step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 # No bias correction #",
"self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence = max(self.max_sequence, len(tokens)) self.max_sequence += 2 vectors = self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x,",
"closure that reevaluates the model and returns the loss. \"\"\" loss = None",
"if lr is not required and lr < 0.0: raise ValueError(\"Invalid learning rate:",
"SCHEDULES: raise ValueError(\"Invalid schedule parameter: {}\".format(schedule)) if not 0.0 <= warmup < 1.0",
"return 0.5 * (1.0 + torch.cos(math.pi * x)) def warmup_constant(x, warmup=0.002): if x",
"< 1.0: raise ValueError(\"Invalid b2 parameter: {} - should be in [0.0, 1.0[\".format(b2))",
"of the weights to the loss with plain (non-momentum) SGD. if group['weight_decay'] >",
"m and v parameters in strange ways. # # Instead we want to",
"attention_mask += padding token_type_ids += padding return np.array(input_ids), np.array(attention_mask), np.array(token_type_ids) @register_plugin class BertDataset(DatasetSplits):",
"\"\"\" loss = None if closure is not None: loss = closure() for",
"b1: Adams b1. Default: 0.9 b2: Adams b2. Default: 0.999 e: Adams epsilon.",
"'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin def bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased',",
"< 1.0 and not warmup == -1: raise ValueError(\"Invalid warmup: {} - should",
"+= 2 vectors = self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids'] = vectors.progress_apply(lambda x: x[0])",
"0: clip_grad_norm_(p, group['max_grad_norm']) # Decay the first and second moment running average coefficient",
"= group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] lr.append(lr_scheduled) return",
"averages at the same time next_m.mul_(beta1).add_(1 - beta1, grad) next_v.mul_(beta2).addcmul_(1 - beta2, grad,",
"weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults) def get_lr(self): lr = [] for group in",
"# Instead we want to decay the weights in a manner that doesn't",
"padding return np.array(input_ids), np.array(attention_mask), np.array(token_type_ids) @register_plugin class BertDataset(DatasetSplits): def __init__(self, data_file: str, batch_size:",
"correct way of using L2 regularization/weight decay with Adam, # since that will",
"== 'train'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] val_df = self.df[self.df.split == 'val'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']]",
"'y_target']] test_df = self.df[self.df.split == 'test'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size,",
"should be in [0.0, 1.0[ or -1\".format(warmup)) if not 0.0 <= b1 <",
"# Exponential moving average of gradient values state['next_m'] = torch.zeros_like(p.data) # Exponential moving",
"p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not",
"= self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x)) train_df = self.df[self.df.split == 'train'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] val_df",
"rate. Default: -1 schedule: schedule to use for the warmup (see above). Default:",
"# State initialization if len(state) == 0: state['step'] = 0 # Exponential moving",
"next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad) update = next_m / (next_v.sqrt() + group['e']) #",
"= closure() for group in self.param_groups: for p in group['params']: if p.grad is",
"'warmup_constant': warmup_constant, 'warmup_linear': warmup_linear, } @register_plugin class BertAdam(Optimizer): \"\"\"Implements BERT version of Adam",
"bias correction # bias_correction1 = 1 - beta1 ** state['step'] # bias_correction2 =",
"if grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')",
"x: x[0]) self.df['attention_mask'] = vectors.progress_apply(lambda x: x[1]) self.df['token_type_ids'] = vectors.progress_apply(lambda x: x[2]) self.df['y_target']",
"= [\"[CLS]\"] + tokens + [\"[SEP]\"] token_type_ids = [0] * len(tokens) input_ids =",
"> 0: clip_grad_norm_(p, group['max_grad_norm']) # Decay the first and second moment running average",
"in sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab = target_vocab def vectorize(self, title: str, max_seq_length: int) ->",
"raise ValueError(\"Invalid learning rate: {} - should be >= 0.0\".format(lr)) if schedule not",
"for category in sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab = target_vocab def vectorize(self, title: str, max_seq_length:",
"from transfer_nlp.plugins.config import register_plugin tqdm.pandas() @register_plugin class BertVectorizer(Vectorizer): def __init__(self, data_file: str): super().__init__(data_file=data_file)",
"warmup=warmup, t_total=t_total, b1=b1, b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults) def get_lr(self): lr",
"as pd import torch from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification from torch.nn.utils import clip_grad_norm_",
"'attention_mask', 'token_type_ids', 'y_target']] val_df = self.df[self.df.split == 'val'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] test_df =",
"import math from typing import Tuple import numpy as np import pandas as",
"= self.tokenizer.convert_tokens_to_ids(tokens) attention_mask = [1] * len(input_ids) padding = [0] * (max_seq_length -",
"ValueError(\"Invalid b1 parameter: {} - should be in [0.0, 1.0[\".format(b1)) if not 0.0",
"> 0.0: update += group['weight_decay'] * p.data if group['t_total'] != -1: schedule_fct =",
"-> Tuple[np.array, np.array, np.array]: tokens = self.tokenizer.tokenize(title) tokens = [\"[CLS]\"] + tokens +",
"self.df.head(n=N) # preprocessing self.vectorizer: Vectorizer = vectorizer self.max_sequence = 0 for title in",
"for p in group['params']: if p.grad is None: continue grad = p.grad.data if",
"mode N = 1000 self.df = self.df.head(n=N) # preprocessing self.vectorizer: Vectorizer = vectorizer",
"schedule: schedule to use for the warmup (see above). Default: 'warmup_linear' b1: Adams",
"the m/v parameters. This is equivalent to adding the square # of the",
"and returns the loss. \"\"\" loss = None if closure is not None:",
"state = self.state[p] if len(state) == 0: return [0] if group['t_total'] != -1:",
"for p in group['params']: state = self.state[p] if len(state) == 0: return [0]",
"return np.array(input_ids), np.array(attention_mask), np.array(token_type_ids) @register_plugin class BertDataset(DatasetSplits): def __init__(self, data_file: str, batch_size: int,",
"of gradient values state['next_m'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient",
"of t_total for the warmup, -1 means no warmup. Default: -1 t_total: total",
"ValueError(\"Invalid learning rate: {} - should be >= 0.0\".format(lr)) if schedule not in",
"single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model",
"weight_decay=0.01, max_grad_norm=1.0): if lr is not required and lr < 0.0: raise ValueError(\"Invalid",
">= 0.0\".format(lr)) if schedule not in SCHEDULES: raise ValueError(\"Invalid schedule parameter: {}\".format(schedule)) if",
"Adams epsilon. Default: 1e-6 weight_decay: Weight decay. Default: 0.01 max_grad_norm: Maximum norm for",
"ways. # # Instead we want to decay the weights in a manner",
"same time next_m.mul_(beta1).add_(1 - beta1, grad) next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad) update =",
"np.array(token_type_ids) @register_plugin class BertDataset(DatasetSplits): def __init__(self, data_file: str, batch_size: int, vectorizer: Vectorizer): self.df",
"self.df = self.df.head(n=N) # preprocessing self.vectorizer: Vectorizer = vectorizer self.max_sequence = 0 for",
"closure (callable, optional): A closure that reevaluates the model and returns the loss.",
"vectorizer: Vectorizer): self.df = pd.read_csv(data_file) np.random.shuffle(self.df.values) # Use this code in dev mode",
"if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient",
"max_seq_length=self.max_sequence)) self.df['input_ids'] = vectors.progress_apply(lambda x: x[0]) self.df['attention_mask'] = vectors.progress_apply(lambda x: x[1]) self.df['token_type_ids'] =",
"num_labels=4) # Optimizer Code from HuggingFace repo def warmup_cosine(x, warmup=0.002): if x <",
"the square of the weights to the loss function is *not* # the",
"L2 regularization/weight decay with Adam, # since that will interact with the m",
"Arguments: closure (callable, optional): A closure that reevaluates the model and returns the",
"0.0 <= b1 < 1.0: raise ValueError(\"Invalid b1 parameter: {} - should be",
"# In-place operations to update the averages at the same time next_m.mul_(beta1).add_(1 -",
"len(tokens) input_ids = self.tokenizer.convert_tokens_to_ids(tokens) attention_mask = [1] * len(input_ids) padding = [0] *",
"{ 'warmup_cosine': warmup_cosine, 'warmup_constant': warmup_constant, 'warmup_linear': warmup_linear, } @register_plugin class BertAdam(Optimizer): \"\"\"Implements BERT",
"class BertAdam(Optimizer): \"\"\"Implements BERT version of Adam algorithm with weight decay fix. Params:",
"group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] lr.append(lr_scheduled) return lr",
"warmup_cosine, 'warmup_constant': warmup_constant, 'warmup_linear': warmup_linear, } @register_plugin class BertAdam(Optimizer): \"\"\"Implements BERT version of",
"BertDataset(DatasetSplits): def __init__(self, data_file: str, batch_size: int, vectorizer: Vectorizer): self.df = pd.read_csv(data_file) np.random.shuffle(self.df.values)",
"self.vectorizer.target_vocab.lookup_token(x)) train_df = self.df[self.df.split == 'train'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] val_df = self.df[self.df.split ==",
"= self.tokenizer.tokenize(title) tokens = [\"[CLS]\"] + tokens + [\"[SEP]\"] token_type_ids = [0] *",
"parameter: {}\".format(schedule)) if not 0.0 <= warmup < 1.0 and not warmup ==",
"warmup_cosine(x, warmup=0.002): if x < warmup: return x / warmup return 0.5 *",
"/ group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] lr.append(lr_scheduled) return lr def step(self, closure=None):",
"state['next_m'], state['next_v'] beta1, beta2 = group['b1'], group['b2'] # Add grad clipping if group['max_grad_norm']",
"update p.data.add_(-update_with_lr) state['step'] += 1 # step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1",
"= [0] * len(tokens) input_ids = self.tokenizer.convert_tokens_to_ids(tokens) attention_mask = [1] * len(input_ids) padding",
"+ torch.cos(math.pi * x)) def warmup_constant(x, warmup=0.002): if x < warmup: return x",
"if not e >= 0.0: raise ValueError(\"Invalid epsilon value: {} - should be",
"0.0 <= warmup < 1.0 and not warmup == -1: raise ValueError(\"Invalid warmup:",
"optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and",
"self.tokenizer.tokenize(title) tokens = [\"[CLS]\"] + tokens + [\"[SEP]\"] token_type_ids = [0] * len(tokens)",
"group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm']) # Decay the first and second moment running",
"None if closure is not None: loss = closure() for group in self.param_groups:",
"grad clipping if group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm']) # Decay the first and",
"decay the weights in a manner that doesn't interact # with the m/v",
"x / warmup return 0.5 * (1.0 + torch.cos(math.pi * x)) def warmup_constant(x,",
"raise ValueError(\"Invalid schedule parameter: {}\".format(schedule)) if not 0.0 <= warmup < 1.0 and",
"self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids'] = vectors.progress_apply(lambda x: x[0]) self.df['attention_mask'] = vectors.progress_apply(lambda x: x[1]) self.df['token_type_ids']",
"rate warmup: portion of t_total for the warmup, -1 means no warmup. Default:",
"'attention_mask', 'token_type_ids', 'y_target']] test_df = self.df[self.df.split == 'test'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size,",
"grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients, please",
"transfer_nlp.loaders.vocabulary import Vocabulary from transfer_nlp.plugins.config import register_plugin tqdm.pandas() @register_plugin class BertVectorizer(Vectorizer): def __init__(self,",
"return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) # Optimizer Code from HuggingFace repo def warmup_cosine(x, warmup=0.002): if",
"- should be in [0.0, 1.0[\".format(b1)) if not 0.0 <= b2 < 1.0:",
"warmup_constant, 'warmup_linear': warmup_linear, } @register_plugin class BertAdam(Optimizer): \"\"\"Implements BERT version of Adam algorithm",
"from typing import Tuple import numpy as np import pandas as pd import",
"beta1 ** state['step'] # bias_correction2 = 1 - beta2 ** state['step'] return loss",
"(see above). Default: 'warmup_linear' b1: Adams b1. Default: 0.9 b2: Adams b2. Default:",
"== 0: return [0] if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled =",
"warmup return 1.0 - x SCHEDULES = { 'warmup_cosine': warmup_cosine, 'warmup_constant': warmup_constant, 'warmup_linear':",
"update += group['weight_decay'] * p.data if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled",
"warmup: return x / warmup return 1.0 - x SCHEDULES = { 'warmup_cosine':",
"model and returns the loss. \"\"\" loss = None if closure is not",
"vectors.progress_apply(lambda x: x[0]) self.df['attention_mask'] = vectors.progress_apply(lambda x: x[1]) self.df['token_type_ids'] = vectors.progress_apply(lambda x: x[2])",
"group['max_grad_norm']) # Decay the first and second moment running average coefficient # In-place",
"+= 1 # step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 # No bias",
"if x < warmup: return x / warmup return 1.0 def warmup_linear(x, warmup=0.002):",
"BertVectorizer(Vectorizer): def __init__(self, data_file: str): super().__init__(data_file=data_file) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') df = pd.read_csv(data_file) target_vocab",
"self.df = pd.read_csv(data_file) np.random.shuffle(self.df.values) # Use this code in dev mode N =",
"self.df[self.df.split == 'test'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin",
"instead') state = self.state[p] # State initialization if len(state) == 0: state['step'] =",
"vectors.progress_apply(lambda x: x[1]) self.df['token_type_ids'] = vectors.progress_apply(lambda x: x[2]) self.df['y_target'] = self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x))",
"loss = closure() for group in self.param_groups: for p in group['params']: if p.grad",
"Exponential moving average of gradient values state['next_m'] = torch.zeros_like(p.data) # Exponential moving average",
"to the loss with plain (non-momentum) SGD. if group['weight_decay'] > 0.0: update +=",
"Code from HuggingFace repo def warmup_cosine(x, warmup=0.002): if x < warmup: return x",
"typing import Tuple import numpy as np import pandas as pd import torch",
"np.array, np.array]: tokens = self.tokenizer.tokenize(title) tokens = [\"[CLS]\"] + tokens + [\"[SEP]\"] token_type_ids",
"= self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids'] = vectors.progress_apply(lambda x: x[0]) self.df['attention_mask'] = vectors.progress_apply(lambda",
"else: lr_scheduled = group['lr'] lr.append(lr_scheduled) return lr def step(self, closure=None): \"\"\"Performs a single",
"update the averages at the same time next_m.mul_(beta1).add_(1 - beta1, grad) next_v.mul_(beta2).addcmul_(1 -",
"= pd.read_csv(data_file) np.random.shuffle(self.df.values) # Use this code in dev mode N = 1000",
"len(input_ids) padding = [0] * (max_seq_length - len(input_ids)) input_ids += padding attention_mask +=",
"Maximum norm for the gradients (-1 means no clipping). Default: 1.0 \"\"\" def",
"warmup_constant(x, warmup=0.002): if x < warmup: return x / warmup return 1.0 def",
"-1: raise ValueError(\"Invalid warmup: {} - should be in [0.0, 1.0[ or -1\".format(warmup))",
"return 1.0 - x SCHEDULES = { 'warmup_cosine': warmup_cosine, 'warmup_constant': warmup_constant, 'warmup_linear': warmup_linear,",
"schedule=schedule, warmup=warmup, t_total=t_total, b1=b1, b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults) def get_lr(self):",
"* p.data if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] *",
"for the gradients (-1 means no clipping). Default: 1.0 \"\"\" def __init__(self, params,",
"0.999 e: Adams epsilon. Default: 1e-6 weight_decay: Weight decay. Default: 0.01 max_grad_norm: Maximum",
"group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam",
"state['next_v'] = torch.zeros_like(p.data) next_m, next_v = state['next_m'], state['next_v'] beta1, beta2 = group['b1'], group['b2']",
"norm for the gradients (-1 means no clipping). Default: 1.0 \"\"\" def __init__(self,",
"@register_plugin class BertDataset(DatasetSplits): def __init__(self, data_file: str, batch_size: int, vectorizer: Vectorizer): self.df =",
"!= -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup'])",
"as np import pandas as pd import torch from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification",
"0.0\".format(e)) defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, b1=b1, b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam,",
"(max_seq_length - len(input_ids)) input_ids += padding attention_mask += padding token_type_ids += padding return",
"self.state[p] if len(state) == 0: return [0] if group['t_total'] != -1: schedule_fct =",
"coefficient # In-place operations to update the averages at the same time next_m.mul_(beta1).add_(1",
"class BertVectorizer(Vectorizer): def __init__(self, data_file: str): super().__init__(data_file=data_file) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') df = pd.read_csv(data_file)",
"test_batch_size=batch_size) @register_plugin def bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) # Optimizer Code from HuggingFace repo",
"values state['next_v'] = torch.zeros_like(p.data) next_m, next_v = state['next_m'], state['next_v'] beta1, beta2 = group['b1'],",
"version of Adam algorithm with weight decay fix. Params: lr: learning rate warmup:",
"self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids'] = vectors.progress_apply(lambda x: x[0]) self.df['attention_mask'] = vectors.progress_apply(lambda x:",
"+= padding token_type_ids += padding return np.array(input_ids), np.array(attention_mask), np.array(token_type_ids) @register_plugin class BertDataset(DatasetSplits): def",
"attention_mask = [1] * len(input_ids) padding = [0] * (max_seq_length - len(input_ids)) input_ids",
"'y_target']] val_df = self.df[self.df.split == 'val'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] test_df = self.df[self.df.split ==",
"+ group['e']) # Just adding the square of the weights to the loss",
"b1. Default: 0.9 b2: Adams b2. Default: 0.999 e: Adams epsilon. Default: 1e-6",
"torch.cos(math.pi * x)) def warmup_constant(x, warmup=0.002): if x < warmup: return x /",
"= p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients, please consider",
"pandas as pd import torch from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification from torch.nn.utils import",
"<= warmup < 1.0 and not warmup == -1: raise ValueError(\"Invalid warmup: {}",
"x / warmup return 1.0 def warmup_linear(x, warmup=0.002): if x < warmup: return",
"str, max_seq_length: int) -> Tuple[np.array, np.array, np.array]: tokens = self.tokenizer.tokenize(title) tokens = [\"[CLS]\"]",
"the correct way of using L2 regularization/weight decay with Adam, # since that",
"torch.zeros_like(p.data) next_m, next_v = state['next_m'], state['next_v'] beta1, beta2 = group['b1'], group['b2'] # Add",
"1.0[\".format(b2)) if not e >= 0.0: raise ValueError(\"Invalid epsilon value: {} - should",
"len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values",
"tqdm.pandas() @register_plugin class BertVectorizer(Vectorizer): def __init__(self, data_file: str): super().__init__(data_file=data_file) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') df",
"rate: {} - should be >= 0.0\".format(lr)) if schedule not in SCHEDULES: raise",
"-1\".format(warmup)) if not 0.0 <= b1 < 1.0: raise ValueError(\"Invalid b1 parameter: {}",
"+= padding attention_mask += padding token_type_ids += padding return np.array(input_ids), np.array(attention_mask), np.array(token_type_ids) @register_plugin",
"0.0\".format(lr)) if schedule not in SCHEDULES: raise ValueError(\"Invalid schedule parameter: {}\".format(schedule)) if not",
"/ warmup return 1.0 - x SCHEDULES = { 'warmup_cosine': warmup_cosine, 'warmup_constant': warmup_constant,",
"from transfer_nlp.loaders.vocabulary import Vocabulary from transfer_nlp.plugins.config import register_plugin tqdm.pandas() @register_plugin class BertVectorizer(Vectorizer): def",
"SGD. if group['weight_decay'] > 0.0: update += group['weight_decay'] * p.data if group['t_total'] !=",
"# Optimizer Code from HuggingFace repo def warmup_cosine(x, warmup=0.002): if x < warmup:",
"def __init__(self, data_file: str, batch_size: int, vectorizer: Vectorizer): self.df = pd.read_csv(data_file) np.random.shuffle(self.df.values) #",
"BertForSequenceClassification from torch.nn.utils import clip_grad_norm_ from torch.optim import Optimizer from torch.optim.optimizer import required",
"[\"[CLS]\"] + tokens + [\"[SEP]\"] token_type_ids = [0] * len(tokens) input_ids = self.tokenizer.convert_tokens_to_ids(tokens)",
"super().__init__(data_file=data_file) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') df = pd.read_csv(data_file) target_vocab = Vocabulary(add_unk=False) for category in",
"Adams b2. Default: 0.999 e: Adams epsilon. Default: 1e-6 weight_decay: Weight decay. Default:",
"= self.state[p] # State initialization if len(state) == 0: state['step'] = 0 #",
"values state['next_m'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['next_v']",
"pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification from torch.nn.utils import clip_grad_norm_ from torch.optim import Optimizer from",
"1.0 - x SCHEDULES = { 'warmup_cosine': warmup_cosine, 'warmup_constant': warmup_constant, 'warmup_linear': warmup_linear, }",
"torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['next_v'] = torch.zeros_like(p.data) next_m,",
"square of the weights to the loss function is *not* # the correct",
"be >= 0.0\".format(lr)) if schedule not in SCHEDULES: raise ValueError(\"Invalid schedule parameter: {}\".format(schedule))",
"return x / warmup return 0.5 * (1.0 + torch.cos(math.pi * x)) def",
"'warmup_linear' b1: Adams b1. Default: 0.9 b2: Adams b2. Default: 0.999 e: Adams",
"lr is not required and lr < 0.0: raise ValueError(\"Invalid learning rate: {}",
"reevaluates the model and returns the loss. \"\"\" loss = None if closure",
"initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of",
"data_file: str, batch_size: int, vectorizer: Vectorizer): self.df = pd.read_csv(data_file) np.random.shuffle(self.df.values) # Use this",
"None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not support sparse",
"b2 < 1.0: raise ValueError(\"Invalid b2 parameter: {} - should be in [0.0,",
"def warmup_linear(x, warmup=0.002): if x < warmup: return x / warmup return 1.0",
"warmup: {} - should be in [0.0, 1.0[ or -1\".format(warmup)) if not 0.0",
"* update p.data.add_(-update_with_lr) state['step'] += 1 # step_size = lr_scheduled * math.sqrt(bias_correction2) /",
"int, vectorizer: Vectorizer): self.df = pd.read_csv(data_file) np.random.shuffle(self.df.values) # Use this code in dev",
"{} - should be in [0.0, 1.0[\".format(b2)) if not e >= 0.0: raise",
"transfer_nlp.loaders.vectorizers import Vectorizer from transfer_nlp.loaders.vocabulary import Vocabulary from transfer_nlp.plugins.config import register_plugin tqdm.pandas() @register_plugin",
"of squared gradient values state['next_v'] = torch.zeros_like(p.data) next_m, next_v = state['next_m'], state['next_v'] beta1,",
"be in [0.0, 1.0[ or -1\".format(warmup)) if not 0.0 <= b1 < 1.0:",
"x[2]) self.df['y_target'] = self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x)) train_df = self.df[self.df.split == 'train'][['input_ids', 'attention_mask', 'token_type_ids',",
"use for the warmup (see above). Default: 'warmup_linear' b1: Adams b1. Default: 0.9",
"lr.append(lr_scheduled) return lr def step(self, closure=None): \"\"\"Performs a single optimization step. Arguments: closure",
"beta2, grad, grad) update = next_m / (next_v.sqrt() + group['e']) # Just adding",
"vectorize(self, title: str, max_seq_length: int) -> Tuple[np.array, np.array, np.array]: tokens = self.tokenizer.tokenize(title) tokens",
"== 'val'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] test_df = self.df[self.df.split == 'test'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']]",
"import Vocabulary from transfer_nlp.plugins.config import register_plugin tqdm.pandas() @register_plugin class BertVectorizer(Vectorizer): def __init__(self, data_file:",
"padding token_type_ids += padding return np.array(input_ids), np.array(attention_mask), np.array(token_type_ids) @register_plugin class BertDataset(DatasetSplits): def __init__(self,",
"import BertTokenizer, BertForSequenceClassification from torch.nn.utils import clip_grad_norm_ from torch.optim import Optimizer from torch.optim.optimizer",
"* (1.0 + torch.cos(math.pi * x)) def warmup_constant(x, warmup=0.002): if x < warmup:",
"[0.0, 1.0[\".format(b1)) if not 0.0 <= b2 < 1.0: raise ValueError(\"Invalid b2 parameter:",
"group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] update_with_lr = lr_scheduled",
"1.0: raise ValueError(\"Invalid b1 parameter: {} - should be in [0.0, 1.0[\".format(b1)) if",
"warmup return 0.5 * (1.0 + torch.cos(math.pi * x)) def warmup_constant(x, warmup=0.002): if",
"warmup=0.002): if x < warmup: return x / warmup return 1.0 def warmup_linear(x,",
"category in sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab = target_vocab def vectorize(self, title: str, max_seq_length: int)",
"and not warmup == -1: raise ValueError(\"Invalid warmup: {} - should be in",
"import clip_grad_norm_ from torch.optim import Optimizer from torch.optim.optimizer import required from tqdm import",
"second moment running average coefficient # In-place operations to update the averages at",
"gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state)",
"Just adding the square of the weights to the loss function is *not*",
"in [0.0, 1.0[\".format(b1)) if not 0.0 <= b2 < 1.0: raise ValueError(\"Invalid b2",
">= 0.0: raise ValueError(\"Invalid epsilon value: {} - should be >= 0.0\".format(e)) defaults",
"warmup: portion of t_total for the warmup, -1 means no warmup. Default: -1",
"token_type_ids = [0] * len(tokens) input_ids = self.tokenizer.convert_tokens_to_ids(tokens) attention_mask = [1] * len(input_ids)",
"len(input_ids)) input_ids += padding attention_mask += padding token_type_ids += padding return np.array(input_ids), np.array(attention_mask),",
"'attention_mask', 'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin def bert_model(): return",
"Weight decay. Default: 0.01 max_grad_norm: Maximum norm for the gradients (-1 means no",
"= torch.zeros_like(p.data) next_m, next_v = state['next_m'], state['next_v'] beta1, beta2 = group['b1'], group['b2'] #",
"< warmup: return x / warmup return 1.0 def warmup_linear(x, warmup=0.002): if x",
"group['warmup']) else: lr_scheduled = group['lr'] update_with_lr = lr_scheduled * update p.data.add_(-update_with_lr) state['step'] +=",
"x < warmup: return x / warmup return 0.5 * (1.0 + torch.cos(math.pi",
"x)) def warmup_constant(x, warmup=0.002): if x < warmup: return x / warmup return",
"to use for the warmup (see above). Default: 'warmup_linear' b1: Adams b1. Default:",
"{} - should be in [0.0, 1.0[ or -1\".format(warmup)) if not 0.0 <=",
"0.0 <= b2 < 1.0: raise ValueError(\"Invalid b2 parameter: {} - should be",
"1.0: raise ValueError(\"Invalid b2 parameter: {} - should be in [0.0, 1.0[\".format(b2)) if",
"if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step'] /",
"def step(self, closure=None): \"\"\"Performs a single optimization step. Arguments: closure (callable, optional): A",
"RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead') state = self.state[p]",
"parameter: {} - should be in [0.0, 1.0[\".format(b1)) if not 0.0 <= b2",
"in tqdm(self.df.title, desc=\"Getting max sequence\"): tokens = self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence = max(self.max_sequence, len(tokens)) self.max_sequence",
"means no clipping). Default: 1.0 \"\"\" def __init__(self, params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear',",
"self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data",
"BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) # Optimizer Code from HuggingFace repo def warmup_cosine(x, warmup=0.002): if x",
"portion of t_total for the warmup, -1 means no warmup. Default: -1 t_total:",
"__init__(self, data_file: str, batch_size: int, vectorizer: Vectorizer): self.df = pd.read_csv(data_file) np.random.shuffle(self.df.values) # Use",
"from HuggingFace repo def warmup_cosine(x, warmup=0.002): if x < warmup: return x /",
"b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0): if lr is not required and lr < 0.0:",
"with plain (non-momentum) SGD. if group['weight_decay'] > 0.0: update += group['weight_decay'] * p.data",
"correction # bias_correction1 = 1 - beta1 ** state['step'] # bias_correction2 = 1",
"def warmup_constant(x, warmup=0.002): if x < warmup: return x / warmup return 1.0",
"import Tuple import numpy as np import pandas as pd import torch from",
"t_total for the warmup, -1 means no warmup. Default: -1 t_total: total number",
"lr_scheduled = group['lr'] update_with_lr = lr_scheduled * update p.data.add_(-update_with_lr) state['step'] += 1 #",
"math.sqrt(bias_correction2) / bias_correction1 # No bias correction # bias_correction1 = 1 - beta1",
"import Optimizer from torch.optim.optimizer import required from tqdm import tqdm from transfer_nlp.loaders.loaders import",
"in SCHEDULES: raise ValueError(\"Invalid schedule parameter: {}\".format(schedule)) if not 0.0 <= warmup <",
"equivalent to adding the square # of the weights to the loss with",
"x: x[1]) self.df['token_type_ids'] = vectors.progress_apply(lambda x: x[2]) self.df['y_target'] = self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x)) train_df",
"= [1] * len(input_ids) padding = [0] * (max_seq_length - len(input_ids)) input_ids +=",
"vectors.progress_apply(lambda x: x[2]) self.df['y_target'] = self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x)) train_df = self.df[self.df.split == 'train'][['input_ids',",
"max sequence\"): tokens = self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence = max(self.max_sequence, len(tokens)) self.max_sequence += 2 vectors",
"not 0.0 <= b1 < 1.0: raise ValueError(\"Invalid b1 parameter: {} - should",
"torch.nn.utils import clip_grad_norm_ from torch.optim import Optimizer from torch.optim.optimizer import required from tqdm",
"should be in [0.0, 1.0[\".format(b1)) if not 0.0 <= b2 < 1.0: raise",
"= 1000 self.df = self.df.head(n=N) # preprocessing self.vectorizer: Vectorizer = vectorizer self.max_sequence =",
"def bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) # Optimizer Code from HuggingFace repo def warmup_cosine(x,",
"pd.read_csv(data_file) np.random.shuffle(self.df.values) # Use this code in dev mode N = 1000 self.df",
"Vocabulary from transfer_nlp.plugins.config import register_plugin tqdm.pandas() @register_plugin class BertVectorizer(Vectorizer): def __init__(self, data_file: str):",
"steps for the learning rate schedule, -1 means constant learning rate. Default: -1",
"tqdm from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.vectorizers import Vectorizer from transfer_nlp.loaders.vocabulary import",
"target_vocab = Vocabulary(add_unk=False) for category in sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab = target_vocab def vectorize(self,",
"self.tokenizer.convert_tokens_to_ids(tokens) attention_mask = [1] * len(input_ids) padding = [0] * (max_seq_length - len(input_ids))",
"= group['lr'] lr.append(lr_scheduled) return lr def step(self, closure=None): \"\"\"Performs a single optimization step.",
"the averages at the same time next_m.mul_(beta1).add_(1 - beta1, grad) next_v.mul_(beta2).addcmul_(1 - beta2,",
"str): super().__init__(data_file=data_file) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') df = pd.read_csv(data_file) target_vocab = Vocabulary(add_unk=False) for category",
"warmup: return x / warmup return 1.0 def warmup_linear(x, warmup=0.002): if x <",
"not warmup == -1: raise ValueError(\"Invalid warmup: {} - should be in [0.0,",
"Optimizer Code from HuggingFace repo def warmup_cosine(x, warmup=0.002): if x < warmup: return",
"# the correct way of using L2 regularization/weight decay with Adam, # since",
"self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential",
"warmup, -1 means no warmup. Default: -1 t_total: total number of training steps",
"{}\".format(schedule)) if not 0.0 <= warmup < 1.0 and not warmup == -1:",
"In-place operations to update the averages at the same time next_m.mul_(beta1).add_(1 - beta1,",
"No bias correction # bias_correction1 = 1 - beta1 ** state['step'] # bias_correction2",
"p in group['params']: state = self.state[p] if len(state) == 0: return [0] if",
"the same time next_m.mul_(beta1).add_(1 - beta1, grad) next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad) update",
"beta1, beta2 = group['b1'], group['b2'] # Add grad clipping if group['max_grad_norm'] > 0:",
"< 1.0: raise ValueError(\"Invalid b1 parameter: {} - should be in [0.0, 1.0[\".format(b1))",
"Vectorizer): self.df = pd.read_csv(data_file) np.random.shuffle(self.df.values) # Use this code in dev mode N",
"Decay the first and second moment running average coefficient # In-place operations to",
"we want to decay the weights in a manner that doesn't interact #",
"transfer_nlp.plugins.config import register_plugin tqdm.pandas() @register_plugin class BertVectorizer(Vectorizer): def __init__(self, data_file: str): super().__init__(data_file=data_file) self.tokenizer",
"warmup return 1.0 def warmup_linear(x, warmup=0.002): if x < warmup: return x /",
"group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step'] / group['t_total'],",
"self.vectorizer: Vectorizer = vectorizer self.max_sequence = 0 for title in tqdm(self.df.title, desc=\"Getting max",
"parameter: {} - should be in [0.0, 1.0[\".format(b2)) if not e >= 0.0:",
"in [0.0, 1.0[ or -1\".format(warmup)) if not 0.0 <= b1 < 1.0: raise",
"def warmup_cosine(x, warmup=0.002): if x < warmup: return x / warmup return 0.5",
"warmup. Default: -1 t_total: total number of training steps for the learning rate",
"in self.param_groups: for p in group['params']: state = self.state[p] if len(state) == 0:",
"self.df['input_ids'] = vectors.progress_apply(lambda x: x[0]) self.df['attention_mask'] = vectors.progress_apply(lambda x: x[1]) self.df['token_type_ids'] = vectors.progress_apply(lambda",
"average of squared gradient values state['next_v'] = torch.zeros_like(p.data) next_m, next_v = state['next_m'], state['next_v']",
"at the same time next_m.mul_(beta1).add_(1 - beta1, grad) next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad)",
"next_m / (next_v.sqrt() + group['e']) # Just adding the square of the weights",
"= group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] update_with_lr =",
"< warmup: return x / warmup return 0.5 * (1.0 + torch.cos(math.pi *",
"Default: 0.01 max_grad_norm: Maximum norm for the gradients (-1 means no clipping). Default:",
"group['lr'] update_with_lr = lr_scheduled * update p.data.add_(-update_with_lr) state['step'] += 1 # step_size =",
"val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin def bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) # Optimizer Code",
"average of gradient values state['next_m'] = torch.zeros_like(p.data) # Exponential moving average of squared",
"if len(state) == 0: return [0] if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']]",
"[\"[SEP]\"] token_type_ids = [0] * len(tokens) input_ids = self.tokenizer.convert_tokens_to_ids(tokens) attention_mask = [1] *",
"x[1]) self.df['token_type_ids'] = vectors.progress_apply(lambda x: x[2]) self.df['y_target'] = self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x)) train_df =",
"grad, grad) update = next_m / (next_v.sqrt() + group['e']) # Just adding the",
"else: lr_scheduled = group['lr'] update_with_lr = lr_scheduled * update p.data.add_(-update_with_lr) state['step'] += 1",
"HuggingFace repo def warmup_cosine(x, warmup=0.002): if x < warmup: return x / warmup",
"- should be >= 0.0\".format(e)) defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, b1=b1, b2=b2,",
"0.0: update += group['weight_decay'] * p.data if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']]",
"Use this code in dev mode N = 1000 self.df = self.df.head(n=N) #",
"adding the square # of the weights to the loss with plain (non-momentum)",
"weight decay fix. Params: lr: learning rate warmup: portion of t_total for the",
"title in tqdm(self.df.title, desc=\"Getting max sequence\"): tokens = self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence = max(self.max_sequence, len(tokens))",
"if x < warmup: return x / warmup return 0.5 * (1.0 +",
"group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] update_with_lr = lr_scheduled * update p.data.add_(-update_with_lr) state['step']",
"- x SCHEDULES = { 'warmup_cosine': warmup_cosine, 'warmup_constant': warmup_constant, 'warmup_linear': warmup_linear, } @register_plugin",
"if not 0.0 <= b1 < 1.0: raise ValueError(\"Invalid b1 parameter: {} -",
"to adding the square # of the weights to the loss with plain",
"interact # with the m/v parameters. This is equivalent to adding the square",
"be in [0.0, 1.0[\".format(b2)) if not e >= 0.0: raise ValueError(\"Invalid epsilon value:",
"training steps for the learning rate schedule, -1 means constant learning rate. Default:",
"Instead we want to decay the weights in a manner that doesn't interact",
"number of training steps for the learning rate schedule, -1 means constant learning",
"next_m.mul_(beta1).add_(1 - beta1, grad) next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad) update = next_m /",
"is *not* # the correct way of using L2 regularization/weight decay with Adam,",
"for the warmup, -1 means no warmup. Default: -1 t_total: total number of",
"gradient values state['next_m'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values",
"= torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['next_v'] = torch.zeros_like(p.data)",
"b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0): if lr is not required and lr <",
"self.df['attention_mask'] = vectors.progress_apply(lambda x: x[1]) self.df['token_type_ids'] = vectors.progress_apply(lambda x: x[2]) self.df['y_target'] = self.df['category'].progress_apply(lambda",
"continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients,",
"x: self.vectorizer.target_vocab.lookup_token(x)) train_df = self.df[self.df.split == 'train'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] val_df = self.df[self.df.split",
"- should be in [0.0, 1.0[ or -1\".format(warmup)) if not 0.0 <= b1",
"/ group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] update_with_lr = lr_scheduled * update p.data.add_(-update_with_lr)",
"square # of the weights to the loss with plain (non-momentum) SGD. if",
"* (max_seq_length - len(input_ids)) input_ids += padding attention_mask += padding token_type_ids += padding",
"lr_scheduled = group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] update_with_lr",
"clip_grad_norm_ from torch.optim import Optimizer from torch.optim.optimizer import required from tqdm import tqdm",
"sequence\"): tokens = self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence = max(self.max_sequence, len(tokens)) self.max_sequence += 2 vectors =",
"with the m and v parameters in strange ways. # # Instead we",
"+= group['weight_decay'] * p.data if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled =",
"closure() for group in self.param_groups: for p in group['params']: if p.grad is None:",
"self.max_sequence = 0 for title in tqdm(self.df.title, desc=\"Getting max sequence\"): tokens = self.vectorizer.tokenizer.tokenize(text=title)",
"loss = None if closure is not None: loss = closure() for group",
"update = next_m / (next_v.sqrt() + group['e']) # Just adding the square of",
"function is *not* # the correct way of using L2 regularization/weight decay with",
"lr < 0.0: raise ValueError(\"Invalid learning rate: {} - should be >= 0.0\".format(lr))",
"optional): A closure that reevaluates the model and returns the loss. \"\"\" loss",
"pd.read_csv(data_file) target_vocab = Vocabulary(add_unk=False) for category in sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab = target_vocab def",
"step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns",
"the gradients (-1 means no clipping). Default: 1.0 \"\"\" def __init__(self, params, lr=required,",
"import required from tqdm import tqdm from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.vectorizers",
"0: state['step'] = 0 # Exponential moving average of gradient values state['next_m'] =",
"please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) ==",
"max_grad_norm: Maximum norm for the gradients (-1 means no clipping). Default: 1.0 \"\"\"",
"np.random.shuffle(self.df.values) # Use this code in dev mode N = 1000 self.df =",
"v parameters in strange ways. # # Instead we want to decay the",
"df = pd.read_csv(data_file) target_vocab = Vocabulary(add_unk=False) for category in sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab =",
"<= b1 < 1.0: raise ValueError(\"Invalid b1 parameter: {} - should be in",
"__init__(self, params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0): if lr",
"adding the square of the weights to the loss function is *not* #",
"'token_type_ids', 'y_target']] val_df = self.df[self.df.split == 'val'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] test_df = self.df[self.df.split",
"token_type_ids += padding return np.array(input_ids), np.array(attention_mask), np.array(token_type_ids) @register_plugin class BertDataset(DatasetSplits): def __init__(self, data_file:",
"Adam algorithm with weight decay fix. Params: lr: learning rate warmup: portion of",
"\"\"\" def __init__(self, params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0):",
"= vectors.progress_apply(lambda x: x[0]) self.df['attention_mask'] = vectors.progress_apply(lambda x: x[1]) self.df['token_type_ids'] = vectors.progress_apply(lambda x:",
"not 0.0 <= b2 < 1.0: raise ValueError(\"Invalid b2 parameter: {} - should",
"required and lr < 0.0: raise ValueError(\"Invalid learning rate: {} - should be",
"warmup (see above). Default: 'warmup_linear' b1: Adams b1. Default: 0.9 b2: Adams b2.",
"warmup == -1: raise ValueError(\"Invalid warmup: {} - should be in [0.0, 1.0[",
"p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse:",
"beta1, grad) next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad) update = next_m / (next_v.sqrt() +",
"raise ValueError(\"Invalid b2 parameter: {} - should be in [0.0, 1.0[\".format(b2)) if not",
"average coefficient # In-place operations to update the averages at the same time",
"- beta1, grad) next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad) update = next_m / (next_v.sqrt()",
"in dev mode N = 1000 self.df = self.df.head(n=N) # preprocessing self.vectorizer: Vectorizer",
"0.0: raise ValueError(\"Invalid learning rate: {} - should be >= 0.0\".format(lr)) if schedule",
"ValueError(\"Invalid warmup: {} - should be in [0.0, 1.0[ or -1\".format(warmup)) if not",
"State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average",
"= vectorizer self.max_sequence = 0 for title in tqdm(self.df.title, desc=\"Getting max sequence\"): tokens",
"= group['b1'], group['b2'] # Add grad clipping if group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm'])",
"update_with_lr = lr_scheduled * update p.data.add_(-update_with_lr) state['step'] += 1 # step_size = lr_scheduled",
"\"\"\"Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates",
"input_ids += padding attention_mask += padding token_type_ids += padding return np.array(input_ids), np.array(attention_mask), np.array(token_type_ids)",
"{} - should be >= 0.0\".format(lr)) if schedule not in SCHEDULES: raise ValueError(\"Invalid",
"be >= 0.0\".format(e)) defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, b1=b1, b2=b2, e=e, weight_decay=weight_decay,",
"defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, b1=b1, b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params,",
"class BertDataset(DatasetSplits): def __init__(self, data_file: str, batch_size: int, vectorizer: Vectorizer): self.df = pd.read_csv(data_file)",
"in group['params']: state = self.state[p] if len(state) == 0: return [0] if group['t_total']",
"'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin def bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4)",
"ValueError(\"Invalid epsilon value: {} - should be >= 0.0\".format(e)) defaults = dict(lr=lr, schedule=schedule,",
"warmup=0.002): if x < warmup: return x / warmup return 1.0 - x",
"*not* # the correct way of using L2 regularization/weight decay with Adam, #",
"0: return [0] if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = group['lr']",
"import register_plugin tqdm.pandas() @register_plugin class BertVectorizer(Vectorizer): def __init__(self, data_file: str): super().__init__(data_file=data_file) self.tokenizer =",
"np.array(input_ids), np.array(attention_mask), np.array(token_type_ids) @register_plugin class BertDataset(DatasetSplits): def __init__(self, data_file: str, batch_size: int, vectorizer:",
"in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise",
"e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults) def get_lr(self): lr = [] for group",
"warmup_linear(x, warmup=0.002): if x < warmup: return x / warmup return 1.0 -",
"should be >= 0.0\".format(lr)) if schedule not in SCHEDULES: raise ValueError(\"Invalid schedule parameter:",
"ValueError(\"Invalid b2 parameter: {} - should be in [0.0, 1.0[\".format(b2)) if not e",
"= self.state[p] if len(state) == 0: return [0] if group['t_total'] != -1: schedule_fct",
"DatasetSplits, DataFrameDataset from transfer_nlp.loaders.vectorizers import Vectorizer from transfer_nlp.loaders.vocabulary import Vocabulary from transfer_nlp.plugins.config import",
"the loss. \"\"\" loss = None if closure is not None: loss =",
"numpy as np import pandas as pd import torch from pytorch_pretrained_bert import BertTokenizer,",
"= [0] * (max_seq_length - len(input_ids)) input_ids += padding attention_mask += padding token_type_ids",
"to decay the weights in a manner that doesn't interact # with the",
"group in self.param_groups: for p in group['params']: if p.grad is None: continue grad",
"data_file: str): super().__init__(data_file=data_file) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') df = pd.read_csv(data_file) target_vocab = Vocabulary(add_unk=False) for",
"b1 parameter: {} - should be in [0.0, 1.0[\".format(b1)) if not 0.0 <=",
"way of using L2 regularization/weight decay with Adam, # since that will interact",
"= self.df[self.df.split == 'train'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] val_df = self.df[self.df.split == 'val'][['input_ids', 'attention_mask',",
"* x)) def warmup_constant(x, warmup=0.002): if x < warmup: return x / warmup",
"This is equivalent to adding the square # of the weights to the",
"transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.vectorizers import Vectorizer from transfer_nlp.loaders.vocabulary import Vocabulary from",
"np import pandas as pd import torch from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification from",
"BertTokenizer, BertForSequenceClassification from torch.nn.utils import clip_grad_norm_ from torch.optim import Optimizer from torch.optim.optimizer import",
"group in self.param_groups: for p in group['params']: state = self.state[p] if len(state) ==",
"= self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence = max(self.max_sequence, len(tokens)) self.max_sequence += 2 vectors = self.df['title'].progress_apply(lambda x:",
"< 0.0: raise ValueError(\"Invalid learning rate: {} - should be >= 0.0\".format(lr)) if",
"t_total: total number of training steps for the learning rate schedule, -1 means",
"next_m, next_v = state['next_m'], state['next_v'] beta1, beta2 = group['b1'], group['b2'] # Add grad",
"target_vocab.add_token(category) self.target_vocab = target_vocab def vectorize(self, title: str, max_seq_length: int) -> Tuple[np.array, np.array,",
"in [0.0, 1.0[\".format(b2)) if not e >= 0.0: raise ValueError(\"Invalid epsilon value: {}",
"state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0",
"value: {} - should be >= 0.0\".format(e)) defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total,",
"SCHEDULES = { 'warmup_cosine': warmup_cosine, 'warmup_constant': warmup_constant, 'warmup_linear': warmup_linear, } @register_plugin class BertAdam(Optimizer):",
"A closure that reevaluates the model and returns the loss. \"\"\" loss =",
"not None: loss = closure() for group in self.param_groups: for p in group['params']:",
"1.0[\".format(b1)) if not 0.0 <= b2 < 1.0: raise ValueError(\"Invalid b2 parameter: {}",
"x < warmup: return x / warmup return 1.0 def warmup_linear(x, warmup=0.002): if",
"return lr def step(self, closure=None): \"\"\"Performs a single optimization step. Arguments: closure (callable,",
"the learning rate schedule, -1 means constant learning rate. Default: -1 schedule: schedule",
"Exponential moving average of squared gradient values state['next_v'] = torch.zeros_like(p.data) next_m, next_v =",
"@register_plugin class BertAdam(Optimizer): \"\"\"Implements BERT version of Adam algorithm with weight decay fix.",
"len(tokens)) self.max_sequence += 2 vectors = self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids'] = vectors.progress_apply(lambda",
"decay with Adam, # since that will interact with the m and v",
"= pd.read_csv(data_file) target_vocab = Vocabulary(add_unk=False) for category in sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab = target_vocab",
"bias_correction1 # No bias correction # bias_correction1 = 1 - beta1 ** state['step']",
"parameters in strange ways. # # Instead we want to decay the weights",
"[0] * (max_seq_length - len(input_ids)) input_ids += padding attention_mask += padding token_type_ids +=",
"{} - should be in [0.0, 1.0[\".format(b1)) if not 0.0 <= b2 <",
"- beta1 ** state['step'] # bias_correction2 = 1 - beta2 ** state['step'] return",
"sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if",
"the m and v parameters in strange ways. # # Instead we want",
"lr = [] for group in self.param_groups: for p in group['params']: state =",
"/ warmup return 0.5 * (1.0 + torch.cos(math.pi * x)) def warmup_constant(x, warmup=0.002):",
"\"\"\"Implements BERT version of Adam algorithm with weight decay fix. Params: lr: learning",
"[1] * len(input_ids) padding = [0] * (max_seq_length - len(input_ids)) input_ids += padding",
"test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin def bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) # Optimizer Code from HuggingFace",
"e: Adams epsilon. Default: 1e-6 weight_decay: Weight decay. Default: 0.01 max_grad_norm: Maximum norm",
"t_total=-1, schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0): if lr is not required and",
"title: str, max_seq_length: int) -> Tuple[np.array, np.array, np.array]: tokens = self.tokenizer.tokenize(title) tokens =",
"doesn't interact # with the m/v parameters. This is equivalent to adding the",
"learning rate schedule, -1 means constant learning rate. Default: -1 schedule: schedule to",
"/ warmup return 1.0 def warmup_linear(x, warmup=0.002): if x < warmup: return x",
"(-1 means no clipping). Default: 1.0 \"\"\" def __init__(self, params, lr=required, warmup=-1, t_total=-1,",
"* schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] update_with_lr = lr_scheduled *",
"1000 self.df = self.df.head(n=N) # preprocessing self.vectorizer: Vectorizer = vectorizer self.max_sequence = 0",
"len(state) == 0: return [0] if group['t_total'] != -1: schedule_fct = SCHEDULES[group['schedule']] lr_scheduled",
"val_df = self.df[self.df.split == 'val'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] test_df = self.df[self.df.split == 'test'][['input_ids',",
"the warmup (see above). Default: 'warmup_linear' b1: Adams b1. Default: 0.9 b2: Adams",
"raise ValueError(\"Invalid b1 parameter: {} - should be in [0.0, 1.0[\".format(b1)) if not",
"group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] lr.append(lr_scheduled) return lr def step(self, closure=None): \"\"\"Performs",
"state['next_v'] beta1, beta2 = group['b1'], group['b2'] # Add grad clipping if group['max_grad_norm'] >",
"time next_m.mul_(beta1).add_(1 - beta1, grad) next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad) update = next_m",
"x[0]) self.df['attention_mask'] = vectors.progress_apply(lambda x: x[1]) self.df['token_type_ids'] = vectors.progress_apply(lambda x: x[2]) self.df['y_target'] =",
"/ (next_v.sqrt() + group['e']) # Just adding the square of the weights to",
"- beta2, grad, grad) update = next_m / (next_v.sqrt() + group['e']) # Just",
"self.df[self.df.split == 'train'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] val_df = self.df[self.df.split == 'val'][['input_ids', 'attention_mask', 'token_type_ids',",
"the weights to the loss function is *not* # the correct way of",
"* len(tokens) input_ids = self.tokenizer.convert_tokens_to_ids(tokens) attention_mask = [1] * len(input_ids) padding = [0]",
"first and second moment running average coefficient # In-place operations to update the",
"Default: 0.9 b2: Adams b2. Default: 0.999 e: Adams epsilon. Default: 1e-6 weight_decay:",
"dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, b1=b1, b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults) def",
"defaults) def get_lr(self): lr = [] for group in self.param_groups: for p in",
"b1 < 1.0: raise ValueError(\"Invalid b1 parameter: {} - should be in [0.0,",
"BERT version of Adam algorithm with weight decay fix. Params: lr: learning rate",
"should be in [0.0, 1.0[\".format(b2)) if not e >= 0.0: raise ValueError(\"Invalid epsilon",
"* len(input_ids) padding = [0] * (max_seq_length - len(input_ids)) input_ids += padding attention_mask",
"the warmup, -1 means no warmup. Default: -1 t_total: total number of training",
"b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults) def get_lr(self): lr = [] for",
"<reponame>0xflotus/transfer-nlp import math from typing import Tuple import numpy as np import pandas",
"schedule parameter: {}\".format(schedule)) if not 0.0 <= warmup < 1.0 and not warmup",
"the weights in a manner that doesn't interact # with the m/v parameters.",
"schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] update_with_lr = lr_scheduled * update",
"# of the weights to the loss with plain (non-momentum) SGD. if group['weight_decay']",
"lr_scheduled = group['lr'] lr.append(lr_scheduled) return lr def step(self, closure=None): \"\"\"Performs a single optimization",
"closure is not None: loss = closure() for group in self.param_groups: for p",
"group['e']) # Just adding the square of the weights to the loss function",
"lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 # No bias correction # bias_correction1 = 1",
"from tqdm import tqdm from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.vectorizers import Vectorizer",
"= 0 # Exponential moving average of gradient values state['next_m'] = torch.zeros_like(p.data) #",
"= dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, b1=b1, b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults)",
"@register_plugin class BertVectorizer(Vectorizer): def __init__(self, data_file: str): super().__init__(data_file=data_file) self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') df =",
"SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: state['step']",
"train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size) @register_plugin def bert_model(): return BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=4) # Optimizer",
"= { 'warmup_cosine': warmup_cosine, 'warmup_constant': warmup_constant, 'warmup_linear': warmup_linear, } @register_plugin class BertAdam(Optimizer): \"\"\"Implements",
"max(self.max_sequence, len(tokens)) self.max_sequence += 2 vectors = self.df['title'].progress_apply(lambda x: self.vectorizer.vectorize(title=x, max_seq_length=self.max_sequence)) self.df['input_ids'] =",
"to the loss function is *not* # the correct way of using L2",
"pd import torch from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification from torch.nn.utils import clip_grad_norm_ from",
"test_df = self.df[self.df.split == 'test'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df),",
"Default: 'warmup_linear' b1: Adams b1. Default: 0.9 b2: Adams b2. Default: 0.999 e:",
"= target_vocab def vectorize(self, title: str, max_seq_length: int) -> Tuple[np.array, np.array, np.array]: tokens",
"Params: lr: learning rate warmup: portion of t_total for the warmup, -1 means",
"def __init__(self, params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0): if",
"and lr < 0.0: raise ValueError(\"Invalid learning rate: {} - should be >=",
"Vocabulary(add_unk=False) for category in sorted(set(df.category)): target_vocab.add_token(category) self.target_vocab = target_vocab def vectorize(self, title: str,",
"tokens + [\"[SEP]\"] token_type_ids = [0] * len(tokens) input_ids = self.tokenizer.convert_tokens_to_ids(tokens) attention_mask =",
"in self.param_groups: for p in group['params']: if p.grad is None: continue grad =",
"lr=required, warmup=-1, t_total=-1, schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0): if lr is not",
"Adams b1. Default: 0.9 b2: Adams b2. Default: 0.999 e: Adams epsilon. Default:",
"fix. Params: lr: learning rate warmup: portion of t_total for the warmup, -1",
"= state['next_m'], state['next_v'] beta1, beta2 = group['b1'], group['b2'] # Add grad clipping if",
"SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr']",
"self.df['y_target'] = self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x)) train_df = self.df[self.df.split == 'train'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']]",
"x / warmup return 1.0 - x SCHEDULES = { 'warmup_cosine': warmup_cosine, 'warmup_constant':",
"[0] * len(tokens) input_ids = self.tokenizer.convert_tokens_to_ids(tokens) attention_mask = [1] * len(input_ids) padding =",
"<= b2 < 1.0: raise ValueError(\"Invalid b2 parameter: {} - should be in",
"repo def warmup_cosine(x, warmup=0.002): if x < warmup: return x / warmup return",
"int) -> Tuple[np.array, np.array, np.array]: tokens = self.tokenizer.tokenize(title) tokens = [\"[CLS]\"] + tokens",
"0 for title in tqdm(self.df.title, desc=\"Getting max sequence\"): tokens = self.vectorizer.tokenizer.tokenize(text=title) self.max_sequence =",
"self.df[self.df.split == 'val'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] test_df = self.df[self.df.split == 'test'][['input_ids', 'attention_mask', 'token_type_ids',",
"1.0[ or -1\".format(warmup)) if not 0.0 <= b1 < 1.0: raise ValueError(\"Invalid b1",
"'token_type_ids', 'y_target']] test_df = self.df[self.df.split == 'test'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df),",
"not required and lr < 0.0: raise ValueError(\"Invalid learning rate: {} - should",
"= SCHEDULES[group['schedule']] lr_scheduled = group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled =",
"lr_scheduled * update p.data.add_(-update_with_lr) state['step'] += 1 # step_size = lr_scheduled * math.sqrt(bias_correction2)",
"regularization/weight decay with Adam, # since that will interact with the m and",
"torch from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification from torch.nn.utils import clip_grad_norm_ from torch.optim import",
"torch.optim.optimizer import required from tqdm import tqdm from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from",
"x: x[2]) self.df['y_target'] = self.df['category'].progress_apply(lambda x: self.vectorizer.target_vocab.lookup_token(x)) train_df = self.df[self.df.split == 'train'][['input_ids', 'attention_mask',",
"train_df = self.df[self.df.split == 'train'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] val_df = self.df[self.df.split == 'val'][['input_ids',",
"of training steps for the learning rate schedule, -1 means constant learning rate.",
"Vectorizer = vectorizer self.max_sequence = 0 for title in tqdm(self.df.title, desc=\"Getting max sequence\"):",
"warmup_linear, } @register_plugin class BertAdam(Optimizer): \"\"\"Implements BERT version of Adam algorithm with weight",
"warmup < 1.0 and not warmup == -1: raise ValueError(\"Invalid warmup: {} -",
"= lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 # No bias correction # bias_correction1 =",
"a manner that doesn't interact # with the m/v parameters. This is equivalent",
"is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not support",
"schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0): if lr is not required and lr",
"{} - should be >= 0.0\".format(e)) defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, b1=b1,",
"- should be >= 0.0\".format(lr)) if schedule not in SCHEDULES: raise ValueError(\"Invalid schedule",
"moving average of squared gradient values state['next_v'] = torch.zeros_like(p.data) next_m, next_v = state['next_m'],",
"= [] for group in self.param_groups: for p in group['params']: state = self.state[p]",
"will interact with the m and v parameters in strange ways. # #",
"# Add grad clipping if group['max_grad_norm'] > 0: clip_grad_norm_(p, group['max_grad_norm']) # Decay the",
"import pandas as pd import torch from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification from torch.nn.utils",
"lr_scheduled = group['lr'] * schedule_fct(state['step'] / group['t_total'], group['warmup']) else: lr_scheduled = group['lr'] lr.append(lr_scheduled)",
"1e-6 weight_decay: Weight decay. Default: 0.01 max_grad_norm: Maximum norm for the gradients (-1",
"= self.df[self.df.split == 'test'][['input_ids', 'attention_mask', 'token_type_ids', 'y_target']] super().__init__(train_set=DataFrameDataset(train_df), train_batch_size=batch_size, val_set=DataFrameDataset(val_df), val_batch_size=batch_size, test_set=DataFrameDataset(test_df), test_batch_size=batch_size)"
] |
[
"'%s' >> ~/.deployer/history; \"\"\" % ('sudo' if run_entry.use_sudo else ' ', esc1(self.from_host), esc1(self.username),",
"' >> ~/.deployer/history; echo '%s' >> ~/.deployer/history; \"\"\" % ('sudo' if run_entry.use_sudo else",
"username): from socket import gethostname self.from_host = gethostname() self.username = username def log_run(self,",
"` >> ~/.deployer/history; echo -n '%s | %s | %s | ' >>",
"socket import gethostname self.from_host = gethostname() self.username = username def log_run(self, run_entry): if",
"%%H:%%M:%%S | ' ` >> ~/.deployer/history; echo -n '%s | %s | %s",
"| %s | %s | ' >> ~/.deployer/history; echo '%s' >> ~/.deployer/history; \"\"\"",
"OnHostLogger(Logger): \"\"\" Log all transactions on every host in: ~/.deployer/history \"\"\" def __init__(self,",
"from socket import gethostname self.from_host = gethostname() self.username = username def log_run(self, run_entry):",
"<reponame>timgates42/python-deployer<filename>deployer/contrib/loggers/on_host.py from deployer.loggers import Logger, RunCallback, ForkCallback from deployer.utils import esc1 class OnHostLogger(Logger):",
"the same class OnHostLogger in forks. class callback(ForkCallback): def get_fork_logger(c): return OnHostLogger(self.username) return",
"return RunCallback() def log_fork(self, fork_entry): # Use the same class OnHostLogger in forks.",
"gethostname() self.username = username def log_run(self, run_entry): if not run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir -p",
"= username def log_run(self, run_entry): if not run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir -p ~/.deployer/; echo",
"in: ~/.deployer/history \"\"\" def __init__(self, username): from socket import gethostname self.from_host = gethostname()",
"deployer.loggers import Logger, RunCallback, ForkCallback from deployer.utils import esc1 class OnHostLogger(Logger): \"\"\" Log",
"%s | %s | ' >> ~/.deployer/history; echo '%s' >> ~/.deployer/history; \"\"\" %",
"class OnHostLogger(Logger): \"\"\" Log all transactions on every host in: ~/.deployer/history \"\"\" def",
"'%s | %s | %s | ' >> ~/.deployer/history; echo '%s' >> ~/.deployer/history;",
"Log all transactions on every host in: ~/.deployer/history \"\"\" def __init__(self, username): from",
"| ' ` >> ~/.deployer/history; echo -n '%s | %s | %s |",
">> ~/.deployer/history; echo -n '%s | %s | %s | ' >> ~/.deployer/history;",
"all transactions on every host in: ~/.deployer/history \"\"\" def __init__(self, username): from socket",
"not run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir -p ~/.deployer/; echo -n `date '+%%Y-%%m-%%d %%H:%%M:%%S | '",
")) return RunCallback() def log_fork(self, fork_entry): # Use the same class OnHostLogger in",
"import Logger, RunCallback, ForkCallback from deployer.utils import esc1 class OnHostLogger(Logger): \"\"\" Log all",
"every host in: ~/.deployer/history \"\"\" def __init__(self, username): from socket import gethostname self.from_host",
"' ` >> ~/.deployer/history; echo -n '%s | %s | %s | '",
"~/.deployer/history; \"\"\" % ('sudo' if run_entry.use_sudo else ' ', esc1(self.from_host), esc1(self.username), esc1(run_entry.command or",
"%s | ' >> ~/.deployer/history; echo '%s' >> ~/.deployer/history; \"\"\" % ('sudo' if",
"deployer.utils import esc1 class OnHostLogger(Logger): \"\"\" Log all transactions on every host in:",
"mkdir -p ~/.deployer/; echo -n `date '+%%Y-%%m-%%d %%H:%%M:%%S | ' ` >> ~/.deployer/history;",
"self.from_host = gethostname() self.username = username def log_run(self, run_entry): if not run_entry.sandboxing: run_entry.host._run_silent(\"\"\"",
"import esc1 class OnHostLogger(Logger): \"\"\" Log all transactions on every host in: ~/.deployer/history",
"\"\"\" def __init__(self, username): from socket import gethostname self.from_host = gethostname() self.username =",
"'+%%Y-%%m-%%d %%H:%%M:%%S | ' ` >> ~/.deployer/history; echo -n '%s | %s |",
"log_fork(self, fork_entry): # Use the same class OnHostLogger in forks. class callback(ForkCallback): def",
"if run_entry.use_sudo else ' ', esc1(self.from_host), esc1(self.username), esc1(run_entry.command or '') )) return RunCallback()",
"esc1(self.from_host), esc1(self.username), esc1(run_entry.command or '') )) return RunCallback() def log_fork(self, fork_entry): # Use",
"~/.deployer/history \"\"\" def __init__(self, username): from socket import gethostname self.from_host = gethostname() self.username",
"if not run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir -p ~/.deployer/; echo -n `date '+%%Y-%%m-%%d %%H:%%M:%%S |",
"echo '%s' >> ~/.deployer/history; \"\"\" % ('sudo' if run_entry.use_sudo else ' ', esc1(self.from_host),",
"Logger, RunCallback, ForkCallback from deployer.utils import esc1 class OnHostLogger(Logger): \"\"\" Log all transactions",
"% ('sudo' if run_entry.use_sudo else ' ', esc1(self.from_host), esc1(self.username), esc1(run_entry.command or '') ))",
">> ~/.deployer/history; \"\"\" % ('sudo' if run_entry.use_sudo else ' ', esc1(self.from_host), esc1(self.username), esc1(run_entry.command",
"echo -n '%s | %s | %s | ' >> ~/.deployer/history; echo '%s'",
"__init__(self, username): from socket import gethostname self.from_host = gethostname() self.username = username def",
"| ' >> ~/.deployer/history; echo '%s' >> ~/.deployer/history; \"\"\" % ('sudo' if run_entry.use_sudo",
"~/.deployer/history; echo -n '%s | %s | %s | ' >> ~/.deployer/history; echo",
"-n `date '+%%Y-%%m-%%d %%H:%%M:%%S | ' ` >> ~/.deployer/history; echo -n '%s |",
"= gethostname() self.username = username def log_run(self, run_entry): if not run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir",
"import gethostname self.from_host = gethostname() self.username = username def log_run(self, run_entry): if not",
"def log_run(self, run_entry): if not run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir -p ~/.deployer/; echo -n `date",
"run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir -p ~/.deployer/; echo -n `date '+%%Y-%%m-%%d %%H:%%M:%%S | ' `",
"esc1(self.username), esc1(run_entry.command or '') )) return RunCallback() def log_fork(self, fork_entry): # Use the",
"username def log_run(self, run_entry): if not run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir -p ~/.deployer/; echo -n",
"log_run(self, run_entry): if not run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir -p ~/.deployer/; echo -n `date '+%%Y-%%m-%%d",
"ForkCallback from deployer.utils import esc1 class OnHostLogger(Logger): \"\"\" Log all transactions on every",
"RunCallback, ForkCallback from deployer.utils import esc1 class OnHostLogger(Logger): \"\"\" Log all transactions on",
"fork_entry): # Use the same class OnHostLogger in forks. class callback(ForkCallback): def get_fork_logger(c):",
"same class OnHostLogger in forks. class callback(ForkCallback): def get_fork_logger(c): return OnHostLogger(self.username) return callback()",
"Use the same class OnHostLogger in forks. class callback(ForkCallback): def get_fork_logger(c): return OnHostLogger(self.username)",
"echo -n `date '+%%Y-%%m-%%d %%H:%%M:%%S | ' ` >> ~/.deployer/history; echo -n '%s",
"`date '+%%Y-%%m-%%d %%H:%%M:%%S | ' ` >> ~/.deployer/history; echo -n '%s | %s",
"on every host in: ~/.deployer/history \"\"\" def __init__(self, username): from socket import gethostname",
"host in: ~/.deployer/history \"\"\" def __init__(self, username): from socket import gethostname self.from_host =",
"-p ~/.deployer/; echo -n `date '+%%Y-%%m-%%d %%H:%%M:%%S | ' ` >> ~/.deployer/history; echo",
"'') )) return RunCallback() def log_fork(self, fork_entry): # Use the same class OnHostLogger",
"# Use the same class OnHostLogger in forks. class callback(ForkCallback): def get_fork_logger(c): return",
"def log_fork(self, fork_entry): # Use the same class OnHostLogger in forks. class callback(ForkCallback):",
"run_entry): if not run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir -p ~/.deployer/; echo -n `date '+%%Y-%%m-%%d %%H:%%M:%%S",
"self.username = username def log_run(self, run_entry): if not run_entry.sandboxing: run_entry.host._run_silent(\"\"\" mkdir -p ~/.deployer/;",
"| %s | ' >> ~/.deployer/history; echo '%s' >> ~/.deployer/history; \"\"\" % ('sudo'",
"~/.deployer/; echo -n `date '+%%Y-%%m-%%d %%H:%%M:%%S | ' ` >> ~/.deployer/history; echo -n",
"run_entry.use_sudo else ' ', esc1(self.from_host), esc1(self.username), esc1(run_entry.command or '') )) return RunCallback() def",
">> ~/.deployer/history; echo '%s' >> ~/.deployer/history; \"\"\" % ('sudo' if run_entry.use_sudo else '",
"-n '%s | %s | %s | ' >> ~/.deployer/history; echo '%s' >>",
"gethostname self.from_host = gethostname() self.username = username def log_run(self, run_entry): if not run_entry.sandboxing:",
"' ', esc1(self.from_host), esc1(self.username), esc1(run_entry.command or '') )) return RunCallback() def log_fork(self, fork_entry):",
"', esc1(self.from_host), esc1(self.username), esc1(run_entry.command or '') )) return RunCallback() def log_fork(self, fork_entry): #",
"\"\"\" % ('sudo' if run_entry.use_sudo else ' ', esc1(self.from_host), esc1(self.username), esc1(run_entry.command or '')",
"esc1 class OnHostLogger(Logger): \"\"\" Log all transactions on every host in: ~/.deployer/history \"\"\"",
"esc1(run_entry.command or '') )) return RunCallback() def log_fork(self, fork_entry): # Use the same",
"from deployer.loggers import Logger, RunCallback, ForkCallback from deployer.utils import esc1 class OnHostLogger(Logger): \"\"\"",
"run_entry.host._run_silent(\"\"\" mkdir -p ~/.deployer/; echo -n `date '+%%Y-%%m-%%d %%H:%%M:%%S | ' ` >>",
"RunCallback() def log_fork(self, fork_entry): # Use the same class OnHostLogger in forks. class",
"or '') )) return RunCallback() def log_fork(self, fork_entry): # Use the same class",
"transactions on every host in: ~/.deployer/history \"\"\" def __init__(self, username): from socket import",
"from deployer.utils import esc1 class OnHostLogger(Logger): \"\"\" Log all transactions on every host",
"('sudo' if run_entry.use_sudo else ' ', esc1(self.from_host), esc1(self.username), esc1(run_entry.command or '') )) return",
"def __init__(self, username): from socket import gethostname self.from_host = gethostname() self.username = username",
"~/.deployer/history; echo '%s' >> ~/.deployer/history; \"\"\" % ('sudo' if run_entry.use_sudo else ' ',",
"else ' ', esc1(self.from_host), esc1(self.username), esc1(run_entry.command or '') )) return RunCallback() def log_fork(self,",
"\"\"\" Log all transactions on every host in: ~/.deployer/history \"\"\" def __init__(self, username):"
] |
[
"# Create buttons with a vertical configuration if orientation == \"vertical\": buttonWidth =",
"display of the menu\"\"\" # Draw the border surfBack = pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor)",
"= self._width - (2*h_padding) - (2*borderWidth) buttonHeight = (self._height - (2*v_padding) - \\",
"color of the menu background (None for transparent) borderColor - rgb color value",
"buttons for b in self._buttons: b[0].draw(screen) def createDisplay(self): \"\"\"Create the display of the",
"menu\"\"\" # Draw the border surfBack = pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor) # Draw the",
"- (x,y) position for the top-left corner of the menu dims - (width,",
"rgb color of the menu background (None for transparent) borderColor - rgb color",
"Create buttons with a horizontal configuration elif orientation == \"horizontal\": buttonWidth = (self._width",
"current selection and resets it to None\"\"\" sel = self._selection self._selection = None",
"space in pixels between buttons color - rgb color of the menu background",
"font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) # Create buttons",
"self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0], yStart + (x*buttonHeight) + \\ (x*spacing) + self._offset[1]), font,",
"self._selection = selection def getSelection(self): \"\"\"Returns the current selection and resets it to",
"for the border font - Supplied as a pygame font orientation - \"vertical\"",
"sel = self._selection self._selection = None return sel def draw(self, screen): \"\"\"Draws the",
"__init__(self, pos, dims, commands, padding=0, spacing=0, color=(80,80,80), borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes the menu\"\"\"",
"for button in self._buttons: if button[0].getText() == text: return button[0] def getButtonByPosition(self, position):",
"position): \"\"\"Return the button at the given position in the menu\"\"\" return self._buttons[position][0]",
"= dims[1] h_padding = padding[0] v_padding = padding[1] self._borderColor = borderColor self._borderWidth =",
"\\ ((n-1)*spacing) - (2*borderWidth)) // n for x, b in enumerate(commands): font =",
"import Window class Menu(Drawable, Window): def __init__(self, pos, dims, commands, padding=0, spacing=0, color=(80,80,80),",
"None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor) # Blit the widget layer onto the back",
"buttons with a horizontal configuration elif orientation == \"horizontal\": buttonWidth = (self._width -",
"the current selection\"\"\" b, selection, closeOnPress, toggleText = button if closeOnPress: self.close() if",
"else: b.setText(toggleText[0]) self._selection = selection def getSelection(self): \"\"\"Returns the current selection and resets",
"b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) # Create buttons with a",
"(2*borderWidth)) // n for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"],",
"// n buttonHeight = self._height - (2*v_padding) - (2*borderWidth) for x, b in",
"getButtonByText(self, text): \"\"\"Return the button with the provided text\"\"\" for button in self._buttons:",
"selection and resets it to None\"\"\" sel = self._selection self._selection = None return",
"b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0] +\\ (x*buttonWidth)",
"n buttonHeight = self._height - (2*v_padding) - (2*borderWidth) for x, b in enumerate(commands):",
"Button from polybius.graphics.basics.drawable import Drawable from polybius.graphics.utils.window import Window class Menu(Drawable, Window): def",
"corner of the menu dims - (width, height) pixels of the menu commands",
"polybius.graphics.basics.drawable import Drawable from polybius.graphics.utils.window import Window class Menu(Drawable, Window): def __init__(self, pos,",
"self._offset[0], yStart + (x*buttonHeight) + \\ (x*spacing) + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight,",
"+ self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) #",
"position for the top-left corner of the menu dims - (width, height) pixels",
"select(self, button): \"\"\"Sets the current selection\"\"\" b, selection, closeOnPress, toggleText = button if",
"\\ ((n-1)*spacing) - (2*borderWidth)) // n buttonHeight = self._height - (2*v_padding) - (2*borderWidth)",
"def handleEvent(self, event): \"\"\"Handles events on the pause menu\"\"\" for b in self._buttons:",
"the menu\"\"\" return self._buttons[position][0] def handleEvent(self, event): \"\"\"Handles events on the pause menu\"\"\"",
"v_padding = padding[1] self._borderColor = borderColor self._borderWidth = borderWidth self._backgroundColor = color n",
"for the top-left corner of the menu dims - (width, height) pixels of",
"creating menus Parameters: pos - (x,y) position for the top-left corner of the",
"+ \\ (x*spacing) + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1,",
"\"\"\" Author: <NAME> File: menu.py A general class for creating menus Parameters: pos",
"== text: return button[0] def getButtonByPosition(self, position): \"\"\"Return the button at the given",
"- space in pixels between buttons color - rgb color of the menu",
"= len(commands) xStart = h_padding yStart = v_padding self._buttons = [] # Create",
"buttons with a vertical configuration if orientation == \"vertical\": buttonWidth = self._width -",
"Blit the widget layer onto the back surface surfBack.blit(surf, (self._borderWidth, self._borderWidth)) self._image =",
"self._height)) surfBack.fill(self._borderColor) # Draw the background surf = pygame.Surface((self._width - (self._borderWidth * 2),",
"= pygame.Surface((self._width - (self._borderWidth * 2), self._height - (self._borderWidth * 2))) # Apply",
"b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) # Create buttons with a horizontal configuration elif",
"== \"horizontal\": buttonWidth = (self._width - (2*h_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) //",
"!= None: currentText = b._text if toggleText[0] == currentText: b.setText(toggleText[1]) else: b.setText(toggleText[0]) self._selection",
"\\ (x*spacing) + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"],",
"padding - (horizontal, vertical) padding between border and buttons spacing - space in",
"pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0] +\\ (x*buttonWidth) + (x*spacing), yStart + self._offset[1]),",
"make transparent if self._backgroundColor == None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor) # Blit the",
"with the provided text\"\"\" for button in self._buttons: if button[0].getText() == text: return",
"color or make transparent if self._backgroundColor == None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor) #",
"Parameters: pos - (x,y) position for the top-left corner of the menu dims",
"= pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor) # Draw the background surf = pygame.Surface((self._width - (self._borderWidth",
"# Draw the background surf = pygame.Surface((self._width - (self._borderWidth * 2), self._height -",
"surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor) # Blit the widget layer onto the back surface surfBack.blit(surf,",
"color value for border borderWidth - pixel width for the border font -",
"self._selection = None self.createDisplay() def getButtonByText(self, text): \"\"\"Return the button with the provided",
"orientation - \"vertical\" | \"horizontal\" \"\"\" import pygame from polybius.graphics.components import Button from",
"b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection = None self.createDisplay() def getButtonByText(self, text): \"\"\"Return",
"sel def draw(self, screen): \"\"\"Draws the menu on the screen\"\"\" super().draw(screen) # Draw",
"yStart = v_padding self._buttons = [] # Create buttons with a vertical configuration",
"handleEvent(self, event): \"\"\"Handles events on the pause menu\"\"\" for b in self._buttons: b[0].handleEvent(event,self.select,(b,))",
"general class for creating menus Parameters: pos - (x,y) position for the top-left",
"height) pixels of the menu commands - list of dictionaries specifying the button",
"for transparent) borderColor - rgb color value for border borderWidth - pixel width",
"# Draw buttons for b in self._buttons: b[0].draw(screen) def createDisplay(self): \"\"\"Create the display",
"menu background (None for transparent) borderColor - rgb color value for border borderWidth",
"\"horizontal\" \"\"\" import pygame from polybius.graphics.components import Button from polybius.graphics.basics.drawable import Drawable from",
"font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0], yStart + (x*buttonHeight) + \\",
"(x,y) position for the top-left corner of the menu dims - (width, height)",
"borderWidth - pixel width for the border font - Supplied as a pygame",
"pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0], yStart + (x*buttonHeight) + \\ (x*spacing) +",
"- (2*v_padding) - (2*borderWidth) for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"])",
"if toggleText[0] == currentText: b.setText(toggleText[1]) else: b.setText(toggleText[0]) self._selection = selection def getSelection(self): \"\"\"Returns",
"2), self._height - (self._borderWidth * 2))) # Apply the background color or make",
"pos, worldBound=False) Window.__init__(self) self._offset = (pos[0], pos[1]) self._width = dims[0] self._height = dims[1]",
"(2*borderWidth) buttonHeight = (self._height - (2*v_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n",
"with a horizontal configuration elif orientation == \"horizontal\": buttonWidth = (self._width - (2*h_padding)",
"closeOnPress: self.close() if toggleText[0] != None: currentText = b._text if toggleText[0] == currentText:",
"given position in the menu\"\"\" return self._buttons[position][0] def handleEvent(self, event): \"\"\"Handles events on",
"resets it to None\"\"\" sel = self._selection self._selection = None return sel def",
"the background surf = pygame.Surface((self._width - (self._borderWidth * 2), self._height - (self._borderWidth *",
"class Menu(Drawable, Window): def __init__(self, pos, dims, commands, padding=0, spacing=0, color=(80,80,80), borderColor=(0,0,0), borderWidth=2,",
"x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0], yStart",
"pos[1]) self._width = dims[0] self._height = dims[1] h_padding = padding[0] v_padding = padding[1]",
"button if closeOnPress: self.close() if toggleText[0] != None: currentText = b._text if toggleText[0]",
"Draw the background surf = pygame.Surface((self._width - (self._borderWidth * 2), self._height - (self._borderWidth",
"(2*h_padding) - (2*borderWidth) buttonHeight = (self._height - (2*v_padding) - \\ ((n-1)*spacing) - (2*borderWidth))",
"self._offset[0] +\\ (x*buttonWidth) + (x*spacing), yStart + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth,",
"pixels between buttons color - rgb color of the menu background (None for",
"pause menu\"\"\" for b in self._buttons: b[0].handleEvent(event,self.select,(b,)) return self.getSelection() def select(self, button): \"\"\"Sets",
"Draw the border surfBack = pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor) # Draw the background surf",
"- (self._borderWidth * 2))) # Apply the background color or make transparent if",
"self._buttons[position][0] def handleEvent(self, event): \"\"\"Handles events on the pause menu\"\"\" for b in",
"self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection =",
"for b in self._buttons: b[0].draw(screen) def createDisplay(self): \"\"\"Create the display of the menu\"\"\"",
"super().draw(screen) # Draw buttons for b in self._buttons: b[0].draw(screen) def createDisplay(self): \"\"\"Create the",
"return sel def draw(self, screen): \"\"\"Draws the menu on the screen\"\"\" super().draw(screen) #",
"- Supplied as a pygame font orientation - \"vertical\" | \"horizontal\" \"\"\" import",
"= padding[1] self._borderColor = borderColor self._borderWidth = borderWidth self._backgroundColor = color n =",
"- (2*borderWidth)) // n for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"])",
"# Blit the widget layer onto the back surface surfBack.blit(surf, (self._borderWidth, self._borderWidth)) self._image",
"button[0] def getButtonByPosition(self, position): \"\"\"Return the button at the given position in the",
"surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor) # Blit the widget layer onto the back surface",
"for creating menus Parameters: pos - (x,y) position for the top-left corner of",
"Drawable.__init__(self, \"\", pos, worldBound=False) Window.__init__(self) self._offset = (pos[0], pos[1]) self._width = dims[0] self._height",
"worldBound=False) Window.__init__(self) self._offset = (pos[0], pos[1]) self._width = dims[0] self._height = dims[1] h_padding",
"button in self._buttons: if button[0].getText() == text: return button[0] def getButtonByPosition(self, position): \"\"\"Return",
"Window.__init__(self) self._offset = (pos[0], pos[1]) self._width = dims[0] self._height = dims[1] h_padding =",
"b[0].handleEvent(event,self.select,(b,)) return self.getSelection() def select(self, button): \"\"\"Sets the current selection\"\"\" b, selection, closeOnPress,",
"menus Parameters: pos - (x,y) position for the top-left corner of the menu",
"b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0], yStart + (x*buttonHeight) + \\ (x*spacing) + self._offset[1]),",
"- \\ ((n-1)*spacing) - (2*borderWidth)) // n buttonHeight = self._height - (2*v_padding) -",
"+ (x*spacing), yStart + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1,",
"and buttons spacing - space in pixels between buttons color - rgb color",
"if closeOnPress: self.close() if toggleText[0] != None: currentText = b._text if toggleText[0] ==",
"on the screen\"\"\" super().draw(screen) # Draw buttons for b in self._buttons: b[0].draw(screen) def",
"h_padding yStart = v_padding self._buttons = [] # Create buttons with a vertical",
"== currentText: b.setText(toggleText[1]) else: b.setText(toggleText[0]) self._selection = selection def getSelection(self): \"\"\"Returns the current",
"specifying the button attributes padding - (horizontal, vertical) padding between border and buttons",
"= dims[0] self._height = dims[1] h_padding = padding[0] v_padding = padding[1] self._borderColor =",
"(xStart + self._offset[0] +\\ (x*buttonWidth) + (x*spacing), yStart + self._offset[1]), font, b[\"fontColor\"], b[\"color\"],",
"Menu(Drawable, Window): def __init__(self, pos, dims, commands, padding=0, spacing=0, color=(80,80,80), borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"):",
"button with the provided text\"\"\" for button in self._buttons: if button[0].getText() == text:",
"or make transparent if self._backgroundColor == None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor) # Blit",
"return self.getSelection() def select(self, button): \"\"\"Sets the current selection\"\"\" b, selection, closeOnPress, toggleText",
"attributes padding - (horizontal, vertical) padding between border and buttons spacing - space",
"x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0] +\\",
"[] # Create buttons with a vertical configuration if orientation == \"vertical\": buttonWidth",
"# Create buttons with a horizontal configuration elif orientation == \"horizontal\": buttonWidth =",
"menu dims - (width, height) pixels of the menu commands - list of",
"transparent) borderColor - rgb color value for border borderWidth - pixel width for",
"b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) # Create buttons with a horizontal configuration elif orientation",
"b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0] +\\ (x*buttonWidth) + (x*spacing), yStart + self._offset[1]), font,",
"(self._borderWidth * 2))) # Apply the background color or make transparent if self._backgroundColor",
"of dictionaries specifying the button attributes padding - (horizontal, vertical) padding between border",
"# Apply the background color or make transparent if self._backgroundColor == None: surf.fill((1,1,1))",
"\"\"\"Create the display of the menu\"\"\" # Draw the border surfBack = pygame.Surface((self._width,",
"= v_padding self._buttons = [] # Create buttons with a vertical configuration if",
"width for the border font - Supplied as a pygame font orientation -",
"b in self._buttons: b[0].draw(screen) def createDisplay(self): \"\"\"Create the display of the menu\"\"\" #",
"createDisplay(self): \"\"\"Create the display of the menu\"\"\" # Draw the border surfBack =",
"borderWidth self._backgroundColor = color n = len(commands) xStart = h_padding yStart = v_padding",
"(2*h_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n buttonHeight = self._height - (2*v_padding)",
"// n for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart",
"the menu dims - (width, height) pixels of the menu commands - list",
"b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection = None self.createDisplay()",
"n = len(commands) xStart = h_padding yStart = v_padding self._buttons = [] #",
"h_padding = padding[0] v_padding = padding[1] self._borderColor = borderColor self._borderWidth = borderWidth self._backgroundColor",
"Window class Menu(Drawable, Window): def __init__(self, pos, dims, commands, padding=0, spacing=0, color=(80,80,80), borderColor=(0,0,0),",
"polybius.graphics.utils.window import Window class Menu(Drawable, Window): def __init__(self, pos, dims, commands, padding=0, spacing=0,",
"surfBack.fill(self._borderColor) # Draw the background surf = pygame.Surface((self._width - (self._borderWidth * 2), self._height",
"= padding[0] v_padding = padding[1] self._borderColor = borderColor self._borderWidth = borderWidth self._backgroundColor =",
"self._borderColor = borderColor self._borderWidth = borderWidth self._backgroundColor = color n = len(commands) xStart",
"yStart + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"])))",
"self.close() if toggleText[0] != None: currentText = b._text if toggleText[0] == currentText: b.setText(toggleText[1])",
"self._buttons: if button[0].getText() == text: return button[0] def getButtonByPosition(self, position): \"\"\"Return the button",
"(self._height - (2*v_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n for x, b",
"between border and buttons spacing - space in pixels between buttons color -",
"buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection = None self.createDisplay() def getButtonByText(self,",
"from polybius.graphics.basics.drawable import Drawable from polybius.graphics.utils.window import Window class Menu(Drawable, Window): def __init__(self,",
"b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection = None self.createDisplay() def",
"screen): \"\"\"Draws the menu on the screen\"\"\" super().draw(screen) # Draw buttons for b",
"dims - (width, height) pixels of the menu commands - list of dictionaries",
"font orientation - \"vertical\" | \"horizontal\" \"\"\" import pygame from polybius.graphics.components import Button",
"getSelection(self): \"\"\"Returns the current selection and resets it to None\"\"\" sel = self._selection",
"def __init__(self, pos, dims, commands, padding=0, spacing=0, color=(80,80,80), borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes the",
"\"\"\"Handles events on the pause menu\"\"\" for b in self._buttons: b[0].handleEvent(event,self.select,(b,)) return self.getSelection()",
"to None\"\"\" sel = self._selection self._selection = None return sel def draw(self, screen):",
"buttonWidth = (self._width - (2*h_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n buttonHeight",
"pos, dims, commands, padding=0, spacing=0, color=(80,80,80), borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes the menu\"\"\" Drawable.__init__(self,",
"surf.fill(self._backgroundColor) # Blit the widget layer onto the back surface surfBack.blit(surf, (self._borderWidth, self._borderWidth))",
"toggleText[0] == currentText: b.setText(toggleText[1]) else: b.setText(toggleText[0]) self._selection = selection def getSelection(self): \"\"\"Returns the",
"+ (x*buttonHeight) + \\ (x*spacing) + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"],",
"borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes the menu\"\"\" Drawable.__init__(self, \"\", pos, worldBound=False) Window.__init__(self) self._offset =",
"self.getSelection() def select(self, button): \"\"\"Sets the current selection\"\"\" b, selection, closeOnPress, toggleText =",
"a horizontal configuration elif orientation == \"horizontal\": buttonWidth = (self._width - (2*h_padding) -",
"| \"horizontal\" \"\"\" import pygame from polybius.graphics.components import Button from polybius.graphics.basics.drawable import Drawable",
"- rgb color of the menu background (None for transparent) borderColor - rgb",
"+ self._offset[0], yStart + (x*buttonHeight) + \\ (x*spacing) + self._offset[1]), font, b[\"fontColor\"], b[\"color\"],",
"the menu\"\"\" # Draw the border surfBack = pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor) # Draw",
"toggleText = button if closeOnPress: self.close() if toggleText[0] != None: currentText = b._text",
"b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0], yStart +",
"(self._borderWidth * 2), self._height - (self._borderWidth * 2))) # Apply the background color",
"the border font - Supplied as a pygame font orientation - \"vertical\" |",
"padding between border and buttons spacing - space in pixels between buttons color",
"the top-left corner of the menu dims - (width, height) pixels of the",
"buttonHeight = self._height - (2*v_padding) - (2*borderWidth) for x, b in enumerate(commands): font",
"+\\ (x*buttonWidth) + (x*spacing), yStart + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"],",
"events on the pause menu\"\"\" for b in self._buttons: b[0].handleEvent(event,self.select,(b,)) return self.getSelection() def",
"(horizontal, vertical) padding between border and buttons spacing - space in pixels between",
"border font - Supplied as a pygame font orientation - \"vertical\" | \"horizontal\"",
"button attributes padding - (horizontal, vertical) padding between border and buttons spacing -",
"b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) # Create buttons with",
"elif orientation == \"horizontal\": buttonWidth = (self._width - (2*h_padding) - \\ ((n-1)*spacing) -",
"pos - (x,y) position for the top-left corner of the menu dims -",
"(x*buttonWidth) + (x*spacing), yStart + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]),",
"dims[0] self._height = dims[1] h_padding = padding[0] v_padding = padding[1] self._borderColor = borderColor",
"self._selection = None return sel def draw(self, screen): \"\"\"Draws the menu on the",
"class for creating menus Parameters: pos - (x,y) position for the top-left corner",
"top-left corner of the menu dims - (width, height) pixels of the menu",
"None\"\"\" sel = self._selection self._selection = None return sel def draw(self, screen): \"\"\"Draws",
"Draw buttons for b in self._buttons: b[0].draw(screen) def createDisplay(self): \"\"\"Create the display of",
"background surf = pygame.Surface((self._width - (self._borderWidth * 2), self._height - (self._borderWidth * 2)))",
"= b._text if toggleText[0] == currentText: b.setText(toggleText[1]) else: b.setText(toggleText[0]) self._selection = selection def",
"n for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart +",
"button): \"\"\"Sets the current selection\"\"\" b, selection, closeOnPress, toggleText = button if closeOnPress:",
"currentText = b._text if toggleText[0] == currentText: b.setText(toggleText[1]) else: b.setText(toggleText[0]) self._selection = selection",
"self._backgroundColor = color n = len(commands) xStart = h_padding yStart = v_padding self._buttons",
"self._height - (2*v_padding) - (2*borderWidth) for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"],",
"of the menu background (None for transparent) borderColor - rgb color value for",
"= None return sel def draw(self, screen): \"\"\"Draws the menu on the screen\"\"\"",
"current selection\"\"\" b, selection, closeOnPress, toggleText = button if closeOnPress: self.close() if toggleText[0]",
"\"horizontal\": buttonWidth = (self._width - (2*h_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n",
"position in the menu\"\"\" return self._buttons[position][0] def handleEvent(self, event): \"\"\"Handles events on the",
"padding[0] v_padding = padding[1] self._borderColor = borderColor self._borderWidth = borderWidth self._backgroundColor = color",
"font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection = None",
"on the pause menu\"\"\" for b in self._buttons: b[0].handleEvent(event,self.select,(b,)) return self.getSelection() def select(self,",
"font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0] +\\ (x*buttonWidth) + (x*spacing), yStart",
"for border borderWidth - pixel width for the border font - Supplied as",
"the display of the menu\"\"\" # Draw the border surfBack = pygame.Surface((self._width, self._height))",
"Apply the background color or make transparent if self._backgroundColor == None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1))",
"the current selection and resets it to None\"\"\" sel = self._selection self._selection =",
"menu on the screen\"\"\" super().draw(screen) # Draw buttons for b in self._buttons: b[0].draw(screen)",
"if toggleText[0] != None: currentText = b._text if toggleText[0] == currentText: b.setText(toggleText[1]) else:",
"b in self._buttons: b[0].handleEvent(event,self.select,(b,)) return self.getSelection() def select(self, button): \"\"\"Sets the current selection\"\"\"",
"return self._buttons[position][0] def handleEvent(self, event): \"\"\"Handles events on the pause menu\"\"\" for b",
"= h_padding yStart = v_padding self._buttons = [] # Create buttons with a",
"borderColor - rgb color value for border borderWidth - pixel width for the",
"the menu commands - list of dictionaries specifying the button attributes padding -",
"- (2*borderWidth) for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart",
"yStart + (x*buttonHeight) + \\ (x*spacing) + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth,",
"selection def getSelection(self): \"\"\"Returns the current selection and resets it to None\"\"\" sel",
"enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0], yStart + (x*buttonHeight) +",
"- list of dictionaries specifying the button attributes padding - (horizontal, vertical) padding",
"self._selection self._selection = None return sel def draw(self, screen): \"\"\"Draws the menu on",
"text: return button[0] def getButtonByPosition(self, position): \"\"\"Return the button at the given position",
"(x*spacing) + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"])))",
"- pixel width for the border font - Supplied as a pygame font",
"+ self._offset[0] +\\ (x*buttonWidth) + (x*spacing), yStart + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight,",
"the screen\"\"\" super().draw(screen) # Draw buttons for b in self._buttons: b[0].draw(screen) def createDisplay(self):",
"background color or make transparent if self._backgroundColor == None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor)",
"(2*v_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n for x, b in enumerate(commands):",
"at the given position in the menu\"\"\" return self._buttons[position][0] def handleEvent(self, event): \"\"\"Handles",
"if button[0].getText() == text: return button[0] def getButtonByPosition(self, position): \"\"\"Return the button at",
"in self._buttons: if button[0].getText() == text: return button[0] def getButtonByPosition(self, position): \"\"\"Return the",
"x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) # Create buttons with a horizontal configuration elif orientation ==",
"value for border borderWidth - pixel width for the border font - Supplied",
"A general class for creating menus Parameters: pos - (x,y) position for the",
"button at the given position in the menu\"\"\" return self._buttons[position][0] def handleEvent(self, event):",
"of the menu\"\"\" # Draw the border surfBack = pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor) #",
"menu\"\"\" Drawable.__init__(self, \"\", pos, worldBound=False) Window.__init__(self) self._offset = (pos[0], pos[1]) self._width = dims[0]",
"= selection def getSelection(self): \"\"\"Returns the current selection and resets it to None\"\"\"",
"the background color or make transparent if self._backgroundColor == None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else:",
"enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0] +\\ (x*buttonWidth) + (x*spacing),",
"padding=0, spacing=0, color=(80,80,80), borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes the menu\"\"\" Drawable.__init__(self, \"\", pos, worldBound=False)",
"= borderWidth self._backgroundColor = color n = len(commands) xStart = h_padding yStart =",
"the button at the given position in the menu\"\"\" return self._buttons[position][0] def handleEvent(self,",
"- rgb color value for border borderWidth - pixel width for the border",
"if self._backgroundColor == None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor) # Blit the widget layer",
"in pixels between buttons color - rgb color of the menu background (None",
"self._height = dims[1] h_padding = padding[0] v_padding = padding[1] self._borderColor = borderColor self._borderWidth",
"(2*borderWidth) for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart +",
"* 2), self._height - (self._borderWidth * 2))) # Apply the background color or",
"menu\"\"\" for b in self._buttons: b[0].handleEvent(event,self.select,(b,)) return self.getSelection() def select(self, button): \"\"\"Sets the",
"Supplied as a pygame font orientation - \"vertical\" | \"horizontal\" \"\"\" import pygame",
"((n-1)*spacing) - (2*borderWidth)) // n buttonHeight = self._height - (2*v_padding) - (2*borderWidth) for",
"buttonHeight = (self._height - (2*v_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n for",
"b.setText(toggleText[0]) self._selection = selection def getSelection(self): \"\"\"Returns the current selection and resets it",
"dims[1] h_padding = padding[0] v_padding = padding[1] self._borderColor = borderColor self._borderWidth = borderWidth",
"= (pos[0], pos[1]) self._width = dims[0] self._height = dims[1] h_padding = padding[0] v_padding",
"vertical) padding between border and buttons spacing - space in pixels between buttons",
"draw(self, screen): \"\"\"Draws the menu on the screen\"\"\" super().draw(screen) # Draw buttons for",
"(b.get(\"toggleText\",None),b[\"text\"]))) self._selection = None self.createDisplay() def getButtonByText(self, text): \"\"\"Return the button with the",
"transparent if self._backgroundColor == None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor) # Blit the widget",
"borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes the menu\"\"\" Drawable.__init__(self, \"\", pos, worldBound=False) Window.__init__(self) self._offset = (pos[0],",
"\"\"\"Return the button with the provided text\"\"\" for button in self._buttons: if button[0].getText()",
"buttons spacing - space in pixels between buttons color - rgb color of",
"Author: <NAME> File: menu.py A general class for creating menus Parameters: pos -",
"\"vertical\" | \"horizontal\" \"\"\" import pygame from polybius.graphics.components import Button from polybius.graphics.basics.drawable import",
"= button if closeOnPress: self.close() if toggleText[0] != None: currentText = b._text if",
"the menu background (None for transparent) borderColor - rgb color value for border",
"2))) # Apply the background color or make transparent if self._backgroundColor == None:",
"pygame font orientation - \"vertical\" | \"horizontal\" \"\"\" import pygame from polybius.graphics.components import",
"for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0]",
"border surfBack = pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor) # Draw the background surf = pygame.Surface((self._width",
"configuration elif orientation == \"horizontal\": buttonWidth = (self._width - (2*h_padding) - \\ ((n-1)*spacing)",
"in self._buttons: b[0].draw(screen) def createDisplay(self): \"\"\"Create the display of the menu\"\"\" # Draw",
"def select(self, button): \"\"\"Sets the current selection\"\"\" b, selection, closeOnPress, toggleText = button",
"a pygame font orientation - \"vertical\" | \"horizontal\" \"\"\" import pygame from polybius.graphics.components",
"self._buttons = [] # Create buttons with a vertical configuration if orientation ==",
"provided text\"\"\" for button in self._buttons: if button[0].getText() == text: return button[0] def",
"the menu\"\"\" Drawable.__init__(self, \"\", pos, worldBound=False) Window.__init__(self) self._offset = (pos[0], pos[1]) self._width =",
"\"\"\"Sets the current selection\"\"\" b, selection, closeOnPress, toggleText = button if closeOnPress: self.close()",
"((n-1)*spacing) - (2*borderWidth)) // n for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"],",
"== \"vertical\": buttonWidth = self._width - (2*h_padding) - (2*borderWidth) buttonHeight = (self._height -",
"with a vertical configuration if orientation == \"vertical\": buttonWidth = self._width - (2*h_padding)",
"def createDisplay(self): \"\"\"Create the display of the menu\"\"\" # Draw the border surfBack",
"= pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0], yStart + (x*buttonHeight) + \\ (x*spacing)",
"b.setText(toggleText[1]) else: b.setText(toggleText[0]) self._selection = selection def getSelection(self): \"\"\"Returns the current selection and",
"self._buttons: b[0].handleEvent(event,self.select,(b,)) return self.getSelection() def select(self, button): \"\"\"Sets the current selection\"\"\" b, selection,",
"orientation == \"horizontal\": buttonWidth = (self._width - (2*h_padding) - \\ ((n-1)*spacing) - (2*borderWidth))",
"list of dictionaries specifying the button attributes padding - (horizontal, vertical) padding between",
"self._height - (self._borderWidth * 2))) # Apply the background color or make transparent",
"pixels of the menu commands - list of dictionaries specifying the button attributes",
"the provided text\"\"\" for button in self._buttons: if button[0].getText() == text: return button[0]",
"getButtonByPosition(self, position): \"\"\"Return the button at the given position in the menu\"\"\" return",
"def getButtonByPosition(self, position): \"\"\"Return the button at the given position in the menu\"\"\"",
"polybius.graphics.components import Button from polybius.graphics.basics.drawable import Drawable from polybius.graphics.utils.window import Window class Menu(Drawable,",
"in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0], yStart + (x*buttonHeight)",
"for b in self._buttons: b[0].handleEvent(event,self.select,(b,)) return self.getSelection() def select(self, button): \"\"\"Sets the current",
"buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection = None self.createDisplay() def getButtonByText(self, text):",
"self._offset = (pos[0], pos[1]) self._width = dims[0] self._height = dims[1] h_padding = padding[0]",
"color n = len(commands) xStart = h_padding yStart = v_padding self._buttons = []",
"screen\"\"\" super().draw(screen) # Draw buttons for b in self._buttons: b[0].draw(screen) def createDisplay(self): \"\"\"Create",
"self._backgroundColor == None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor) # Blit the widget layer onto",
"self._width - (2*h_padding) - (2*borderWidth) buttonHeight = (self._height - (2*v_padding) - \\ ((n-1)*spacing)",
"(self._width - (2*h_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n buttonHeight = self._height",
"the given position in the menu\"\"\" return self._buttons[position][0] def handleEvent(self, event): \"\"\"Handles events",
"orientation == \"vertical\": buttonWidth = self._width - (2*h_padding) - (2*borderWidth) buttonHeight = (self._height",
"menu.py A general class for creating menus Parameters: pos - (x,y) position for",
"= None self.createDisplay() def getButtonByText(self, text): \"\"\"Return the button with the provided text\"\"\"",
"and resets it to None\"\"\" sel = self._selection self._selection = None return sel",
"selection\"\"\" b, selection, closeOnPress, toggleText = button if closeOnPress: self.close() if toggleText[0] !=",
"currentText: b.setText(toggleText[1]) else: b.setText(toggleText[0]) self._selection = selection def getSelection(self): \"\"\"Returns the current selection",
"the border surfBack = pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor) # Draw the background surf =",
"return button[0] def getButtonByPosition(self, position): \"\"\"Return the button at the given position in",
"def getButtonByText(self, text): \"\"\"Return the button with the provided text\"\"\" for button in",
"\"\", pos, worldBound=False) Window.__init__(self) self._offset = (pos[0], pos[1]) self._width = dims[0] self._height =",
"def getSelection(self): \"\"\"Returns the current selection and resets it to None\"\"\" sel =",
"== None: surf.fill((1,1,1)) surfBack.set_colorkey((1,1,1)) else: surf.fill(self._backgroundColor) # Blit the widget layer onto the",
"text\"\"\" for button in self._buttons: if button[0].getText() == text: return button[0] def getButtonByPosition(self,",
"= self._selection self._selection = None return sel def draw(self, screen): \"\"\"Draws the menu",
"spacing - space in pixels between buttons color - rgb color of the",
"\"\"\"Return the button at the given position in the menu\"\"\" return self._buttons[position][0] def",
"commands, padding=0, spacing=0, color=(80,80,80), borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes the menu\"\"\" Drawable.__init__(self, \"\", pos,",
"pygame.Surface((self._width - (self._borderWidth * 2), self._height - (self._borderWidth * 2))) # Apply the",
"in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0] +\\ (x*buttonWidth) +",
"from polybius.graphics.components import Button from polybius.graphics.basics.drawable import Drawable from polybius.graphics.utils.window import Window class",
"\"\"\"Returns the current selection and resets it to None\"\"\" sel = self._selection self._selection",
"orientation=\"vertical\"): \"\"\"Initializes the menu\"\"\" Drawable.__init__(self, \"\", pos, worldBound=False) Window.__init__(self) self._offset = (pos[0], pos[1])",
"- (2*v_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n for x, b in",
"- \\ ((n-1)*spacing) - (2*borderWidth)) // n for x, b in enumerate(commands): font",
"= (self._height - (2*v_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n for x,",
"font - Supplied as a pygame font orientation - \"vertical\" | \"horizontal\" \"\"\"",
"a vertical configuration if orientation == \"vertical\": buttonWidth = self._width - (2*h_padding) -",
"\"\"\"Draws the menu on the screen\"\"\" super().draw(screen) # Draw buttons for b in",
"None self.createDisplay() def getButtonByText(self, text): \"\"\"Return the button with the provided text\"\"\" for",
"dims, commands, padding=0, spacing=0, color=(80,80,80), borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes the menu\"\"\" Drawable.__init__(self, \"\",",
"the pause menu\"\"\" for b in self._buttons: b[0].handleEvent(event,self.select,(b,)) return self.getSelection() def select(self, button):",
"configuration if orientation == \"vertical\": buttonWidth = self._width - (2*h_padding) - (2*borderWidth) buttonHeight",
"- \"vertical\" | \"horizontal\" \"\"\" import pygame from polybius.graphics.components import Button from polybius.graphics.basics.drawable",
"self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) # Create",
"x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection = None self.createDisplay() def getButtonByText(self, text): \"\"\"Return the button",
"- (horizontal, vertical) padding between border and buttons spacing - space in pixels",
"len(commands) xStart = h_padding yStart = v_padding self._buttons = [] # Create buttons",
"color=(80,80,80), borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes the menu\"\"\" Drawable.__init__(self, \"\", pos, worldBound=False) Window.__init__(self) self._offset",
"b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) # Create buttons with a horizontal configuration elif orientation == \"horizontal\":",
"+ self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection",
"else: surf.fill(self._backgroundColor) # Blit the widget layer onto the back surface surfBack.blit(surf, (self._borderWidth,",
"selection, closeOnPress, toggleText = button if closeOnPress: self.close() if toggleText[0] != None: currentText",
"pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor) # Draw the background surf = pygame.Surface((self._width - (self._borderWidth *",
"self._buttons: b[0].draw(screen) def createDisplay(self): \"\"\"Create the display of the menu\"\"\" # Draw the",
"the button attributes padding - (horizontal, vertical) padding between border and buttons spacing",
"border and buttons spacing - space in pixels between buttons color - rgb",
"as a pygame font orientation - \"vertical\" | \"horizontal\" \"\"\" import pygame from",
"(width, height) pixels of the menu commands - list of dictionaries specifying the",
"color - rgb color of the menu background (None for transparent) borderColor -",
"(x*buttonHeight) + \\ (x*spacing) + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]),",
"menu commands - list of dictionaries specifying the button attributes padding - (horizontal,",
"commands - list of dictionaries specifying the button attributes padding - (horizontal, vertical)",
"buttonWidth = self._width - (2*h_padding) - (2*borderWidth) buttonHeight = (self._height - (2*v_padding) -",
"b._text if toggleText[0] == currentText: b.setText(toggleText[1]) else: b.setText(toggleText[0]) self._selection = selection def getSelection(self):",
"horizontal configuration elif orientation == \"horizontal\": buttonWidth = (self._width - (2*h_padding) - \\",
"in the menu\"\"\" return self._buttons[position][0] def handleEvent(self, event): \"\"\"Handles events on the pause",
"in self._buttons: b[0].handleEvent(event,self.select,(b,)) return self.getSelection() def select(self, button): \"\"\"Sets the current selection\"\"\" b,",
"surf = pygame.Surface((self._width - (self._borderWidth * 2), self._height - (self._borderWidth * 2))) #",
"None return sel def draw(self, screen): \"\"\"Draws the menu on the screen\"\"\" super().draw(screen)",
"- (2*h_padding) - (2*borderWidth) buttonHeight = (self._height - (2*v_padding) - \\ ((n-1)*spacing) -",
"menu\"\"\" return self._buttons[position][0] def handleEvent(self, event): \"\"\"Handles events on the pause menu\"\"\" for",
"\"\"\" import pygame from polybius.graphics.components import Button from polybius.graphics.basics.drawable import Drawable from polybius.graphics.utils.window",
"- (width, height) pixels of the menu commands - list of dictionaries specifying",
"* 2))) # Apply the background color or make transparent if self._backgroundColor ==",
"toggleText[0] != None: currentText = b._text if toggleText[0] == currentText: b.setText(toggleText[1]) else: b.setText(toggleText[0])",
"def draw(self, screen): \"\"\"Draws the menu on the screen\"\"\" super().draw(screen) # Draw buttons",
"buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) # Create buttons with a horizontal configuration",
"Drawable from polybius.graphics.utils.window import Window class Menu(Drawable, Window): def __init__(self, pos, dims, commands,",
"Window): def __init__(self, pos, dims, commands, padding=0, spacing=0, color=(80,80,80), borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes",
"= pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0] +\\ (x*buttonWidth) + (x*spacing), yStart +",
"b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection = None self.createDisplay() def getButtonByText(self, text): \"\"\"Return the button with",
"text): \"\"\"Return the button with the provided text\"\"\" for button in self._buttons: if",
"\"\"\"Initializes the menu\"\"\" Drawable.__init__(self, \"\", pos, worldBound=False) Window.__init__(self) self._offset = (pos[0], pos[1]) self._width",
"b[0].draw(screen) def createDisplay(self): \"\"\"Create the display of the menu\"\"\" # Draw the border",
"<NAME> File: menu.py A general class for creating menus Parameters: pos - (x,y)",
"(2*v_padding) - (2*borderWidth) for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"],",
"background (None for transparent) borderColor - rgb color value for border borderWidth -",
"vertical configuration if orientation == \"vertical\": buttonWidth = self._width - (2*h_padding) - (2*borderWidth)",
"pygame from polybius.graphics.components import Button from polybius.graphics.basics.drawable import Drawable from polybius.graphics.utils.window import Window",
"from polybius.graphics.utils.window import Window class Menu(Drawable, Window): def __init__(self, pos, dims, commands, padding=0,",
"= self._height - (2*v_padding) - (2*borderWidth) for x, b in enumerate(commands): font =",
"spacing=0, color=(80,80,80), borderColor=(0,0,0), borderWidth=2, orientation=\"vertical\"): \"\"\"Initializes the menu\"\"\" Drawable.__init__(self, \"\", pos, worldBound=False) Window.__init__(self)",
"b, selection, closeOnPress, toggleText = button if closeOnPress: self.close() if toggleText[0] != None:",
"between buttons color - rgb color of the menu background (None for transparent)",
"surfBack = pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor) # Draw the background surf = pygame.Surface((self._width -",
"self._borderWidth = borderWidth self._backgroundColor = color n = len(commands) xStart = h_padding yStart",
"self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0] +\\ (x*buttonWidth) + (x*spacing), yStart + self._offset[1]), font, b[\"fontColor\"],",
"None: currentText = b._text if toggleText[0] == currentText: b.setText(toggleText[1]) else: b.setText(toggleText[0]) self._selection =",
"pixel width for the border font - Supplied as a pygame font orientation",
"self.createDisplay() def getButtonByText(self, text): \"\"\"Return the button with the provided text\"\"\" for button",
"(2*borderWidth)) // n buttonHeight = self._height - (2*v_padding) - (2*borderWidth) for x, b",
"xStart = h_padding yStart = v_padding self._buttons = [] # Create buttons with",
"dictionaries specifying the button attributes padding - (horizontal, vertical) padding between border and",
"b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) self._selection = None self.createDisplay() def getButtonByText(self, text): \"\"\"Return the",
"(None for transparent) borderColor - rgb color value for border borderWidth - pixel",
"padding[1] self._borderColor = borderColor self._borderWidth = borderWidth self._backgroundColor = color n = len(commands)",
"of the menu commands - list of dictionaries specifying the button attributes padding",
"borderColor self._borderWidth = borderWidth self._backgroundColor = color n = len(commands) xStart = h_padding",
"border borderWidth - pixel width for the border font - Supplied as a",
"event): \"\"\"Handles events on the pause menu\"\"\" for b in self._buttons: b[0].handleEvent(event,self.select,(b,)) return",
"= borderColor self._borderWidth = borderWidth self._backgroundColor = color n = len(commands) xStart =",
"it to None\"\"\" sel = self._selection self._selection = None return sel def draw(self,",
"closeOnPress, toggleText = button if closeOnPress: self.close() if toggleText[0] != None: currentText =",
"the widget layer onto the back surface surfBack.blit(surf, (self._borderWidth, self._borderWidth)) self._image = surfBack",
"the button with the provided text\"\"\" for button in self._buttons: if button[0].getText() ==",
"if orientation == \"vertical\": buttonWidth = self._width - (2*h_padding) - (2*borderWidth) buttonHeight =",
"the menu on the screen\"\"\" super().draw(screen) # Draw buttons for b in self._buttons:",
"- (2*borderWidth)) // n buttonHeight = self._height - (2*v_padding) - (2*borderWidth) for x,",
"Create buttons with a vertical configuration if orientation == \"vertical\": buttonWidth = self._width",
"buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"], (b.get(\"toggleText\",None),b[\"text\"]))) # Create buttons with a horizontal",
"(x*spacing), yStart + self._offset[1]), font, b[\"fontColor\"], b[\"color\"], buttonHeight, buttonWidth, b[\"borderColor\"], b[\"borderWidth\"]), x+1, b[\"closeOnPress\"],",
"v_padding self._buttons = [] # Create buttons with a vertical configuration if orientation",
"- (2*h_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n buttonHeight = self._height -",
"self._width = dims[0] self._height = dims[1] h_padding = padding[0] v_padding = padding[1] self._borderColor",
"(pos[0], pos[1]) self._width = dims[0] self._height = dims[1] h_padding = padding[0] v_padding =",
"= [] # Create buttons with a vertical configuration if orientation == \"vertical\":",
"import Drawable from polybius.graphics.utils.window import Window class Menu(Drawable, Window): def __init__(self, pos, dims,",
"import pygame from polybius.graphics.components import Button from polybius.graphics.basics.drawable import Drawable from polybius.graphics.utils.window import",
"File: menu.py A general class for creating menus Parameters: pos - (x,y) position",
"of the menu dims - (width, height) pixels of the menu commands -",
"buttons color - rgb color of the menu background (None for transparent) borderColor",
"(b.get(\"toggleText\",None),b[\"text\"]))) # Create buttons with a horizontal configuration elif orientation == \"horizontal\": buttonWidth",
"\"vertical\": buttonWidth = self._width - (2*h_padding) - (2*borderWidth) buttonHeight = (self._height - (2*v_padding)",
"= (self._width - (2*h_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) // n buttonHeight =",
"rgb color value for border borderWidth - pixel width for the border font",
"import Button from polybius.graphics.basics.drawable import Drawable from polybius.graphics.utils.window import Window class Menu(Drawable, Window):",
"for x, b in enumerate(commands): font = pygame.font.SysFont(b[\"font\"], b[\"fontSize\"]) self._buttons.append((Button(b[\"text\"], (xStart + self._offset[0],",
"= color n = len(commands) xStart = h_padding yStart = v_padding self._buttons =",
"button[0].getText() == text: return button[0] def getButtonByPosition(self, position): \"\"\"Return the button at the",
"- (2*borderWidth) buttonHeight = (self._height - (2*v_padding) - \\ ((n-1)*spacing) - (2*borderWidth)) //",
"(xStart + self._offset[0], yStart + (x*buttonHeight) + \\ (x*spacing) + self._offset[1]), font, b[\"fontColor\"],",
"# Draw the border surfBack = pygame.Surface((self._width, self._height)) surfBack.fill(self._borderColor) # Draw the background",
"- (self._borderWidth * 2), self._height - (self._borderWidth * 2))) # Apply the background"
] |
[
"gravity\", \"SRM\" : \"standard reference method\", \"t/h\" : \"tons per hour\", \"TA\" :",
"\"POST\"]) @login_required @adminRequired def editUnitOfMeasurement(unitOfMeasurementId): operation = \"Edit\" unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form =",
"@adminRequired def editUnitOfMeasurement(unitOfMeasurementId): operation = \"Edit\" unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form = UnitOfMeasurementForm(obj =",
"import adminRequired from .. models import UnitOfMeasurement modelName = \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods =",
"degree of fermentation\", \"bbl\" : \"barrel\", \"cells/ml\" : \"cells per milliliter\", \"cells/ml/°P\" :",
": \"potential of hydrogen\", \"lb\" : \"pound\", \"lb/bbl\" : \"pounds per barrel\", \"psi\"",
"addedUnits.append(defaultUnits[defaultUnit]) unit = UnitOfMeasurement(Abbreviation = defaultUnit) unit.Name = defaultUnits[defaultUnit] db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit()",
"\"\" if skippedUnits: for unit in skippedUnits: if skippedMessage == \"\": skippedMessage =",
"\"mg\" : \"milligram\", \"mL\" : \"milliliter\", \"mm\" : \"millimeter\", \"min\" : \"minute\", \"ppb\"",
"\"ppb\" : \"parts per billion\", \"ppm\" : \"parts per million\", \"%\" : \"percentage\",",
"addedMessage = \"{}, {}\".format(addedMessage, unit) addedMessage = \"{}.\".format(addedMessage) else: addedMessage = \"Added none",
"else: addedMessage = \"{}, {}\".format(addedMessage, unit) addedMessage = \"{}.\".format(addedMessage) else: addedMessage = \"Added",
"class = \\\"glyphicon glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form, modelName",
"\"grams per liter\", \"h\" : \"hour\", \"in\" : \"inches\", \"IBU\" : \"international bittering",
"Present a form to add a new unit of measurement. breadcrumbs = [{\"url\"",
". import unitOfMeasurements from . forms import UnitOfMeasurementForm from .. import db from",
": url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\", breadcrumbs =",
"= \"Added: {}\".format(unit) alert = \"alert alert-success\" else: addedMessage = \"{}, {}\".format(addedMessage, unit)",
"= \"alert alert-warning\" if addedUnits: for unit in addedUnits: if addedMessage == \"\":",
"methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addDefaultUnitsOfMeasurements(): defaultUnits = {\"ASBC\" : \"american",
": \"inches\", \"IBU\" : \"international bittering unit\", \"kg\" : \"kilogram\", \"L\" : \"liters\",",
"operation = \"Add\" form = UnitOfMeasurementForm() # Add a new unit of measurement.",
"@login_required @adminRequired def addUnitOfMeasurement(): operation = \"Add\" form = UnitOfMeasurementForm() # Add a",
"hour\", \"TA\" : \"total acidity\", \"vol\" : \"volumes\", \"x10^12 cells\" : \"x10^12 cells\",",
"skippedMessage = \"{} as they already exist.\".format(skippedMessage) flash(skippedMessage, \"alert alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\",",
"flash('You have successfully deleted the unit of measurement \"' + unitOfMeasurement.Abbreviation + '\".',",
"from flask_login import login_required from sqlalchemy import and_ from . import unitOfMeasurements from",
"skippedMessage = \"Skipped: {}\".format(unit) else: skippedMessage = \"{}, {}\".format(skippedMessage, unit) skippedMessage = \"{}",
"unit of measurement. form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data = unitOfMeasurement.Abbreviation form.name.data = unitOfMeasurement.Name breadcrumbs",
": \"parts per million\", \"%\" : \"percentage\", \"pH\" : \"potential of hydrogen\", \"lb\"",
"addedUnits: if addedMessage == \"\": addedMessage = \"Added: {}\".format(unit) alert = \"alert alert-success\"",
"= breadcrumbs, form = form, modelName = modelName, operation = operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods",
"\"european brewery convention\", \"gal\" : \"gallon\", \"gpm\" : \"gallons per minute\", \"g\" :",
"unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data = unitOfMeasurement.Abbreviation form.name.data = unitOfMeasurement.Name breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\"",
"render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements = unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addUnitOfMeasurement():",
"\"{}\" is referenced by one or more element and/or event frame attribute template",
"milliliter\", \"cells/ml/°P\" : \"cells per ml per degree plato\", \"°C\" : \"degree celsius\",",
"\"inches\", \"IBU\" : \"international bittering unit\", \"kg\" : \"kilogram\", \"L\" : \"liters\", \"mg\"",
"= \\\"glyphicon glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form, modelName =",
": \"pounds per square inch\", \"RDF\" : \"real degree of fermentation\", \"RE\" :",
"breadcrumbs = breadcrumbs, form = form, modelName = modelName, operation = operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\",",
"and_ from . import unitOfMeasurements from . forms import UnitOfMeasurementForm from .. import",
"chemists\", \"ADF\" : \"apparent degree of fermentation\", \"bbl\" : \"barrel\", \"cells/ml\" : \"cells",
"\"barrel\", \"cells/ml\" : \"cells per milliliter\", \"cells/ml/°P\" : \"cells per ml per degree",
": \"cells per ml per degree plato\", \"°C\" : \"degree celsius\", \"°P\" :",
"per minute\", \"EBC\" : \"european brewery convention\", \"gal\" : \"gallon\", \"gpm\" : \"gallons",
"none of the default units of measurements.\" flash(addedMessage, alert) skippedMessage = \"\" if",
"\"POST\"]) @login_required @adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced(): flash('Unit of Measurement",
"\"degree celsius\", \"°P\" : \"degree plato\", \"°F\" : \"degree fahrenheit\", \"°F/min\" : \"degree",
"and/or tag and cannot be deleted.'. \\ format(unitOfMeasurement.Abbreviation), \"alert alert-danger\") else: unitOfMeasurement.delete() db.session.commit()",
"== \"\": skippedMessage = \"Skipped: {}\".format(unit) else: skippedMessage = \"{}, {}\".format(skippedMessage, unit) skippedMessage",
"else: skippedMessage = \"{}, {}\".format(skippedMessage, unit) skippedMessage = \"{} as they already exist.\".format(skippedMessage)",
"if unit is None: addedUnits.append(defaultUnits[defaultUnit]) unit = UnitOfMeasurement(Abbreviation = defaultUnit) unit.Name = defaultUnits[defaultUnit]",
"# Present a form to edit an existing unit of measurement. form.unitOfMeasurementId.data =",
"\"SRM\" : \"standard reference method\", \"t/h\" : \"tons per hour\", \"TA\" : \"total",
"per liter\", \"h\" : \"hour\", \"in\" : \"inches\", \"IBU\" : \"international bittering unit\",",
"UnitOfMeasurementForm from .. import db from .. decorators import adminRequired from .. models",
": \"minute\", \"ppb\" : \"parts per billion\", \"ppm\" : \"parts per million\", \"%\"",
"\"kg\" : \"kilogram\", \"L\" : \"liters\", \"mg\" : \"milligram\", \"mL\" : \"milliliter\", \"mm\"",
"barrel\", \"psi\" : \"pounds per square inch\", \"RDF\" : \"real degree of fermentation\",",
"\"g/bbl\" : \"grams per barrel\", \"g/L\" : \"grams per liter\", \"h\" : \"hour\",",
"db.session.add(unitOfMeasurement) db.session.commit() flash(\"You have successfully added the new unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert",
"= UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements = unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods = [\"GET\", \"POST\"]) @login_required",
"\"\": skippedMessage = \"Skipped: {}\".format(unit) else: skippedMessage = \"{}, {}\".format(skippedMessage, unit) skippedMessage =",
"an existing unit of measurement. if form.validate_on_submit(): unitOfMeasurement.Abbreviation = form.abbreviation.data unitOfMeasurement.Name = form.name.data",
"\"international bittering unit\", \"kg\" : \"kilogram\", \"L\" : \"liters\", \"mg\" : \"milligram\", \"mL\"",
"= \"{}, {}\".format(addedMessage, unit) addedMessage = \"{}.\".format(addedMessage) else: addedMessage = \"Added none of",
"degree of fermentation\", \"RE\" : \"real extract\", \"s\" : \"second\", \"SG\" : \"specific",
"acidity\", \"vol\" : \"volumes\", \"x10^12 cells\" : \"x10^12 cells\", \"x10^6 cells\" : \"x10^6",
"and cannot be deleted.'. \\ format(unitOfMeasurement.Abbreviation), \"alert alert-danger\") else: unitOfMeasurement.delete() db.session.commit() flash('You have",
"successfully edited the unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present",
"celsius\", \"°P\" : \"degree plato\", \"°F\" : \"degree fahrenheit\", \"°F/min\" : \"degree fahrenheit",
"= defaultUnit) unit.Name = defaultUnits[defaultUnit] db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage = \"\" alert",
"[\"GET\", \"POST\"]) @login_required @adminRequired def editUnitOfMeasurement(unitOfMeasurementId): operation = \"Edit\" unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form",
"from . import unitOfMeasurements from . forms import UnitOfMeasurementForm from .. import db",
"\"alert alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId):",
"\"mL\" : \"milliliter\", \"mm\" : \"millimeter\", \"min\" : \"minute\", \"ppb\" : \"parts per",
"flask import flash, redirect, render_template, request, url_for from flask_login import login_required from sqlalchemy",
"event frame attribute template and/or tag and cannot be deleted.'. \\ format(unitOfMeasurement.Abbreviation), \"alert",
"\"g\" : \"grams\", \"g/bbl\" : \"grams per barrel\", \"g/L\" : \"grams per liter\",",
"of fermentation\", \"RE\" : \"real extract\", \"s\" : \"second\", \"SG\" : \"specific gravity\",",
"[\"GET\", \"POST\"]) @login_required @adminRequired def addDefaultUnitsOfMeasurements(): defaultUnits = {\"ASBC\" : \"american society of",
"per square inch\", \"RDF\" : \"real degree of fermentation\", \"RE\" : \"real extract\",",
"operation = \"Edit\" unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form = UnitOfMeasurementForm(obj = unitOfMeasurement) # Edit",
"addedMessage = \"\" alert = \"alert alert-warning\" if addedUnits: for unit in addedUnits:",
"a form to edit an existing unit of measurement. form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data",
"defaultUnits: unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit, UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first() if unit is None:",
"the unit of measurement \"' + unitOfMeasurement.Abbreviation + '\".', \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\"))",
"form = UnitOfMeasurementForm(obj = unitOfMeasurement) # Edit an existing unit of measurement. if",
"redirect, render_template, request, url_for from flask_login import login_required from sqlalchemy import and_ from",
"= \\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\" : None, \"text\" : unitOfMeasurement.Name}] return render_template(\"addEdit.html\", breadcrumbs =",
"request, url_for from flask_login import login_required from sqlalchemy import and_ from . import",
"import login_required from sqlalchemy import and_ from . import unitOfMeasurements from . forms",
": \"pounds per barrel\", \"psi\" : \"pounds per square inch\", \"RDF\" : \"real",
"to add a new unit of measurement. breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\"",
"= form, modelName = modelName, operation = operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods = [\"GET\", \"POST\"])",
"\"apparent degree of fermentation\", \"bbl\" : \"barrel\", \"cells/ml\" : \"cells per milliliter\", \"cells/ml/°P\"",
"per degree plato\", \"°C\" : \"degree celsius\", \"°P\" : \"degree plato\", \"°F\" :",
"edit an existing unit of measurement. form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data = unitOfMeasurement.Abbreviation form.name.data",
"\"SG\" : \"specific gravity\", \"SRM\" : \"standard reference method\", \"t/h\" : \"tons per",
"deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced(): flash('Unit of Measurement \"{}\" is referenced by",
"= UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form = UnitOfMeasurementForm(obj = unitOfMeasurement) # Edit an existing unit of",
"unitOfMeasurement.isReferenced(): flash('Unit of Measurement \"{}\" is referenced by one or more element and/or",
"Edit an existing unit of measurement. if form.validate_on_submit(): unitOfMeasurement.Abbreviation = form.abbreviation.data unitOfMeasurement.Name =",
"{}\".format(addedMessage, unit) addedMessage = \"{}.\".format(addedMessage) else: addedMessage = \"Added none of the default",
"billion\", \"ppm\" : \"parts per million\", \"%\" : \"percentage\", \"pH\" : \"potential of",
"if addedUnits: for unit in addedUnits: if addedMessage == \"\": addedMessage = \"Added:",
"url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\" : None, \"text\" :",
": \"milliliter\", \"mm\" : \"millimeter\", \"min\" : \"minute\", \"ppb\" : \"parts per billion\",",
"alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to add a new unit of",
"barrel\", \"g/L\" : \"grams per liter\", \"h\" : \"hour\", \"in\" : \"inches\", \"IBU\"",
"\"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to add a new unit",
"more element and/or event frame attribute template and/or tag and cannot be deleted.'.",
"= \"{} as they already exist.\".format(skippedMessage) flash(skippedMessage, \"alert alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods",
"element and/or event frame attribute template and/or tag and cannot be deleted.'. \\",
"new unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form",
"\"ADF\" : \"apparent degree of fermentation\", \"bbl\" : \"barrel\", \"cells/ml\" : \"cells per",
"@adminRequired def addDefaultUnitsOfMeasurements(): defaultUnits = {\"ASBC\" : \"american society of brewing chemists\", \"ADF\"",
"= \"Added none of the default units of measurements.\" flash(addedMessage, alert) skippedMessage =",
"of Measurement \"{}\" is referenced by one or more element and/or event frame",
"\"h\" : \"hour\", \"in\" : \"inches\", \"IBU\" : \"international bittering unit\", \"kg\" :",
"addedUnits = [] skippedUnits = [] for defaultUnit in defaultUnits: unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation",
"\"milligram\", \"mL\" : \"milliliter\", \"mm\" : \"millimeter\", \"min\" : \"minute\", \"ppb\" : \"parts",
"db.session.commit() flash('You have successfully deleted the unit of measurement \"' + unitOfMeasurement.Abbreviation +",
"redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def editUnitOfMeasurement(unitOfMeasurementId): operation = \"Edit\"",
"\"cells/ml\" : \"cells per milliliter\", \"cells/ml/°P\" : \"cells per ml per degree plato\",",
"@adminRequired def addUnitOfMeasurement(): operation = \"Add\" form = UnitOfMeasurementForm() # Add a new",
"\"IBU\" : \"international bittering unit\", \"kg\" : \"kilogram\", \"L\" : \"liters\", \"mg\" :",
"= form.abbreviation.data, Name = form.name.data) db.session.add(unitOfMeasurement) db.session.commit() flash(\"You have successfully added the new",
"alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def editUnitOfMeasurement(unitOfMeasurementId): operation",
"@unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addDefaultUnitsOfMeasurements(): defaultUnits = {\"ASBC\" :",
"defaultUnits = {\"ASBC\" : \"american society of brewing chemists\", \"ADF\" : \"apparent degree",
"redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to add a new unit of measurement. breadcrumbs",
"[\"GET\", \"POST\"]) @login_required @adminRequired def listUnitOfMeasurements(): unitOfMeasurements = UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements =",
"alert = \"alert alert-warning\" if addedUnits: for unit in addedUnits: if addedMessage ==",
"deleted.'. \\ format(unitOfMeasurement.Abbreviation), \"alert alert-danger\") else: unitOfMeasurement.delete() db.session.commit() flash('You have successfully deleted the",
"from .. import db from .. decorators import adminRequired from .. models import",
"render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form, modelName = modelName, operation = operation)",
": \"parts per billion\", \"ppm\" : \"parts per million\", \"%\" : \"percentage\", \"pH\"",
"unit of measurement. if form.validate_on_submit(): unitOfMeasurement.Abbreviation = form.abbreviation.data unitOfMeasurement.Name = form.name.data db.session.commit() flash(\"You",
"and/or event frame attribute template and/or tag and cannot be deleted.'. \\ format(unitOfMeasurement.Abbreviation),",
"# Add a new unit of measurement. if form.validate_on_submit(): unitOfMeasurement = UnitOfMeasurement(Abbreviation =",
"for unit in skippedUnits: if skippedMessage == \"\": skippedMessage = \"Skipped: {}\".format(unit) else:",
"\"potential of hydrogen\", \"lb\" : \"pound\", \"lb/bbl\" : \"pounds per barrel\", \"psi\" :",
"form.abbreviation.data, Name = form.name.data) db.session.add(unitOfMeasurement) db.session.commit() flash(\"You have successfully added the new unit",
"flash(skippedMessage, \"alert alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def",
"form to add a new unit of measurement. breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"),",
"square inch\", \"RDF\" : \"real degree of fermentation\", \"RE\" : \"real extract\", \"s\"",
": unitOfMeasurement.Name}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form, modelName = modelName,",
". forms import UnitOfMeasurementForm from .. import db from .. decorators import adminRequired",
"= UnitOfMeasurement(Abbreviation = form.abbreviation.data, Name = form.name.data) db.session.add(unitOfMeasurement) db.session.commit() flash(\"You have successfully added",
": \"real extract\", \"s\" : \"second\", \"SG\" : \"specific gravity\", \"SRM\" : \"standard",
"of the default units of measurements.\" flash(addedMessage, alert) skippedMessage = \"\" if skippedUnits:",
"skippedUnits: if skippedMessage == \"\": skippedMessage = \"Skipped: {}\".format(unit) else: skippedMessage = \"{},",
"# Present a form to add a new unit of measurement. breadcrumbs =",
"defaultUnit, UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first() if unit is None: addedUnits.append(defaultUnits[defaultUnit]) unit = UnitOfMeasurement(Abbreviation =",
"fahrenheit per minute\", \"EBC\" : \"european brewery convention\", \"gal\" : \"gallon\", \"gpm\" :",
"alert-success\" else: addedMessage = \"{}, {}\".format(addedMessage, unit) addedMessage = \"{}.\".format(addedMessage) else: addedMessage =",
": \"total acidity\", \"vol\" : \"volumes\", \"x10^12 cells\" : \"x10^12 cells\", \"x10^6 cells\"",
"db.session.commit() flash(\"You have successfully added the new unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\")",
"else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage = \"\" alert = \"alert alert-warning\" if addedUnits: for",
"per hour\", \"TA\" : \"total acidity\", \"vol\" : \"volumes\", \"x10^12 cells\" : \"x10^12",
"\"x10^6 cells\"} addedUnits = [] skippedUnits = [] for defaultUnit in defaultUnits: unit",
"\"s\" : \"second\", \"SG\" : \"specific gravity\", \"SRM\" : \"standard reference method\", \"t/h\"",
"{\"url\" : None, \"text\" : unitOfMeasurement.Name}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form =",
"\"t/h\" : \"tons per hour\", \"TA\" : \"total acidity\", \"vol\" : \"volumes\", \"x10^12",
"None, \"text\" : unitOfMeasurement.Name}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form, modelName",
"attribute template and/or tag and cannot be deleted.'. \\ format(unitOfMeasurement.Abbreviation), \"alert alert-danger\") else:",
"defaultUnit) unit.Name = defaultUnits[defaultUnit] db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage = \"\" alert =",
"ml per degree plato\", \"°C\" : \"degree celsius\", \"°P\" : \"degree plato\", \"°F\"",
".. models import UnitOfMeasurement modelName = \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required",
"operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addDefaultUnitsOfMeasurements(): defaultUnits = {\"ASBC\"",
"unit = UnitOfMeasurement(Abbreviation = defaultUnit) unit.Name = defaultUnits[defaultUnit] db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage",
"listUnitOfMeasurements(): unitOfMeasurements = UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements = unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods = [\"GET\",",
"\"alert alert-danger\") else: unitOfMeasurement.delete() db.session.commit() flash('You have successfully deleted the unit of measurement",
"\"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\" : None, \"text\" : unitOfMeasurement.Name}]",
"of fermentation\", \"bbl\" : \"barrel\", \"cells/ml\" : \"cells per milliliter\", \"cells/ml/°P\" : \"cells",
": \"degree fahrenheit per minute\", \"EBC\" : \"european brewery convention\", \"gal\" : \"gallon\",",
"class = \\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\" : None, \"text\" : unitOfMeasurement.Name}] return render_template(\"addEdit.html\", breadcrumbs",
"== defaultUnit, UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first() if unit is None: addedUnits.append(defaultUnits[defaultUnit]) unit = UnitOfMeasurement(Abbreviation",
"form.name.data db.session.commit() flash(\"You have successfully edited the unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\")",
": \"grams\", \"g/bbl\" : \"grams per barrel\", \"g/L\" : \"grams per liter\", \"h\"",
"Present a form to edit an existing unit of measurement. form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId",
"new unit of measurement. breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class",
"the default units of measurements.\" flash(addedMessage, alert) skippedMessage = \"\" if skippedUnits: for",
"\\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\" : None, \"text\" : unitOfMeasurement.Name}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs,",
"def editUnitOfMeasurement(unitOfMeasurementId): operation = \"Edit\" unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form = UnitOfMeasurementForm(obj = unitOfMeasurement)",
"existing unit of measurement. form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data = unitOfMeasurement.Abbreviation form.name.data = unitOfMeasurement.Name",
"cells\" : \"x10^12 cells\", \"x10^6 cells\" : \"x10^6 cells\"} addedUnits = [] skippedUnits",
"@unitOfMeasurements.route(\"/unitOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def listUnitOfMeasurements(): unitOfMeasurements = UnitOfMeasurement.query return",
"breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\"",
"existing unit of measurement. if form.validate_on_submit(): unitOfMeasurement.Abbreviation = form.abbreviation.data unitOfMeasurement.Name = form.name.data db.session.commit()",
"\"mm\" : \"millimeter\", \"min\" : \"minute\", \"ppb\" : \"parts per billion\", \"ppm\" :",
"for unit in addedUnits: if addedMessage == \"\": addedMessage = \"Added: {}\".format(unit) alert",
"successfully added the new unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) #",
"\"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def listUnitOfMeasurements(): unitOfMeasurements = UnitOfMeasurement.query",
"[{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\" : None,",
"template and/or tag and cannot be deleted.'. \\ format(unitOfMeasurement.Abbreviation), \"alert alert-danger\") else: unitOfMeasurement.delete()",
"unit of measurement \"' + unitOfMeasurement.Abbreviation + '\".', \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\",",
"\"gpm\" : \"gallons per minute\", \"g\" : \"grams\", \"g/bbl\" : \"grams per barrel\",",
"= modelName, operation = operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def",
"breadcrumbs, form = form, modelName = modelName, operation = operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods =",
"\"{}.\".format(addedMessage) else: addedMessage = \"Added none of the default units of measurements.\" flash(addedMessage,",
"= UnitOfMeasurementForm() # Add a new unit of measurement. if form.validate_on_submit(): unitOfMeasurement =",
": None, \"text\" : unitOfMeasurement.Name}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form,",
"= [\"GET\", \"POST\"]) @login_required @adminRequired def addDefaultUnitsOfMeasurements(): defaultUnits = {\"ASBC\" : \"american society",
"unitOfMeasurement.delete() db.session.commit() flash('You have successfully deleted the unit of measurement \"' + unitOfMeasurement.Abbreviation",
"from .. models import UnitOfMeasurement modelName = \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods = [\"GET\", \"POST\"])",
"decorators import adminRequired from .. models import UnitOfMeasurement modelName = \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods",
"@unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if",
"by one or more element and/or event frame attribute template and/or tag and",
"methods = [\"GET\", \"POST\"]) @login_required @adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced():",
"\"kilogram\", \"L\" : \"liters\", \"mg\" : \"milligram\", \"mL\" : \"milliliter\", \"mm\" : \"millimeter\",",
"fahrenheit\", \"°F/min\" : \"degree fahrenheit per minute\", \"EBC\" : \"european brewery convention\", \"gal\"",
"defaultUnit in defaultUnits: unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit, UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first() if unit",
"redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to edit an existing unit of measurement. form.unitOfMeasurementId.data",
"per billion\", \"ppm\" : \"parts per million\", \"%\" : \"percentage\", \"pH\" : \"potential",
".. import db from .. decorators import adminRequired from .. models import UnitOfMeasurement",
"UnitOfMeasurement(Abbreviation = defaultUnit) unit.Name = defaultUnits[defaultUnit] db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage = \"\"",
": \"hour\", \"in\" : \"inches\", \"IBU\" : \"international bittering unit\", \"kg\" : \"kilogram\",",
"defaultUnits[defaultUnit] db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage = \"\" alert = \"alert alert-warning\" if",
": \"grams per liter\", \"h\" : \"hour\", \"in\" : \"inches\", \"IBU\" : \"international",
"successfully deleted the unit of measurement \"' + unitOfMeasurement.Abbreviation + '\".', \"alert alert-success\")",
": \"volumes\", \"x10^12 cells\" : \"x10^12 cells\", \"x10^6 cells\" : \"x10^6 cells\"} addedUnits",
"\"x10^6 cells\" : \"x10^6 cells\"} addedUnits = [] skippedUnits = [] for defaultUnit",
"\"american society of brewing chemists\", \"ADF\" : \"apparent degree of fermentation\", \"bbl\" :",
"measurement. form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data = unitOfMeasurement.Abbreviation form.name.data = unitOfMeasurement.Name breadcrumbs = [{\"url\"",
"db from .. decorators import adminRequired from .. models import UnitOfMeasurement modelName =",
"{\"ASBC\" : \"american society of brewing chemists\", \"ADF\" : \"apparent degree of fermentation\",",
"Add a new unit of measurement. if form.validate_on_submit(): unitOfMeasurement = UnitOfMeasurement(Abbreviation = form.abbreviation.data,",
"as they already exist.\".format(skippedMessage) flash(skippedMessage, \"alert alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods = [\"GET\",",
"addedUnits: for unit in addedUnits: if addedMessage == \"\": addedMessage = \"Added: {}\".format(unit)",
"\"x10^12 cells\" : \"x10^12 cells\", \"x10^6 cells\" : \"x10^6 cells\"} addedUnits = []",
"\\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to add a new",
"\"total acidity\", \"vol\" : \"volumes\", \"x10^12 cells\" : \"x10^12 cells\", \"x10^6 cells\" :",
"@adminRequired def listUnitOfMeasurements(): unitOfMeasurements = UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements = unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods",
": \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form =",
"= unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addUnitOfMeasurement(): operation =",
"of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to edit",
"form = form, modelName = modelName, operation = operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods = [\"GET\",",
"\"grams\", \"g/bbl\" : \"grams per barrel\", \"g/L\" : \"grams per liter\", \"h\" :",
"alert-danger\") else: unitOfMeasurement.delete() db.session.commit() flash('You have successfully deleted the unit of measurement \"'",
"addUnitOfMeasurement(): operation = \"Add\" form = UnitOfMeasurementForm() # Add a new unit of",
"\"vol\" : \"volumes\", \"x10^12 cells\" : \"x10^12 cells\", \"x10^6 cells\" : \"x10^6 cells\"}",
"= \"Skipped: {}\".format(unit) else: skippedMessage = \"{}, {}\".format(skippedMessage, unit) skippedMessage = \"{} as",
": url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\" : None, \"text\"",
"import flash, redirect, render_template, request, url_for from flask_login import login_required from sqlalchemy import",
"\"bbl\" : \"barrel\", \"cells/ml\" : \"cells per milliliter\", \"cells/ml/°P\" : \"cells per ml",
"already exist.\".format(skippedMessage) flash(skippedMessage, \"alert alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required",
"\"text\" : unitOfMeasurement.Name}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form, modelName =",
"\"pounds per barrel\", \"psi\" : \"pounds per square inch\", \"RDF\" : \"real degree",
": \"international bittering unit\", \"kg\" : \"kilogram\", \"L\" : \"liters\", \"mg\" : \"milligram\",",
"\"gallons per minute\", \"g\" : \"grams\", \"g/bbl\" : \"grams per barrel\", \"g/L\" :",
"per ml per degree plato\", \"°C\" : \"degree celsius\", \"°P\" : \"degree plato\",",
"per milliliter\", \"cells/ml/°P\" : \"cells per ml per degree plato\", \"°C\" : \"degree",
"flask_login import login_required from sqlalchemy import and_ from . import unitOfMeasurements from .",
"convention\", \"gal\" : \"gallon\", \"gpm\" : \"gallons per minute\", \"g\" : \"grams\", \"g/bbl\"",
"render_template, request, url_for from flask_login import login_required from sqlalchemy import and_ from .",
"== defaultUnits[defaultUnit])).first() if unit is None: addedUnits.append(defaultUnits[defaultUnit]) unit = UnitOfMeasurement(Abbreviation = defaultUnit) unit.Name",
"UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form = UnitOfMeasurementForm(obj = unitOfMeasurement) # Edit an existing unit of measurement.",
"= \"Edit\" unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form = UnitOfMeasurementForm(obj = unitOfMeasurement) # Edit an",
"redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId)",
"{}\".format(skippedMessage, unit) skippedMessage = \"{} as they already exist.\".format(skippedMessage) flash(skippedMessage, \"alert alert-warning\") return",
"\"standard reference method\", \"t/h\" : \"tons per hour\", \"TA\" : \"total acidity\", \"vol\"",
": \"cells per milliliter\", \"cells/ml/°P\" : \"cells per ml per degree plato\", \"°C\"",
"+ '\".', \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired",
"def addDefaultUnitsOfMeasurements(): defaultUnits = {\"ASBC\" : \"american society of brewing chemists\", \"ADF\" :",
"cells\"} addedUnits = [] skippedUnits = [] for defaultUnit in defaultUnits: unit =",
": \"tons per hour\", \"TA\" : \"total acidity\", \"vol\" : \"volumes\", \"x10^12 cells\"",
"skippedMessage = \"{}, {}\".format(skippedMessage, unit) skippedMessage = \"{} as they already exist.\".format(skippedMessage) flash(skippedMessage,",
"\"\" alert = \"alert alert-warning\" if addedUnits: for unit in addedUnits: if addedMessage",
"= \"\" if skippedUnits: for unit in skippedUnits: if skippedMessage == \"\": skippedMessage",
"the new unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a",
"@unitOfMeasurements.route(\"/units/add\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addUnitOfMeasurement(): operation = \"Add\" form",
"unit.Name = defaultUnits[defaultUnit] db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage = \"\" alert = \"alert",
"cells\" : \"x10^6 cells\"} addedUnits = [] skippedUnits = [] for defaultUnit in",
"else: addedMessage = \"Added none of the default units of measurements.\" flash(addedMessage, alert)",
"return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def editUnitOfMeasurement(unitOfMeasurementId): operation =",
"added the new unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present",
"form, modelName = modelName, operation = operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required",
"of measurement. if form.validate_on_submit(): unitOfMeasurement.Abbreviation = form.abbreviation.data unitOfMeasurement.Name = form.name.data db.session.commit() flash(\"You have",
"= operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addDefaultUnitsOfMeasurements(): defaultUnits =",
"models import UnitOfMeasurement modelName = \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired",
"exist.\".format(skippedMessage) flash(skippedMessage, \"alert alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired",
"unitOfMeasurements = unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addUnitOfMeasurement(): operation",
"= form.abbreviation.data unitOfMeasurement.Name = form.name.data db.session.commit() flash(\"You have successfully edited the unit of",
"= [\"GET\", \"POST\"]) @login_required @adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced(): flash('Unit",
"of brewing chemists\", \"ADF\" : \"apparent degree of fermentation\", \"bbl\" : \"barrel\", \"cells/ml\"",
": \"apparent degree of fermentation\", \"bbl\" : \"barrel\", \"cells/ml\" : \"cells per milliliter\",",
"minute\", \"EBC\" : \"european brewery convention\", \"gal\" : \"gallon\", \"gpm\" : \"gallons per",
"db.session.commit() addedMessage = \"\" alert = \"alert alert-warning\" if addedUnits: for unit in",
": \"degree celsius\", \"°P\" : \"degree plato\", \"°F\" : \"degree fahrenheit\", \"°F/min\" :",
"breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}] return",
": \"gallon\", \"gpm\" : \"gallons per minute\", \"g\" : \"grams\", \"g/bbl\" : \"grams",
"= [\"GET\", \"POST\"]) @login_required @adminRequired def editUnitOfMeasurement(unitOfMeasurementId): operation = \"Edit\" unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId)",
"unitOfMeasurement) # Edit an existing unit of measurement. if form.validate_on_submit(): unitOfMeasurement.Abbreviation = form.abbreviation.data",
"\"real degree of fermentation\", \"RE\" : \"real extract\", \"s\" : \"second\", \"SG\" :",
"in skippedUnits: if skippedMessage == \"\": skippedMessage = \"Skipped: {}\".format(unit) else: skippedMessage =",
"Name = form.name.data) db.session.add(unitOfMeasurement) db.session.commit() flash(\"You have successfully added the new unit of",
"= [\"GET\", \"POST\"]) @login_required @adminRequired def listUnitOfMeasurements(): unitOfMeasurements = UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements",
"unitOfMeasurement.Name}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form, modelName = modelName, operation",
"[] skippedUnits = [] for defaultUnit in defaultUnits: unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit,",
"unit in skippedUnits: if skippedMessage == \"\": skippedMessage = \"Skipped: {}\".format(unit) else: skippedMessage",
"alert = \"alert alert-success\" else: addedMessage = \"{}, {}\".format(addedMessage, unit) addedMessage = \"{}.\".format(addedMessage)",
"default units of measurements.\" flash(addedMessage, alert) skippedMessage = \"\" if skippedUnits: for unit",
"flash(\"You have successfully added the new unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return",
"unitOfMeasurements from . forms import UnitOfMeasurementForm from .. import db from .. decorators",
"a form to add a new unit of measurement. breadcrumbs = [{\"url\" :",
"if addedMessage == \"\": addedMessage = \"Added: {}\".format(unit) alert = \"alert alert-success\" else:",
"plato\", \"°F\" : \"degree fahrenheit\", \"°F/min\" : \"degree fahrenheit per minute\", \"EBC\" :",
"\"°F/min\" : \"degree fahrenheit per minute\", \"EBC\" : \"european brewery convention\", \"gal\" :",
"\"L\" : \"liters\", \"mg\" : \"milligram\", \"mL\" : \"milliliter\", \"mm\" : \"millimeter\", \"min\"",
"edited the unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a",
"\"POST\"]) @login_required @adminRequired def addDefaultUnitsOfMeasurements(): defaultUnits = {\"ASBC\" : \"american society of brewing",
"\"milliliter\", \"mm\" : \"millimeter\", \"min\" : \"minute\", \"ppb\" : \"parts per billion\", \"ppm\"",
"return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to edit an existing unit of measurement.",
"= \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def listUnitOfMeasurements(): unitOfMeasurements =",
"\"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def editUnitOfMeasurement(unitOfMeasurementId):",
"\\ format(unitOfMeasurement.Abbreviation), \"alert alert-danger\") else: unitOfMeasurement.delete() db.session.commit() flash('You have successfully deleted the unit",
"return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement =",
"= UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit, UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first() if unit is None: addedUnits.append(defaultUnits[defaultUnit]) unit",
"form.name.data = unitOfMeasurement.Name breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class =",
"def listUnitOfMeasurements(): unitOfMeasurements = UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements = unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods =",
"def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced(): flash('Unit of Measurement \"{}\" is referenced",
"extract\", \"s\" : \"second\", \"SG\" : \"specific gravity\", \"SRM\" : \"standard reference method\",",
"if form.validate_on_submit(): unitOfMeasurement.Abbreviation = form.abbreviation.data unitOfMeasurement.Name = form.name.data db.session.commit() flash(\"You have successfully edited",
": \"milligram\", \"mL\" : \"milliliter\", \"mm\" : \"millimeter\", \"min\" : \"minute\", \"ppb\" :",
": \"standard reference method\", \"t/h\" : \"tons per hour\", \"TA\" : \"total acidity\",",
"form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data = unitOfMeasurement.Abbreviation form.name.data = unitOfMeasurement.Name breadcrumbs = [{\"url\" :",
"\"cells per milliliter\", \"cells/ml/°P\" : \"cells per ml per degree plato\", \"°C\" :",
"unit\", \"kg\" : \"kilogram\", \"L\" : \"liters\", \"mg\" : \"milligram\", \"mL\" : \"milliliter\",",
"add a new unit of measurement. breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" :",
"\"°P\" : \"degree plato\", \"°F\" : \"degree fahrenheit\", \"°F/min\" : \"degree fahrenheit per",
"measurement. breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}]",
"\"{}, {}\".format(skippedMessage, unit) skippedMessage = \"{} as they already exist.\".format(skippedMessage) flash(skippedMessage, \"alert alert-warning\")",
"\"specific gravity\", \"SRM\" : \"standard reference method\", \"t/h\" : \"tons per hour\", \"TA\"",
"have successfully edited the unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) #",
"from sqlalchemy import and_ from . import unitOfMeasurements from . forms import UnitOfMeasurementForm",
"alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to edit an existing unit of",
": \"pound\", \"lb/bbl\" : \"pounds per barrel\", \"psi\" : \"pounds per square inch\",",
"minute\", \"g\" : \"grams\", \"g/bbl\" : \"grams per barrel\", \"g/L\" : \"grams per",
"= unitOfMeasurement.Name breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon",
"import UnitOfMeasurement modelName = \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def",
"alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement",
"of measurement. form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data = unitOfMeasurement.Abbreviation form.name.data = unitOfMeasurement.Name breadcrumbs =",
"\"POST\"]) @login_required @adminRequired def addUnitOfMeasurement(): operation = \"Add\" form = UnitOfMeasurementForm() # Add",
"per barrel\", \"psi\" : \"pounds per square inch\", \"RDF\" : \"real degree of",
"modelName = \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def listUnitOfMeasurements(): unitOfMeasurements",
": \"percentage\", \"pH\" : \"potential of hydrogen\", \"lb\" : \"pound\", \"lb/bbl\" : \"pounds",
"bittering unit\", \"kg\" : \"kilogram\", \"L\" : \"liters\", \"mg\" : \"milligram\", \"mL\" :",
"methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addUnitOfMeasurement(): operation = \"Add\" form =",
"addedMessage = \"{}.\".format(addedMessage) else: addedMessage = \"Added none of the default units of",
"measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to add a",
": \"real degree of fermentation\", \"RE\" : \"real extract\", \"s\" : \"second\", \"SG\"",
"[] for defaultUnit in defaultUnits: unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit, UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first()",
"\"pounds per square inch\", \"RDF\" : \"real degree of fermentation\", \"RE\" : \"real",
"addedMessage = \"Added: {}\".format(unit) alert = \"alert alert-success\" else: addedMessage = \"{}, {}\".format(addedMessage,",
"return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form, modelName = modelName, operation =",
"unit) skippedMessage = \"{} as they already exist.\".format(skippedMessage) flash(skippedMessage, \"alert alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\"))",
"defaultUnits[defaultUnit])).first() if unit is None: addedUnits.append(defaultUnits[defaultUnit]) unit = UnitOfMeasurement(Abbreviation = defaultUnit) unit.Name =",
"= unitOfMeasurement.Abbreviation form.name.data = unitOfMeasurement.Name breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span",
"cells\", \"x10^6 cells\" : \"x10^6 cells\"} addedUnits = [] skippedUnits = [] for",
"= \"alert alert-success\" else: addedMessage = \"{}, {}\".format(addedMessage, unit) addedMessage = \"{}.\".format(addedMessage) else:",
"[\"GET\", \"POST\"]) @login_required @adminRequired def addUnitOfMeasurement(): operation = \"Add\" form = UnitOfMeasurementForm() #",
"= defaultUnits[defaultUnit] db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage = \"\" alert = \"alert alert-warning\"",
"UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit, UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first() if unit is None: addedUnits.append(defaultUnits[defaultUnit]) unit =",
"they already exist.\".format(skippedMessage) flash(skippedMessage, \"alert alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"])",
"measurements.\" flash(addedMessage, alert) skippedMessage = \"\" if skippedUnits: for unit in skippedUnits: if",
"\"parts per million\", \"%\" : \"percentage\", \"pH\" : \"potential of hydrogen\", \"lb\" :",
"\"cells/ml/°P\" : \"cells per ml per degree plato\", \"°C\" : \"degree celsius\", \"°P\"",
": \"american society of brewing chemists\", \"ADF\" : \"apparent degree of fermentation\", \"bbl\"",
": \"european brewery convention\", \"gal\" : \"gallon\", \"gpm\" : \"gallons per minute\", \"g\"",
"= [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\" :",
"measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to edit an",
".. decorators import adminRequired from .. models import UnitOfMeasurement modelName = \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\",",
"# Edit an existing unit of measurement. if form.validate_on_submit(): unitOfMeasurement.Abbreviation = form.abbreviation.data unitOfMeasurement.Name",
"db.session.commit() flash(\"You have successfully edited the unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return",
": \"barrel\", \"cells/ml\" : \"cells per milliliter\", \"cells/ml/°P\" : \"cells per ml per",
"flash(\"You have successfully edited the unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\"))",
"society of brewing chemists\", \"ADF\" : \"apparent degree of fermentation\", \"bbl\" : \"barrel\",",
"\"degree fahrenheit per minute\", \"EBC\" : \"european brewery convention\", \"gal\" : \"gallon\", \"gpm\"",
": \"millimeter\", \"min\" : \"minute\", \"ppb\" : \"parts per billion\", \"ppm\" : \"parts",
"== \"\": addedMessage = \"Added: {}\".format(unit) alert = \"alert alert-success\" else: addedMessage =",
"\"degree plato\", \"°F\" : \"degree fahrenheit\", \"°F/min\" : \"degree fahrenheit per minute\", \"EBC\"",
"from . forms import UnitOfMeasurementForm from .. import db from .. decorators import",
"\"second\", \"SG\" : \"specific gravity\", \"SRM\" : \"standard reference method\", \"t/h\" : \"tons",
"glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form, modelName = modelName, operation",
"\"POST\"]) @login_required @adminRequired def listUnitOfMeasurements(): unitOfMeasurements = UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements = unitOfMeasurements)",
"from .. decorators import adminRequired from .. models import UnitOfMeasurement modelName = \"Unit\"",
"\"real extract\", \"s\" : \"second\", \"SG\" : \"specific gravity\", \"SRM\" : \"standard reference",
"'\".', \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def",
"addedMessage == \"\": addedMessage = \"Added: {}\".format(unit) alert = \"alert alert-success\" else: addedMessage",
": \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\" : None, \"text\" : unitOfMeasurement.Name}] return",
"skippedMessage = \"\" if skippedUnits: for unit in skippedUnits: if skippedMessage == \"\":",
"\"parts per billion\", \"ppm\" : \"parts per million\", \"%\" : \"percentage\", \"pH\" :",
"unitOfMeasurement.Name breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"},",
"= [] for defaultUnit in defaultUnits: unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit, UnitOfMeasurement.Name ==",
"None: addedUnits.append(defaultUnits[defaultUnit]) unit = UnitOfMeasurement(Abbreviation = defaultUnit) unit.Name = defaultUnits[defaultUnit] db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit])",
"\"min\" : \"minute\", \"ppb\" : \"parts per billion\", \"ppm\" : \"parts per million\",",
"tag and cannot be deleted.'. \\ format(unitOfMeasurement.Abbreviation), \"alert alert-danger\") else: unitOfMeasurement.delete() db.session.commit() flash('You",
"\"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to edit an existing unit",
"for defaultUnit in defaultUnits: unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit, UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first() if",
"if unitOfMeasurement.isReferenced(): flash('Unit of Measurement \"{}\" is referenced by one or more element",
"skippedUnits: for unit in skippedUnits: if skippedMessage == \"\": skippedMessage = \"Skipped: {}\".format(unit)",
"skippedUnits = [] for defaultUnit in defaultUnits: unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit, UnitOfMeasurement.Name",
"in addedUnits: if addedMessage == \"\": addedMessage = \"Added: {}\".format(unit) alert = \"alert",
"\"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form",
"+ unitOfMeasurement.Abbreviation + '\".', \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"])",
"[{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\", breadcrumbs",
"\"cells per ml per degree plato\", \"°C\" : \"degree celsius\", \"°P\" : \"degree",
"\"°F\" : \"degree fahrenheit\", \"°F/min\" : \"degree fahrenheit per minute\", \"EBC\" : \"european",
"\"Added: {}\".format(unit) alert = \"alert alert-success\" else: addedMessage = \"{}, {}\".format(addedMessage, unit) addedMessage",
"to edit an existing unit of measurement. form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data = unitOfMeasurement.Abbreviation",
"url_for from flask_login import login_required from sqlalchemy import and_ from . import unitOfMeasurements",
"editUnitOfMeasurement(unitOfMeasurementId): operation = \"Edit\" unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form = UnitOfMeasurementForm(obj = unitOfMeasurement) #",
"modelName = modelName, operation = operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired",
"of hydrogen\", \"lb\" : \"pound\", \"lb/bbl\" : \"pounds per barrel\", \"psi\" : \"pounds",
"measurement. if form.validate_on_submit(): unitOfMeasurement.Abbreviation = form.abbreviation.data unitOfMeasurement.Name = form.name.data db.session.commit() flash(\"You have successfully",
"forms import UnitOfMeasurementForm from .. import db from .. decorators import adminRequired from",
": \"degree fahrenheit\", \"°F/min\" : \"degree fahrenheit per minute\", \"EBC\" : \"european brewery",
"unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit, UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first() if unit is None: addedUnits.append(defaultUnits[defaultUnit])",
": \"gallons per minute\", \"g\" : \"grams\", \"g/bbl\" : \"grams per barrel\", \"g/L\"",
"\"pH\" : \"potential of hydrogen\", \"lb\" : \"pound\", \"lb/bbl\" : \"pounds per barrel\",",
"login_required from sqlalchemy import and_ from . import unitOfMeasurements from . forms import",
"unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced(): flash('Unit of Measurement \"{}\" is referenced by one",
"def addUnitOfMeasurement(): operation = \"Add\" form = UnitOfMeasurementForm() # Add a new unit",
"@login_required @adminRequired def addDefaultUnitsOfMeasurements(): defaultUnits = {\"ASBC\" : \"american society of brewing chemists\",",
": \"grams per barrel\", \"g/L\" : \"grams per liter\", \"h\" : \"hour\", \"in\"",
"of measurements.\" flash(addedMessage, alert) skippedMessage = \"\" if skippedUnits: for unit in skippedUnits:",
"cannot be deleted.'. \\ format(unitOfMeasurement.Abbreviation), \"alert alert-danger\") else: unitOfMeasurement.delete() db.session.commit() flash('You have successfully",
"unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form = UnitOfMeasurementForm(obj = unitOfMeasurement) # Edit an existing unit",
"form to edit an existing unit of measurement. form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data =",
"unit) addedMessage = \"{}.\".format(addedMessage) else: addedMessage = \"Added none of the default units",
"an existing unit of measurement. form.unitOfMeasurementId.data = unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data = unitOfMeasurement.Abbreviation form.name.data =",
": \"liters\", \"mg\" : \"milligram\", \"mL\" : \"milliliter\", \"mm\" : \"millimeter\", \"min\" :",
"deleted the unit of measurement \"' + unitOfMeasurement.Abbreviation + '\".', \"alert alert-success\") return",
"reference method\", \"t/h\" : \"tons per hour\", \"TA\" : \"total acidity\", \"vol\" :",
"\"{} as they already exist.\".format(skippedMessage) flash(skippedMessage, \"alert alert-warning\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/delete/<int:unitOfMeasurementId>\", methods =",
"UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced(): flash('Unit of Measurement \"{}\" is referenced by one or more",
": \"x10^6 cells\"} addedUnits = [] skippedUnits = [] for defaultUnit in defaultUnits:",
"form.abbreviation.data unitOfMeasurement.Name = form.name.data db.session.commit() flash(\"You have successfully edited the unit of measurement",
"skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage = \"\" alert = \"alert alert-warning\" if addedUnits: for unit",
"\"Skipped: {}\".format(unit) else: skippedMessage = \"{}, {}\".format(skippedMessage, unit) skippedMessage = \"{} as they",
"form.validate_on_submit(): unitOfMeasurement.Abbreviation = form.abbreviation.data unitOfMeasurement.Name = form.name.data db.session.commit() flash(\"You have successfully edited the",
"\"percentage\", \"pH\" : \"potential of hydrogen\", \"lb\" : \"pound\", \"lb/bbl\" : \"pounds per",
"addedMessage = \"Added none of the default units of measurements.\" flash(addedMessage, alert) skippedMessage",
"plato\", \"°C\" : \"degree celsius\", \"°P\" : \"degree plato\", \"°F\" : \"degree fahrenheit\",",
"form = UnitOfMeasurementForm() # Add a new unit of measurement. if form.validate_on_submit(): unitOfMeasurement",
"degree plato\", \"°C\" : \"degree celsius\", \"°P\" : \"degree plato\", \"°F\" : \"degree",
"\"%\" : \"percentage\", \"pH\" : \"potential of hydrogen\", \"lb\" : \"pound\", \"lb/bbl\" :",
"measurement. if form.validate_on_submit(): unitOfMeasurement = UnitOfMeasurement(Abbreviation = form.abbreviation.data, Name = form.name.data) db.session.add(unitOfMeasurement) db.session.commit()",
"UnitOfMeasurementForm() # Add a new unit of measurement. if form.validate_on_submit(): unitOfMeasurement = UnitOfMeasurement(Abbreviation",
"\"lb/bbl\" : \"pounds per barrel\", \"psi\" : \"pounds per square inch\", \"RDF\" :",
": \"kilogram\", \"L\" : \"liters\", \"mg\" : \"milligram\", \"mL\" : \"milliliter\", \"mm\" :",
"\"alert alert-success\" else: addedMessage = \"{}, {}\".format(addedMessage, unit) addedMessage = \"{}.\".format(addedMessage) else: addedMessage",
"@adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced(): flash('Unit of Measurement \"{}\" is",
"liter\", \"h\" : \"hour\", \"in\" : \"inches\", \"IBU\" : \"international bittering unit\", \"kg\"",
"frame attribute template and/or tag and cannot be deleted.'. \\ format(unitOfMeasurement.Abbreviation), \"alert alert-danger\")",
"Measurement \"{}\" is referenced by one or more element and/or event frame attribute",
"\"RE\" : \"real extract\", \"s\" : \"second\", \"SG\" : \"specific gravity\", \"SRM\" :",
"\"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}, {\"url\" : None, \"text\" : unitOfMeasurement.Name}] return render_template(\"addEdit.html\",",
"alert-warning\" if addedUnits: for unit in addedUnits: if addedMessage == \"\": addedMessage =",
"\"Edit\" unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form = UnitOfMeasurementForm(obj = unitOfMeasurement) # Edit an existing",
"inch\", \"RDF\" : \"real degree of fermentation\", \"RE\" : \"real extract\", \"s\" :",
"in defaultUnits: unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation == defaultUnit, UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first() if unit is",
"be deleted.'. \\ format(unitOfMeasurement.Abbreviation), \"alert alert-danger\") else: unitOfMeasurement.delete() db.session.commit() flash('You have successfully deleted",
"\"psi\" : \"pounds per square inch\", \"RDF\" : \"real degree of fermentation\", \"RE\"",
"hydrogen\", \"lb\" : \"pound\", \"lb/bbl\" : \"pounds per barrel\", \"psi\" : \"pounds per",
"\"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form,",
"\"grams per barrel\", \"g/L\" : \"grams per liter\", \"h\" : \"hour\", \"in\" :",
"have successfully deleted the unit of measurement \"' + unitOfMeasurement.Abbreviation + '\".', \"alert",
"format(unitOfMeasurement.Abbreviation), \"alert alert-danger\") else: unitOfMeasurement.delete() db.session.commit() flash('You have successfully deleted the unit of",
"= UnitOfMeasurementForm(obj = unitOfMeasurement) # Edit an existing unit of measurement. if form.validate_on_submit():",
"\"in\" : \"inches\", \"IBU\" : \"international bittering unit\", \"kg\" : \"kilogram\", \"L\" :",
"or more element and/or event frame attribute template and/or tag and cannot be",
"the unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form",
"\"ppm\" : \"parts per million\", \"%\" : \"percentage\", \"pH\" : \"potential of hydrogen\",",
"methods = [\"GET\", \"POST\"]) @login_required @adminRequired def listUnitOfMeasurements(): unitOfMeasurements = UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\",",
"if skippedMessage == \"\": skippedMessage = \"Skipped: {}\".format(unit) else: skippedMessage = \"{}, {}\".format(skippedMessage,",
"referenced by one or more element and/or event frame attribute template and/or tag",
"unit of measurement. if form.validate_on_submit(): unitOfMeasurement = UnitOfMeasurement(Abbreviation = form.abbreviation.data, Name = form.name.data)",
"is None: addedUnits.append(defaultUnits[defaultUnit]) unit = UnitOfMeasurement(Abbreviation = defaultUnit) unit.Name = defaultUnits[defaultUnit] db.session.add(unit) else:",
"= \"{}.\".format(addedMessage) else: addedMessage = \"Added none of the default units of measurements.\"",
"\"RDF\" : \"real degree of fermentation\", \"RE\" : \"real extract\", \"s\" : \"second\",",
"@unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def editUnitOfMeasurement(unitOfMeasurementId): operation = \"Edit\" unitOfMeasurement",
"adminRequired from .. models import UnitOfMeasurement modelName = \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods = [\"GET\",",
"unit in addedUnits: if addedMessage == \"\": addedMessage = \"Added: {}\".format(unit) alert =",
"\"hour\", \"in\" : \"inches\", \"IBU\" : \"international bittering unit\", \"kg\" : \"kilogram\", \"L\"",
"= [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\",",
"unit of measurement. breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class =",
"= [\"GET\", \"POST\"]) @login_required @adminRequired def addUnitOfMeasurement(): operation = \"Add\" form = UnitOfMeasurementForm()",
"= UnitOfMeasurement(Abbreviation = defaultUnit) unit.Name = defaultUnits[defaultUnit] db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage =",
"import UnitOfMeasurementForm from .. import db from .. decorators import adminRequired from ..",
"\"alert alert-warning\" if addedUnits: for unit in addedUnits: if addedMessage == \"\": addedMessage",
"UnitOfMeasurement modelName = \"Unit\" @unitOfMeasurements.route(\"/unitOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def listUnitOfMeasurements():",
"\\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to edit an existing",
"\"gal\" : \"gallon\", \"gpm\" : \"gallons per minute\", \"g\" : \"grams\", \"g/bbl\" :",
"\"TA\" : \"total acidity\", \"vol\" : \"volumes\", \"x10^12 cells\" : \"x10^12 cells\", \"x10^6",
"@login_required @adminRequired def editUnitOfMeasurement(unitOfMeasurementId): operation = \"Edit\" unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) form = UnitOfMeasurementForm(obj",
"= UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced(): flash('Unit of Measurement \"{}\" is referenced by one or",
"\"' + unitOfMeasurement.Abbreviation + '\".', \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods = [\"GET\",",
"@login_required @adminRequired def listUnitOfMeasurements(): unitOfMeasurements = UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements = unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\",",
"\\\"glyphicon glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form = form, modelName = modelName,",
"from flask import flash, redirect, render_template, request, url_for from flask_login import login_required from",
"\"Add\" form = UnitOfMeasurementForm() # Add a new unit of measurement. if form.validate_on_submit():",
"return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to add a new unit of measurement.",
"a new unit of measurement. breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span",
"return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements = unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def",
"db.session.add(unit) else: skippedUnits.append(defaultUnits[defaultUnit]) db.session.commit() addedMessage = \"\" alert = \"alert alert-warning\" if addedUnits:",
"if skippedUnits: for unit in skippedUnits: if skippedMessage == \"\": skippedMessage = \"Skipped:",
"unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addUnitOfMeasurement(): operation = \"Add\"",
"= unitOfMeasurement.UnitOfMeasurementId form.abbreviation.data = unitOfMeasurement.Abbreviation form.name.data = unitOfMeasurement.Name breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"),",
"brewing chemists\", \"ADF\" : \"apparent degree of fermentation\", \"bbl\" : \"barrel\", \"cells/ml\" :",
"fermentation\", \"bbl\" : \"barrel\", \"cells/ml\" : \"cells per milliliter\", \"cells/ml/°P\" : \"cells per",
"glyphicon-home\\\"></span>\"}, {\"url\" : None, \"text\" : unitOfMeasurement.Name}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs, form",
"else: unitOfMeasurement.delete() db.session.commit() flash('You have successfully deleted the unit of measurement \"' +",
"unitOfMeasurement.Abbreviation = form.abbreviation.data unitOfMeasurement.Name = form.name.data db.session.commit() flash(\"You have successfully edited the unit",
"is referenced by one or more element and/or event frame attribute template and/or",
"unitOfMeasurements = UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements = unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods = [\"GET\", \"POST\"])",
"\"lb\" : \"pound\", \"lb/bbl\" : \"pounds per barrel\", \"psi\" : \"pounds per square",
"measurement \"' + unitOfMeasurement.Abbreviation + '\".', \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods =",
"\"millimeter\", \"min\" : \"minute\", \"ppb\" : \"parts per billion\", \"ppm\" : \"parts per",
"if form.validate_on_submit(): unitOfMeasurement = UnitOfMeasurement(Abbreviation = form.abbreviation.data, Name = form.name.data) db.session.add(unitOfMeasurement) db.session.commit() flash(\"You",
"a new unit of measurement. if form.validate_on_submit(): unitOfMeasurement = UnitOfMeasurement(Abbreviation = form.abbreviation.data, Name",
"of measurement. breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon",
"\"°C\" : \"degree celsius\", \"°P\" : \"degree plato\", \"°F\" : \"degree fahrenheit\", \"°F/min\"",
"\"Added none of the default units of measurements.\" flash(addedMessage, alert) skippedMessage = \"\"",
"\"volumes\", \"x10^12 cells\" : \"x10^12 cells\", \"x10^6 cells\" : \"x10^6 cells\"} addedUnits =",
"= form.name.data) db.session.add(unitOfMeasurement) db.session.commit() flash(\"You have successfully added the new unit of measurement",
"\"degree fahrenheit\", \"°F/min\" : \"degree fahrenheit per minute\", \"EBC\" : \"european brewery convention\",",
"form.validate_on_submit(): unitOfMeasurement = UnitOfMeasurement(Abbreviation = form.abbreviation.data, Name = form.name.data) db.session.add(unitOfMeasurement) db.session.commit() flash(\"You have",
"addDefaultUnitsOfMeasurements(): defaultUnits = {\"ASBC\" : \"american society of brewing chemists\", \"ADF\" : \"apparent",
"= \"{}, {}\".format(skippedMessage, unit) skippedMessage = \"{} as they already exist.\".format(skippedMessage) flash(skippedMessage, \"alert",
"= unitOfMeasurement) # Edit an existing unit of measurement. if form.validate_on_submit(): unitOfMeasurement.Abbreviation =",
"flash('Unit of Measurement \"{}\" is referenced by one or more element and/or event",
"per million\", \"%\" : \"percentage\", \"pH\" : \"potential of hydrogen\", \"lb\" : \"pound\",",
"UnitOfMeasurement(Abbreviation = form.abbreviation.data, Name = form.name.data) db.session.add(unitOfMeasurement) db.session.commit() flash(\"You have successfully added the",
"million\", \"%\" : \"percentage\", \"pH\" : \"potential of hydrogen\", \"lb\" : \"pound\", \"lb/bbl\"",
"form.abbreviation.data = unitOfMeasurement.Abbreviation form.name.data = unitOfMeasurement.Name breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" :",
"unitOfMeasurement.Abbreviation form.name.data = unitOfMeasurement.Name breadcrumbs = [{\"url\" : url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class",
"modelName, operation = operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addDefaultUnitsOfMeasurements():",
"operation = operation) @unitOfMeasurements.route(\"/units/addDefaultUnitsOfMeasurements\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired def addDefaultUnitsOfMeasurements(): defaultUnits",
"\"g/L\" : \"grams per liter\", \"h\" : \"hour\", \"in\" : \"inches\", \"IBU\" :",
"\"tons per hour\", \"TA\" : \"total acidity\", \"vol\" : \"volumes\", \"x10^12 cells\" :",
": \"specific gravity\", \"SRM\" : \"standard reference method\", \"t/h\" : \"tons per hour\",",
"unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to",
"= \"\" alert = \"alert alert-warning\" if addedUnits: for unit in addedUnits: if",
"UnitOfMeasurementForm(obj = unitOfMeasurement) # Edit an existing unit of measurement. if form.validate_on_submit(): unitOfMeasurement.Abbreviation",
"{}\".format(unit) alert = \"alert alert-success\" else: addedMessage = \"{}, {}\".format(addedMessage, unit) addedMessage =",
"flash(addedMessage, alert) skippedMessage = \"\" if skippedUnits: for unit in skippedUnits: if skippedMessage",
"UnitOfMeasurement.query return render_template(\"unitOfMeasurements/unitOfMeasurements.html\", unitOfMeasurements = unitOfMeasurements) @unitOfMeasurements.route(\"/units/add\", methods = [\"GET\", \"POST\"]) @login_required @adminRequired",
"[\"GET\", \"POST\"]) @login_required @adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced(): flash('Unit of",
"import and_ from . import unitOfMeasurements from . forms import UnitOfMeasurementForm from ..",
"\"liters\", \"mg\" : \"milligram\", \"mL\" : \"milliliter\", \"mm\" : \"millimeter\", \"min\" : \"minute\",",
"url_for(\"unitOfMeasurements.listUnitOfMeasurements\"), \"text\" : \"<span class = \\\"glyphicon glyphicon-home\\\"></span>\"}] return render_template(\"addEdit.html\", breadcrumbs = breadcrumbs,",
"\"pound\", \"lb/bbl\" : \"pounds per barrel\", \"psi\" : \"pounds per square inch\", \"RDF\"",
"methods = [\"GET\", \"POST\"]) @login_required @adminRequired def editUnitOfMeasurement(unitOfMeasurementId): operation = \"Edit\" unitOfMeasurement =",
"have successfully added the new unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\"))",
"= [] skippedUnits = [] for defaultUnit in defaultUnits: unit = UnitOfMeasurement.query.filter(and_(UnitOfMeasurement.Abbreviation ==",
"unitOfMeasurement.Abbreviation + '\".', \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods = [\"GET\", \"POST\"]) @login_required",
"fermentation\", \"RE\" : \"real extract\", \"s\" : \"second\", \"SG\" : \"specific gravity\", \"SRM\"",
"unit is None: addedUnits.append(defaultUnits[defaultUnit]) unit = UnitOfMeasurement(Abbreviation = defaultUnit) unit.Name = defaultUnits[defaultUnit] db.session.add(unit)",
"\"gallon\", \"gpm\" : \"gallons per minute\", \"g\" : \"grams\", \"g/bbl\" : \"grams per",
"= \"Add\" form = UnitOfMeasurementForm() # Add a new unit of measurement. if",
"of measurement. if form.validate_on_submit(): unitOfMeasurement = UnitOfMeasurement(Abbreviation = form.abbreviation.data, Name = form.name.data) db.session.add(unitOfMeasurement)",
"@login_required @adminRequired def deleteUnitOfMeasurement(unitOfMeasurementId): unitOfMeasurement = UnitOfMeasurement.query.get_or_404(unitOfMeasurementId) if unitOfMeasurement.isReferenced(): flash('Unit of Measurement \"{}\"",
"form.name.data) db.session.add(unitOfMeasurement) db.session.commit() flash(\"You have successfully added the new unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation),",
"method\", \"t/h\" : \"tons per hour\", \"TA\" : \"total acidity\", \"vol\" : \"volumes\",",
"{}\".format(unit) else: skippedMessage = \"{}, {}\".format(skippedMessage, unit) skippedMessage = \"{} as they already",
"\"minute\", \"ppb\" : \"parts per billion\", \"ppm\" : \"parts per million\", \"%\" :",
"\"\": addedMessage = \"Added: {}\".format(unit) alert = \"alert alert-success\" else: addedMessage = \"{},",
"per minute\", \"g\" : \"grams\", \"g/bbl\" : \"grams per barrel\", \"g/L\" : \"grams",
"import db from .. decorators import adminRequired from .. models import UnitOfMeasurement modelName",
"unitOfMeasurement = UnitOfMeasurement(Abbreviation = form.abbreviation.data, Name = form.name.data) db.session.add(unitOfMeasurement) db.session.commit() flash(\"You have successfully",
"per barrel\", \"g/L\" : \"grams per liter\", \"h\" : \"hour\", \"in\" : \"inches\",",
"= form.name.data db.session.commit() flash(\"You have successfully edited the unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert",
"UnitOfMeasurement.Name == defaultUnits[defaultUnit])).first() if unit is None: addedUnits.append(defaultUnits[defaultUnit]) unit = UnitOfMeasurement(Abbreviation = defaultUnit)",
": \"degree plato\", \"°F\" : \"degree fahrenheit\", \"°F/min\" : \"degree fahrenheit per minute\",",
"unitOfMeasurement.Name = form.name.data db.session.commit() flash(\"You have successfully edited the unit of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation),",
": \"second\", \"SG\" : \"specific gravity\", \"SRM\" : \"standard reference method\", \"t/h\" :",
"\"{}, {}\".format(addedMessage, unit) addedMessage = \"{}.\".format(addedMessage) else: addedMessage = \"Added none of the",
"one or more element and/or event frame attribute template and/or tag and cannot",
"= {\"ASBC\" : \"american society of brewing chemists\", \"ADF\" : \"apparent degree of",
": \"x10^12 cells\", \"x10^6 cells\" : \"x10^6 cells\"} addedUnits = [] skippedUnits =",
"new unit of measurement. if form.validate_on_submit(): unitOfMeasurement = UnitOfMeasurement(Abbreviation = form.abbreviation.data, Name =",
"flash, redirect, render_template, request, url_for from flask_login import login_required from sqlalchemy import and_",
"units of measurements.\" flash(addedMessage, alert) skippedMessage = \"\" if skippedUnits: for unit in",
"of measurement \\\"{}\\\".\".format(unitOfMeasurement.Abbreviation), \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) # Present a form to add",
"\"x10^12 cells\", \"x10^6 cells\" : \"x10^6 cells\"} addedUnits = [] skippedUnits = []",
"skippedMessage == \"\": skippedMessage = \"Skipped: {}\".format(unit) else: skippedMessage = \"{}, {}\".format(skippedMessage, unit)",
"brewery convention\", \"gal\" : \"gallon\", \"gpm\" : \"gallons per minute\", \"g\" : \"grams\",",
"of measurement \"' + unitOfMeasurement.Abbreviation + '\".', \"alert alert-success\") return redirect(url_for(\"unitOfMeasurements.listUnitOfMeasurements\")) @unitOfMeasurements.route(\"/unitOfMeasurements/edit/<int:unitOfMeasurementId>\", methods",
"alert) skippedMessage = \"\" if skippedUnits: for unit in skippedUnits: if skippedMessage ==",
"import unitOfMeasurements from . forms import UnitOfMeasurementForm from .. import db from ..",
"sqlalchemy import and_ from . import unitOfMeasurements from . forms import UnitOfMeasurementForm from",
"\"EBC\" : \"european brewery convention\", \"gal\" : \"gallon\", \"gpm\" : \"gallons per minute\","
] |
[
"from unittest import mock import pytest from bs4 import BeautifulSoup from conf import",
"REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, ) response = wsgi.application(environ=environ, start_response=mock.Mock) assert response.status_code == 200 soup =",
"conf import wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'), ('', '/accounts/'))) def test_set_script_name(rf, script_name, prefix):",
"wsgi.application(environ=environ, start_response=mock.Mock) assert response.status_code == 200 soup = BeautifulSoup(response.content, 'html.parser') element = soup.find(id='header-sign-in-link')",
"charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, ) response = wsgi.application(environ=environ, start_response=mock.Mock) assert response.status_code == 200 soup",
"prefix): environ = rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, ) response = wsgi.application(environ=environ,",
"test_set_script_name(rf, script_name, prefix): environ = rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, ) response",
"'/accounts/'))) def test_set_script_name(rf, script_name, prefix): environ = rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name,",
"script_name, prefix): environ = rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, ) response =",
"from bs4 import BeautifulSoup from conf import wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'), ('',",
"= wsgi.application(environ=environ, start_response=mock.Mock) assert response.status_code == 200 soup = BeautifulSoup(response.content, 'html.parser') element =",
"response = wsgi.application(environ=environ, start_response=mock.Mock) assert response.status_code == 200 soup = BeautifulSoup(response.content, 'html.parser') element",
"import mock import pytest from bs4 import BeautifulSoup from conf import wsgi @pytest.mark.django_db",
"@pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'), ('', '/accounts/'))) def test_set_script_name(rf, script_name, prefix): environ = rf._base_environ(",
"assert response.status_code == 200 soup = BeautifulSoup(response.content, 'html.parser') element = soup.find(id='header-sign-in-link') assert element.attrs['href'].startswith(prefix)",
"HTTP_X_SCRIPT_NAME=script_name, ) response = wsgi.application(environ=environ, start_response=mock.Mock) assert response.status_code == 200 soup = BeautifulSoup(response.content,",
"bs4 import BeautifulSoup from conf import wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'), ('', '/accounts/')))",
"'/sso/accounts/'), ('', '/accounts/'))) def test_set_script_name(rf, script_name, prefix): environ = rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\",",
"PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, ) response = wsgi.application(environ=environ, start_response=mock.Mock) assert response.status_code ==",
"unittest import mock import pytest from bs4 import BeautifulSoup from conf import wsgi",
"import wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'), ('', '/accounts/'))) def test_set_script_name(rf, script_name, prefix): environ",
"import pytest from bs4 import BeautifulSoup from conf import wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso',",
"import BeautifulSoup from conf import wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'), ('', '/accounts/'))) def",
"= rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, ) response = wsgi.application(environ=environ, start_response=mock.Mock) assert",
"environ = rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, ) response = wsgi.application(environ=environ, start_response=mock.Mock)",
"rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, ) response = wsgi.application(environ=environ, start_response=mock.Mock) assert response.status_code",
"@pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'), ('', '/accounts/'))) def test_set_script_name(rf, script_name, prefix): environ = rf._base_environ( PATH_INFO='/accounts/password/reset/',",
"start_response=mock.Mock) assert response.status_code == 200 soup = BeautifulSoup(response.content, 'html.parser') element = soup.find(id='header-sign-in-link') assert",
"pytest from bs4 import BeautifulSoup from conf import wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'),",
"def test_set_script_name(rf, script_name, prefix): environ = rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, )",
"('', '/accounts/'))) def test_set_script_name(rf, script_name, prefix): environ = rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\",",
"from conf import wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'), ('', '/accounts/'))) def test_set_script_name(rf, script_name,",
"(('/sso', '/sso/accounts/'), ('', '/accounts/'))) def test_set_script_name(rf, script_name, prefix): environ = rf._base_environ( PATH_INFO='/accounts/password/reset/', CONTENT_TYPE=\"text/html;",
"CONTENT_TYPE=\"text/html; charset=utf-8\", REQUEST_METHOD=\"GET\", HTTP_X_SCRIPT_NAME=script_name, ) response = wsgi.application(environ=environ, start_response=mock.Mock) assert response.status_code == 200",
") response = wsgi.application(environ=environ, start_response=mock.Mock) assert response.status_code == 200 soup = BeautifulSoup(response.content, 'html.parser')",
"wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'), ('', '/accounts/'))) def test_set_script_name(rf, script_name, prefix): environ =",
"BeautifulSoup from conf import wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix', (('/sso', '/sso/accounts/'), ('', '/accounts/'))) def test_set_script_name(rf,",
"mock import pytest from bs4 import BeautifulSoup from conf import wsgi @pytest.mark.django_db @pytest.mark.parametrize('script_name,prefix',"
] |
[
"model_name='publishedgame', name='edition', ), migrations.RemoveField( model_name='publishedgame', name='game_system', ), migrations.RemoveField( model_name='publishedgame', name='isbn', ), migrations.RemoveField( model_name='publishedgame',",
"migrations.RemoveField( model_name='publishedgame', name='edition', ), migrations.RemoveField( model_name='publishedgame', name='game_system', ), migrations.RemoveField( model_name='publishedgame', name='isbn', ), migrations.RemoveField(",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('game_catalog', '0010_auto_20181104_1036'), ] operations = [",
"('game_catalog', '0010_auto_20181104_1036'), ] operations = [ migrations.RemoveField( model_name='publishedgame', name='edition', ), migrations.RemoveField( model_name='publishedgame', name='game_system',",
"class Migration(migrations.Migration): dependencies = [ ('game_catalog', '0010_auto_20181104_1036'), ] operations = [ migrations.RemoveField( model_name='publishedgame',",
"16:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"on 2018-11-04 16:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"Generated by Django 2.1.2 on 2018-11-04 16:16 from django.db import migrations, models import",
"= [ migrations.RemoveField( model_name='publishedgame', name='edition', ), migrations.RemoveField( model_name='publishedgame', name='game_system', ), migrations.RemoveField( model_name='publishedgame', name='isbn',",
"by Django 2.1.2 on 2018-11-04 16:16 from django.db import migrations, models import django.db.models.deletion",
"'0010_auto_20181104_1036'), ] operations = [ migrations.RemoveField( model_name='publishedgame', name='edition', ), migrations.RemoveField( model_name='publishedgame', name='game_system', ),",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('game_catalog',",
"migrations.RemoveField( model_name='publishedgame', name='game_system', ), migrations.RemoveField( model_name='publishedgame', name='isbn', ), migrations.RemoveField( model_name='publishedgame', name='publisher', ), ]",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('game_catalog', '0010_auto_20181104_1036'), ] operations =",
"operations = [ migrations.RemoveField( model_name='publishedgame', name='edition', ), migrations.RemoveField( model_name='publishedgame', name='game_system', ), migrations.RemoveField( model_name='publishedgame',",
"dependencies = [ ('game_catalog', '0010_auto_20181104_1036'), ] operations = [ migrations.RemoveField( model_name='publishedgame', name='edition', ),",
"name='edition', ), migrations.RemoveField( model_name='publishedgame', name='game_system', ), migrations.RemoveField( model_name='publishedgame', name='isbn', ), migrations.RemoveField( model_name='publishedgame', name='publisher',",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('game_catalog', '0010_auto_20181104_1036'), ] operations",
"# Generated by Django 2.1.2 on 2018-11-04 16:16 from django.db import migrations, models",
"] operations = [ migrations.RemoveField( model_name='publishedgame', name='edition', ), migrations.RemoveField( model_name='publishedgame', name='game_system', ), migrations.RemoveField(",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('game_catalog', '0010_auto_20181104_1036'),",
"Migration(migrations.Migration): dependencies = [ ('game_catalog', '0010_auto_20181104_1036'), ] operations = [ migrations.RemoveField( model_name='publishedgame', name='edition',",
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('game_catalog', '0010_auto_20181104_1036'), ] operations = [ migrations.RemoveField(",
"[ ('game_catalog', '0010_auto_20181104_1036'), ] operations = [ migrations.RemoveField( model_name='publishedgame', name='edition', ), migrations.RemoveField( model_name='publishedgame',",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('game_catalog', '0010_auto_20181104_1036'), ]",
"Django 2.1.2 on 2018-11-04 16:16 from django.db import migrations, models import django.db.models.deletion class",
"2.1.2 on 2018-11-04 16:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"[ migrations.RemoveField( model_name='publishedgame', name='edition', ), migrations.RemoveField( model_name='publishedgame', name='game_system', ), migrations.RemoveField( model_name='publishedgame', name='isbn', ),",
"2018-11-04 16:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"), migrations.RemoveField( model_name='publishedgame', name='game_system', ), migrations.RemoveField( model_name='publishedgame', name='isbn', ), migrations.RemoveField( model_name='publishedgame', name='publisher', ),",
"= [ ('game_catalog', '0010_auto_20181104_1036'), ] operations = [ migrations.RemoveField( model_name='publishedgame', name='edition', ), migrations.RemoveField("
] |
[
"async def rename(self, client, message, parameters): session = SessionManager.get_session(message.channel) if session: if not",
"SyntaxBuilder from bashbot.session_manager import SessionManager class RenameCommand(Command): def __init__(self): super().__init__() self.name = \"Rename",
"= \"session.rename\" self.syntax = SyntaxBuilder() \\ .param(\"new_name\", \"rename\") \\ .build() async def rename(self,",
"% len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop()) else: await client.send_message(message.channel, \":no_entry_sign: You are trying to freeze",
"client.send_message(message.channel, \":no_entry_sign: Maximum length of session name is 20. Your is: %s\" %",
"terminal\" self.aliases = [\".rename\"] self.description = \"Renames terminal session\" self.usage = \".rename <new_name>\"",
"message, parameters): session = SessionManager.get_session(message.channel) if session: if not len(parameters[\"new_name\"]) > 20: session.name",
"= \"Renames terminal session\" self.usage = \".rename <new_name>\" self.permission = \"session.rename\" self.syntax =",
"<new_name>\" self.permission = \"session.rename\" self.syntax = SyntaxBuilder() \\ .param(\"new_name\", \"rename\") \\ .build() async",
"import Command from bashbot.commands.syntax import SyntaxBuilder from bashbot.session_manager import SessionManager class RenameCommand(Command): def",
"length of session name is 20. Your is: %s\" % len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop())",
"= SessionManager.get_session(message.channel) if session: if not len(parameters[\"new_name\"]) > 20: session.name = parameters[\"new_name\"] else:",
"from bashbot.session_manager import SessionManager class RenameCommand(Command): def __init__(self): super().__init__() self.name = \"Rename terminal\"",
"Command from bashbot.commands.syntax import SyntaxBuilder from bashbot.session_manager import SessionManager class RenameCommand(Command): def __init__(self):",
"Your is: %s\" % len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop()) else: await client.send_message(message.channel, \":no_entry_sign: You are",
"self.permission = \"session.rename\" self.syntax = SyntaxBuilder() \\ .param(\"new_name\", \"rename\") \\ .build() async def",
"super().__init__() self.name = \"Rename terminal\" self.aliases = [\".rename\"] self.description = \"Renames terminal session\"",
"\\ .param(\"new_name\", \"rename\") \\ .build() async def rename(self, client, message, parameters): session =",
"session\" self.usage = \".rename <new_name>\" self.permission = \"session.rename\" self.syntax = SyntaxBuilder() \\ .param(\"new_name\",",
".param(\"new_name\", \"rename\") \\ .build() async def rename(self, client, message, parameters): session = SessionManager.get_session(message.channel)",
"= parameters[\"new_name\"] else: await client.send_message(message.channel, \":no_entry_sign: Maximum length of session name is 20.",
"def rename(self, client, message, parameters): session = SessionManager.get_session(message.channel) if session: if not len(parameters[\"new_name\"])",
"SyntaxBuilder() \\ .param(\"new_name\", \"rename\") \\ .build() async def rename(self, client, message, parameters): session",
"\"session.rename\" self.syntax = SyntaxBuilder() \\ .param(\"new_name\", \"rename\") \\ .build() async def rename(self, client,",
"is: %s\" % len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop()) else: await client.send_message(message.channel, \":no_entry_sign: You are trying",
"from bashbot.commands.syntax import SyntaxBuilder from bashbot.session_manager import SessionManager class RenameCommand(Command): def __init__(self): super().__init__()",
"is 20. Your is: %s\" % len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop()) else: await client.send_message(message.channel, \":no_entry_sign:",
"terminal session\" self.usage = \".rename <new_name>\" self.permission = \"session.rename\" self.syntax = SyntaxBuilder() \\",
"= [\".rename\"] self.description = \"Renames terminal session\" self.usage = \".rename <new_name>\" self.permission =",
"session.name = parameters[\"new_name\"] else: await client.send_message(message.channel, \":no_entry_sign: Maximum length of session name is",
"def __init__(self): super().__init__() self.name = \"Rename terminal\" self.aliases = [\".rename\"] self.description = \"Renames",
"Maximum length of session name is 20. Your is: %s\" % len(parameters[\"name\"])) return",
"> 20: session.name = parameters[\"new_name\"] else: await client.send_message(message.channel, \":no_entry_sign: Maximum length of session",
"\\ .build() async def rename(self, client, message, parameters): session = SessionManager.get_session(message.channel) if session:",
"from bashbot.commands import Command from bashbot.commands.syntax import SyntaxBuilder from bashbot.session_manager import SessionManager class",
"session name is 20. Your is: %s\" % len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop()) else: await",
"not len(parameters[\"new_name\"]) > 20: session.name = parameters[\"new_name\"] else: await client.send_message(message.channel, \":no_entry_sign: Maximum length",
".build() async def rename(self, client, message, parameters): session = SessionManager.get_session(message.channel) if session: if",
"[\".rename\"] self.description = \"Renames terminal session\" self.usage = \".rename <new_name>\" self.permission = \"session.rename\"",
"name is 20. Your is: %s\" % len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop()) else: await client.send_message(message.channel,",
"import SyntaxBuilder from bashbot.session_manager import SessionManager class RenameCommand(Command): def __init__(self): super().__init__() self.name =",
"\":no_entry_sign: Maximum length of session name is 20. Your is: %s\" % len(parameters[\"name\"]))",
"of session name is 20. Your is: %s\" % len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop()) else:",
"\"Rename terminal\" self.aliases = [\".rename\"] self.description = \"Renames terminal session\" self.usage = \".rename",
"bashbot.session_manager import SessionManager class RenameCommand(Command): def __init__(self): super().__init__() self.name = \"Rename terminal\" self.aliases",
"len(parameters[\"new_name\"]) > 20: session.name = parameters[\"new_name\"] else: await client.send_message(message.channel, \":no_entry_sign: Maximum length of",
"client, message, parameters): session = SessionManager.get_session(message.channel) if session: if not len(parameters[\"new_name\"]) > 20:",
"%s\" % len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop()) else: await client.send_message(message.channel, \":no_entry_sign: You are trying to",
"20: session.name = parameters[\"new_name\"] else: await client.send_message(message.channel, \":no_entry_sign: Maximum length of session name",
"= \"Rename terminal\" self.aliases = [\".rename\"] self.description = \"Renames terminal session\" self.usage =",
"session: if not len(parameters[\"new_name\"]) > 20: session.name = parameters[\"new_name\"] else: await client.send_message(message.channel, \":no_entry_sign:",
"bashbot.commands import Command from bashbot.commands.syntax import SyntaxBuilder from bashbot.session_manager import SessionManager class RenameCommand(Command):",
"parameters): session = SessionManager.get_session(message.channel) if session: if not len(parameters[\"new_name\"]) > 20: session.name =",
"await client.send_message(message.channel, \":no_entry_sign: Maximum length of session name is 20. Your is: %s\"",
"import asyncio from bashbot.commands import Command from bashbot.commands.syntax import SyntaxBuilder from bashbot.session_manager import",
"\".rename <new_name>\" self.permission = \"session.rename\" self.syntax = SyntaxBuilder() \\ .param(\"new_name\", \"rename\") \\ .build()",
"self.description = \"Renames terminal session\" self.usage = \".rename <new_name>\" self.permission = \"session.rename\" self.syntax",
"= SyntaxBuilder() \\ .param(\"new_name\", \"rename\") \\ .build() async def rename(self, client, message, parameters):",
"self.syntax = SyntaxBuilder() \\ .param(\"new_name\", \"rename\") \\ .build() async def rename(self, client, message,",
"len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop()) else: await client.send_message(message.channel, \":no_entry_sign: You are trying to freeze non-existing",
"SessionManager.get_session(message.channel) if session: if not len(parameters[\"new_name\"]) > 20: session.name = parameters[\"new_name\"] else: await",
"if not len(parameters[\"new_name\"]) > 20: session.name = parameters[\"new_name\"] else: await client.send_message(message.channel, \":no_entry_sign: Maximum",
"rename(self, client, message, parameters): session = SessionManager.get_session(message.channel) if session: if not len(parameters[\"new_name\"]) >",
"__init__(self): super().__init__() self.name = \"Rename terminal\" self.aliases = [\".rename\"] self.description = \"Renames terminal",
"\"Renames terminal session\" self.usage = \".rename <new_name>\" self.permission = \"session.rename\" self.syntax = SyntaxBuilder()",
"return session.send_output(asyncio.get_event_loop()) else: await client.send_message(message.channel, \":no_entry_sign: You are trying to freeze non-existing session\")",
"import SessionManager class RenameCommand(Command): def __init__(self): super().__init__() self.name = \"Rename terminal\" self.aliases =",
"self.aliases = [\".rename\"] self.description = \"Renames terminal session\" self.usage = \".rename <new_name>\" self.permission",
"RenameCommand(Command): def __init__(self): super().__init__() self.name = \"Rename terminal\" self.aliases = [\".rename\"] self.description =",
"else: await client.send_message(message.channel, \":no_entry_sign: Maximum length of session name is 20. Your is:",
"self.name = \"Rename terminal\" self.aliases = [\".rename\"] self.description = \"Renames terminal session\" self.usage",
"parameters[\"new_name\"] else: await client.send_message(message.channel, \":no_entry_sign: Maximum length of session name is 20. Your",
"class RenameCommand(Command): def __init__(self): super().__init__() self.name = \"Rename terminal\" self.aliases = [\".rename\"] self.description",
"20. Your is: %s\" % len(parameters[\"name\"])) return session.send_output(asyncio.get_event_loop()) else: await client.send_message(message.channel, \":no_entry_sign: You",
"\"rename\") \\ .build() async def rename(self, client, message, parameters): session = SessionManager.get_session(message.channel) if",
"self.usage = \".rename <new_name>\" self.permission = \"session.rename\" self.syntax = SyntaxBuilder() \\ .param(\"new_name\", \"rename\")",
"asyncio from bashbot.commands import Command from bashbot.commands.syntax import SyntaxBuilder from bashbot.session_manager import SessionManager",
"bashbot.commands.syntax import SyntaxBuilder from bashbot.session_manager import SessionManager class RenameCommand(Command): def __init__(self): super().__init__() self.name",
"= \".rename <new_name>\" self.permission = \"session.rename\" self.syntax = SyntaxBuilder() \\ .param(\"new_name\", \"rename\") \\",
"SessionManager class RenameCommand(Command): def __init__(self): super().__init__() self.name = \"Rename terminal\" self.aliases = [\".rename\"]",
"if session: if not len(parameters[\"new_name\"]) > 20: session.name = parameters[\"new_name\"] else: await client.send_message(message.channel,",
"session = SessionManager.get_session(message.channel) if session: if not len(parameters[\"new_name\"]) > 20: session.name = parameters[\"new_name\"]"
] |
[
"[0, 0, 0] positive_classes_weight = [0, 0, 0] negative_policy_weight = [0, 0, 0]",
"0] negative_policy_weight = [0, 0, 0] positive_policy_weight = [0, 0, 0] for i",
"0, 0] positive_classes_weight = [0, 0, 0] negative_policy_weight = [0, 0, 0] positive_policy_weight",
"for i in range(len(negative_identity_weight)): log = f'log/cifar10/icpkd/resnet18_from_resnet50_option_1_{i}_2倍.txt' os.system(\"rm -rf ./resource\") os.system(f\"python ./SST/image_classification_policy.py --log",
"sys if __name__ == \"__main__\": negative_identity_weight = [0, 0, 0] positive_identity_weight = [0,",
"__name__ == \"__main__\": negative_identity_weight = [0, 0, 0] positive_identity_weight = [0, 0, 0]",
"[0, 0, 0] for i in range(len(negative_identity_weight)): log = f'log/cifar10/icpkd/resnet18_from_resnet50_option_1_{i}_2倍.txt' os.system(\"rm -rf ./resource\")",
"= [0, 0, 0] for i in range(len(negative_identity_weight)): log = f'log/cifar10/icpkd/resnet18_from_resnet50_option_1_{i}_2倍.txt' os.system(\"rm -rf",
"== \"__main__\": negative_identity_weight = [0, 0, 0] positive_identity_weight = [0, 0, 0] negative_classes_weight",
"i in range(len(negative_identity_weight)): log = f'log/cifar10/icpkd/resnet18_from_resnet50_option_1_{i}_2倍.txt' os.system(\"rm -rf ./resource\") os.system(f\"python ./SST/image_classification_policy.py --log {log}\")",
"[0, 0, 0] negative_classes_weight = [0, 0, 0] positive_classes_weight = [0, 0, 0]",
"if __name__ == \"__main__\": negative_identity_weight = [0, 0, 0] positive_identity_weight = [0, 0,",
"os, sys if __name__ == \"__main__\": negative_identity_weight = [0, 0, 0] positive_identity_weight =",
"= [0, 0, 0] positive_identity_weight = [0, 0, 0] negative_classes_weight = [0, 0,",
"0] positive_identity_weight = [0, 0, 0] negative_classes_weight = [0, 0, 0] positive_classes_weight =",
"negative_classes_weight = [0, 0, 0] positive_classes_weight = [0, 0, 0] negative_policy_weight = [0,",
"0, 0] positive_identity_weight = [0, 0, 0] negative_classes_weight = [0, 0, 0] positive_classes_weight",
"= [0, 0, 0] negative_classes_weight = [0, 0, 0] positive_classes_weight = [0, 0,",
"= [0, 0, 0] positive_classes_weight = [0, 0, 0] negative_policy_weight = [0, 0,",
"0] positive_classes_weight = [0, 0, 0] negative_policy_weight = [0, 0, 0] positive_policy_weight =",
"range(len(negative_identity_weight)): log = f'log/cifar10/icpkd/resnet18_from_resnet50_option_1_{i}_2倍.txt' os.system(\"rm -rf ./resource\") os.system(f\"python ./SST/image_classification_policy.py --log {log}\") print(f\"============================end {i}================================\")",
"[0, 0, 0] positive_identity_weight = [0, 0, 0] negative_classes_weight = [0, 0, 0]",
"import os, sys if __name__ == \"__main__\": negative_identity_weight = [0, 0, 0] positive_identity_weight",
"0, 0] negative_policy_weight = [0, 0, 0] positive_policy_weight = [0, 0, 0] for",
"negative_policy_weight = [0, 0, 0] positive_policy_weight = [0, 0, 0] for i in",
"positive_classes_weight = [0, 0, 0] negative_policy_weight = [0, 0, 0] positive_policy_weight = [0,",
"\"__main__\": negative_identity_weight = [0, 0, 0] positive_identity_weight = [0, 0, 0] negative_classes_weight =",
"positive_policy_weight = [0, 0, 0] for i in range(len(negative_identity_weight)): log = f'log/cifar10/icpkd/resnet18_from_resnet50_option_1_{i}_2倍.txt' os.system(\"rm",
"0] for i in range(len(negative_identity_weight)): log = f'log/cifar10/icpkd/resnet18_from_resnet50_option_1_{i}_2倍.txt' os.system(\"rm -rf ./resource\") os.system(f\"python ./SST/image_classification_policy.py",
"0, 0] for i in range(len(negative_identity_weight)): log = f'log/cifar10/icpkd/resnet18_from_resnet50_option_1_{i}_2倍.txt' os.system(\"rm -rf ./resource\") os.system(f\"python",
"0, 0] positive_policy_weight = [0, 0, 0] for i in range(len(negative_identity_weight)): log =",
"0] positive_policy_weight = [0, 0, 0] for i in range(len(negative_identity_weight)): log = f'log/cifar10/icpkd/resnet18_from_resnet50_option_1_{i}_2倍.txt'",
"0] negative_classes_weight = [0, 0, 0] positive_classes_weight = [0, 0, 0] negative_policy_weight =",
"negative_identity_weight = [0, 0, 0] positive_identity_weight = [0, 0, 0] negative_classes_weight = [0,",
"= [0, 0, 0] positive_policy_weight = [0, 0, 0] for i in range(len(negative_identity_weight)):",
"positive_identity_weight = [0, 0, 0] negative_classes_weight = [0, 0, 0] positive_classes_weight = [0,",
"[0, 0, 0] negative_policy_weight = [0, 0, 0] positive_policy_weight = [0, 0, 0]",
"in range(len(negative_identity_weight)): log = f'log/cifar10/icpkd/resnet18_from_resnet50_option_1_{i}_2倍.txt' os.system(\"rm -rf ./resource\") os.system(f\"python ./SST/image_classification_policy.py --log {log}\") print(f\"============================end",
"0, 0] negative_classes_weight = [0, 0, 0] positive_classes_weight = [0, 0, 0] negative_policy_weight",
"[0, 0, 0] positive_policy_weight = [0, 0, 0] for i in range(len(negative_identity_weight)): log",
"= [0, 0, 0] negative_policy_weight = [0, 0, 0] positive_policy_weight = [0, 0,"
] |
[
"True if object in RRsTYPES else False def isClass(self, object): \"\"\"returns True if",
"in the Zone\"\"\" return set([i[4] for i in self.table]) def getClasses(self): \"\"\"returns set",
"closed from zone file line\"\"\" self.zone = [self.zone[i].replace(\"(\", \"\").replace(\")\", \"\") if self.zone[i].count(\"(\") ==",
"for i in self.table]) def getTTLs(self): \"\"\"returns set of all available TTLs in",
"\"MX\", \"NAPTR\", \"NSAP\", \"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\", \"PX\", \"RP\", \"PRSIG\", \"RT\", \"SIG\",",
"avoid collaps of mapping for i in self.pop: self.zone.pop(i) def move(self, index): \"\"\"Merge",
"Exception handler\"\"\" def __init__(self, error, file): self.error = str(error) self.file = str(file) def",
"def getName(self, Name): \"\"\"Returns entrys matching the given name\"\"\" return [i for i",
"changes aren't supported per day.\"\"\" if len(self.serial) < 2: self.serial = \"0{0}\".format(self.serial) return",
"TTL): \"\"\"Returns entrys matching the given TTL\"\"\" return [i for i in self.table",
"self.paranthese += 1 self.use_index = i continue if \")\" in self.zone[i]: self.paranthese -=",
"liste: if self.isType(i): return i def getClass(self, liste): \"\"\"returns class of given entry\"\"\"",
"i in CLASSES]))) # also insecure self.cursor.executemany('INSERT INTO \"{0}\" VALUES (?,?,?,?,?,?)' .format(self.tableName), self.table)",
"from zone (;, #, /**/, //)\"\"\" if \";\" in self.zone_org: self.zone = [i.split(\";\")[0]",
"ID's // prim. keys of internal table\"\"\" return set([i[0] for i in self.table])",
"ttl, probatly class self.over = len(entry) if self.over == 3: if entry.pop(2) !=",
"a fatal logical error at {0}.\\nPlease contact support for more information\".format(\" \".join(entry))) self.over",
"if ID and ID != i[0]: continue if not isinstance(ID, bool) and ID",
"\"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(argv[2]) print(\"wrote database to {0}\".format(argv[2])) else:",
"self.connection if __name__ == \"__main__\": from sys import argv from os import path",
"i in self.table]) def getDefaultTTL(self): \"\"\"Returns last used TTL\"\"\" return self.TTL def getRecords(self,",
"NOT NULL, ttl INT, class VARCHAR({2}) NOT NULL, type VARCHAR({3}) NOT NULL, value",
"[self.zone[i].replace(\"(\", \"\").replace(\")\", \"\") if self.zone[i].count(\"(\") == self.zone[i].count(\")\") else self.zone[i] for i in range(len(self.zone))]",
"if self.over == 3: if entry.pop(2) != self.klasse: self.error(\"There occured a fatal logical",
"\"\"\"Returns Master-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self): \"\"\"Returns contact-field of SOA",
"ttl if entry[0] == self.klasse: entry.pop() elif self.isTTLobj(entry[0]): print(\"warning at {0}. I'll handle",
"for i in self.table if i[1] == Name] def getID(self, ID): \"\"\"Returns entrys",
"TTL record\"\"\" return True if liste[0] == '$TTL' and len(liste) < 3 else",
"given ID\"\"\" return [i for i in self.table if i[0] == ID] def",
"False, TTL = False, Class = False, Type = False, Value = False):",
"db, else connection object is returned\"\"\" import sqlite3 as sql if table: self.tableName",
"line. Normally it should work, but you should use it carefull - problems",
"i in self.zone if i != \";\"] if \"#\" in self.zone_org: self.zone =",
"eg.\"\"\" return True if object in CLASSES else False def isTTL(self, liste): \"\"\"returns",
"I'll handle it as TTL!\".format(\" | \".join([str(y) for y in (self.primKey, self.name, entry[0],",
"= [i.split(\"//\")[0] for i in self.zone if i != \"//\"] if \"/*\" in",
"\"IN\", Type=\"AAAA\")[0][5] def mkSerial(self, check = True): \"\"\"Sets timestamp allone. If check, no",
"for i in range(len(self.zone)): i -= self.subt # to compense the mapping collaps",
"Error occured: {1}\"\"\".format(self.file, self.error) class _Parser(): \"\"\"Main Parser\"\"\" def __init__(self, file): self.file =",
"set of all available ID's // prim. keys of internal table\"\"\" return set([i[0]",
"information\".format(\" \".join(entry))) self.over = len(entry) if self.over == 2: # Possible: class, ttl,",
"\"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\", \"PX\", \"RP\", \"PRSIG\", \"RT\", \"SIG\", \"SOA\", \"SPF\", \"SRV\", \"SSHFP\", \"TXT\",",
"if obeject is a class like IN, eg.\"\"\" return True if object in",
"error, file): self.error = str(error) self.file = str(file) def __str__(self): return \"\"\"Please check",
"= self.getSerial()[:8] self.new_time = strftime(\"%Y%m%d\") if self.old_time != self.new_time: self.serial = \"01\" else:",
"and i[0] != 0: continue if Domain and Domain != i[1]: continue if",
"getIndexe(self, pattern): \"\"\"return every index of fitting patter\"\"\" self.counter = 0 self.result =",
"elif len(argv) == 3: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1])",
"return True if liste[0] == '$TTL' and len(liste) < 3 else False def",
"Problems: \"db.mydomain.local\".count(\".\") != 0 -> mySQL Syntax error self.cursor.execute(\"\"\"CREATE TABLE '{0}' (id INT,",
"if len(argv) == 1: print(\"\"\" Bind Zonefile Parser ==================== Version: {0} Converts zone",
"self.zone[i].count(\"(\") == self.zone[i].count(\")\") else self.zone[i] for i in range(len(self.zone))] def mergeParanthese(self): \"\"\"Merge every",
"{TTL//class} -> !name if entry[1] == self.klasse: entry.pop() else: self.ttl = entry.pop() #",
"self.cursor.close() else: return self.connection if __name__ == \"__main__\": from sys import argv from",
"NOT NULL, type VARCHAR({3}) NOT NULL, value TEXT NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i) for",
"getIDs(self): \"\"\"returns set of all available ID's // prim. keys of internal table\"\"\"",
"self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese() self.split() self.cleanUp() self.parse() def error(self, error): \"\"\"returns error\"\"\" raise ZoneFileError(error,",
"0 while [i for i in self.zone if \"(\" in i or \")\"",
"def getType(self, liste): \"\"\"returns type of given entry\"\"\" for i in liste: if",
"self.name = entry[0] try: self.ttl = self.default_TTL except AttributeError: self.error(\"Please check your zonfile.",
"check the given zone file {0}.\\nFollowing Error occured: {1}\"\"\".format(self.file, self.error) class _Parser(): \"\"\"Main",
"self.file) def getIndexe(self, pattern): \"\"\"return every index of fitting patter\"\"\" self.counter = 0",
"str(file) def __str__(self): return \"\"\"Please check the given zone file {0}.\\nFollowing Error occured:",
"# RAM clean def getValues(self): \"\"\"returns set of all available Values in the",
"def getRefreshTime(self): \"\"\"Returns refersh time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[3] def",
"1 return self.result def rmComment(self): \"\"\"Removes comments from zone (;, #, /**/, //)\"\"\"",
"self.primKey += 1 class Parser(): \"\"\"Paser - Friendly User API\"\"\" def __init__(self, file):",
"[i for i in self.table if i[5] == Value] def getType(self, Type): \"\"\"Returns",
"ttl self.over = len(entry) if self.over == 1: # possible: name, class, ttl",
"\" \" + self.zone[index + 1] self.zone.pop(index + 1) def rmParanthese(self): \"\"\"removes paranthes",
"support for more information\".format(\" \".join(entry))) self.over = len(entry) if self.over == 2: #",
"= self.zonename self.connection = sql.connect(file) self.cursor = self.connection.cursor() self.cursor.execute(\"drop table if exists '{0}'\".format(self.tableName))",
"return [i for i in self.table if i[1] == Name] def getID(self, ID):",
"RAM clean def getValues(self): \"\"\"returns set of all available Values in the Zone\"\"\"",
"// prim. keys of internal table\"\"\" return set([i[0] for i in self.table]) def",
"else False def isTTLobj(self, object): \"\"\"Returns if given object is ttl. Warning: it's",
"in self.table if i[1] == Name] def getID(self, ID): \"\"\"Returns entrys matching the",
"serial > 99 are supported\"\"\" self.old_time = self.getSerial()[:8] self.new_time = strftime(\"%Y%m%d\") if self.old_time",
"Types in the Zone\"\"\" return set([i[4] for i in self.table]) def getClasses(self): \"\"\"returns",
"i in self.table]) def getTTLs(self): \"\"\"returns set of all available TTLs in the",
"= self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese() self.split() self.cleanUp() self.parse() def error(self, error): \"\"\"returns error\"\"\" raise",
"TTL\"\"\" return self.TTL def getRecords(self, ID = False, Domain = False, TTL =",
"one)\"\"\" return set([i[2] for i in self.table]) def getDomains(self): \"\"\"returns set of all",
"because of 23h for eg. def cleanUp(self): \"\"\"removes empty strings and lists from",
"if self.isType(i): return i def getClass(self, liste): \"\"\"returns class of given entry\"\"\" for",
"if entry[1] == self.klasse: entry.pop() else: self.ttl = entry.pop() # Has to be",
"the given name\"\"\" return [i for i in self.table if i[1] == Name]",
"returned\"\"\" import sqlite3 as sql if table: self.tableName = table else: self.tableName =",
"is TTL record\"\"\" return True if liste[0] == '$TTL' and len(liste) < 3",
"per line\") self.rmParanthese() del self.count def split(self): \"\"\"splits zone to fields\"\"\" self.zone =",
"entry.pop() else: self.ttl = entry.pop() # Has to be ttl self.over = len(entry)",
"self.zonename self.connection = sql.connect(file) self.cursor = self.connection.cursor() self.cursor.execute(\"drop table if exists '{0}'\".format(self.tableName)) #",
"self.error(\"Please check your zonfile. Error at {0}.\\nType not found\".format(\" \".join(entry))) if self.klasse: self.default_klasse",
"else: try: self.klasse = self.default_klasse except NameError: self.error(\"Please check your zonfile. Error at",
"return self.getType(\"SOA\")[0][5].split()[1] def getSerial(self): \"\"\"Returns serial-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self):",
"return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"AAAA\")[0][5] def mkSerial(self, check = True):",
"Type, Value]) def isType(self, object): \"\"\"returns true if object is a entry type",
"the Zone\"\"\" return set([i[3] for i in self.table]) def getTTLs(self): \"\"\"returns set of",
"self.name, entry[0], self.klasse, self.type, self.value)]))) # carefull!!! 123456d as dom -> undifined error",
"to sqlite database Stand Alone Usage: ./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv) == 2:",
"if not isinstance(ID, bool) and ID == 0 and i[0] != 0: continue",
"= list() self.counter = False for i in range(len(self.zone)): if \"/*\" in self.zone[i]:",
"\"\"\"Sets timestamp allone. If check, no serial > 99 are supported\"\"\" self.old_time =",
"def getExpireTime(self): \"\"\"Returns expire time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[5] def",
"in self.table if i[2] == str(TTL)] def getName(self, Name): \"\"\"Returns entrys matching the",
"i in self.zone if \"(\" in i or \")\" in i]: self.count +=",
"index of fitting patter\"\"\" self.counter = 0 self.result = list() for i in",
"self.default_TTL except AttributeError: self.error(\"Please check your zonfile. TTL not found\") self.handle(self.primKey, self.name,self.ttl, self.klasse,",
"given zone file {0}.\\nFollowing Error occured: {1}\"\"\".format(self.file, self.error) class _Parser(): \"\"\"Main Parser\"\"\" def",
"= [self.zone[i].replace(\"(\", \"\").replace(\")\", \"\") if self.zone[i].count(\"(\") == self.zone[i].count(\")\") else self.zone[i] for i in",
"for entry in self.zone: if self.isTTL(entry): self.default_TTL = entry[1] # default ttl continue",
"of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self): \"\"\"Returns refersh time - field of",
"entrys matching the given TTL\"\"\" return [i for i in self.table if i[2]",
"default ttl continue self.type = self.getType(entry) self.klasse = self.getClass(entry) if self.type: self.default_type =",
"self.zone: if self.isTTL(entry): self.default_TTL = entry[1] # default ttl continue self.type = self.getType(entry)",
"exists '{0}'\".format(self.tableName)) # insecure !!! Problems: \"db.mydomain.local\".count(\".\") != 0 -> mySQL Syntax error",
"file {0}.\\nFollowing Error occured: {1}\"\"\".format(self.file, self.error) class _Parser(): \"\"\"Main Parser\"\"\" def __init__(self, file):",
"insecure !!! Problems: \"db.mydomain.local\".count(\".\") != 0 -> mySQL Syntax error self.cursor.execute(\"\"\"CREATE TABLE '{0}'",
"Domain and Domain != i[1]: continue if TTL and TTL != i[2]: continue",
"if Type and Type != i[4]: continue if Value and Value != i[5]:",
"-= self.subt # to compense the mapping collaps try: self.zone[i] except IndexError: break",
"all available TTLs in the Zone (Normaly one)\"\"\" return set([i[2] for i in",
"getDomains(self): \"\"\"returns set of all available Domains in the Zone\"\"\" return set([i[1] for",
"given name\"\"\" return [i for i in self.table if i[1] == Name] def",
"of 23h for eg. def cleanUp(self): \"\"\"removes empty strings and lists from zone\"\"\"",
"\"X25\"] from time import strftime class ZoneFileError(Exception): \"\"\"Simple Exception handler\"\"\" def __init__(self, error,",
"self.table) if commit: self.connection.commit() self.cursor.close() else: return self.connection if __name__ == \"__main__\": from",
"getSerial(self): \"\"\"Returns serial-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self): \"\"\"Returns refersh time",
"Value = False): \"\"\"MetaGer - returns list of matching rows\"\"\" self.result = list()",
"len(self.serial) < 2: self.serial = \"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time, self.serial) def refresh(self): \"\"\"Reloads complete",
"in brackets - avoid using more then one bracket per line. Normally it",
"object is ttl. Warning: it's just probatly correct\"\"\" return True if object[:-1].isdigit() else",
"set([i[3] for i in self.table]) def getTTLs(self): \"\"\"returns set of all available TTLs",
"self.serial = \"01\" else: self.serial = str(int(self.getSerial()[8:]) + 1) if check: assert int(self.serial)",
"\"{0}\" VALUES (?,?,?,?,?,?)' .format(self.tableName), self.table) if commit: self.connection.commit() self.cursor.close() else: return self.connection if",
"self.TTL def getRecords(self, ID = False, Domain = False, TTL = False, Class",
"= \"@\", Class = \"IN\", Type=\"AAAA\")[0][5] def mkSerial(self, check = True): \"\"\"Sets timestamp",
"ID != i[0]: continue if not isinstance(ID, bool) and ID == 0 and",
"record\"\"\" return self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self): \"\"\"Returns negative cache time - field of SOA",
"True if object in CLASSES else False def isTTL(self, liste): \"\"\"returns True if",
"+= 1 self.rmParanthese() self.mergeParanthese() if self.count > 100: self.error(\"Paranthese Syntax: Please avoid using",
"return set([i[3] for i in self.table]) def getTTLs(self): \"\"\"returns set of all available",
"import sqlite3 as sql if table: self.tableName = table else: self.tableName = self.zonename",
"VARCHAR({1}) NOT NULL, ttl INT, class VARCHAR({2}) NOT NULL, type VARCHAR({3}) NOT NULL,",
"i[0]: continue if not isinstance(ID, bool) and ID == 0 and i[0] !=",
"found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database to zone.sqlite\") elif len(argv) == 3:",
"i[4]: continue if Value and Value != i[5]: continue self.result.append(i) return self.result def",
"ID] def getMaster(self): \"\"\"Returns Master-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self): \"\"\"Returns",
"error\"\"\" raise ZoneFileError(error, self.file) def getIndexe(self, pattern): \"\"\"return every index of fitting patter\"\"\"",
"strings and lists from zone\"\"\" self.zone = [i for i in self.zone if",
"[i.split(\";\")[0] for i in self.zone if i != \";\"] if \"#\" in self.zone_org:",
"value\"\"\" return [i for i in self.table if i[5] == Value] def getType(self,",
"in self.table if i[0] == ID] def getMaster(self): \"\"\"Returns Master-field of SOA record\"\"\"",
"i in self.table]) def getClasses(self): \"\"\"returns set of all available classes in the",
"entry.pop(2) != self.klasse: self.error(\"There occured a fatal logical error at {0}.\\nPlease contact support",
"paranthes from zone by merging\"\"\" self.count = 0 while [i for i in",
"= 0 for i in range(len(self.zone)): i -= self.subt # to compense the",
"self.rmComment() self.rmCompleteParanthese() self.split() self.cleanUp() self.parse() def error(self, error): \"\"\"returns error\"\"\" raise ZoneFileError(error, self.file)",
"in self.zone] def handle(self, primKey, Name, TTL, Class, Type, Value): \"\"\"Handler for parser",
"table\"\"\" return set([i[0] for i in self.table]) def getDefaultTTL(self): \"\"\"Returns last used TTL\"\"\"",
"self.zone = [i.split() for i in self.zone] def handle(self, primKey, Name, TTL, Class,",
"if i != \"#\"] if \"//\" in self.zone_org: self.zone = [i.split(\"//\")[0] for i",
"if \"(\" in self.zone[i]: self.paranthese += 1 self.use_index = i continue if \")\"",
"= sql.connect(file) self.cursor = self.connection.cursor() self.cursor.execute(\"drop table if exists '{0}'\".format(self.tableName)) # insecure !!!",
"\"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database to zone.sqlite\") elif",
"continue if not isinstance(ID, bool) and ID == 0 and i[0] != 0:",
"\"\"\"Returns refersh time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self): \"\"\"Returns",
"index + 1 with index.\"\"\" self.zone[index] += \" \" + self.zone[index + 1]",
"/**/, //)\"\"\" if \";\" in self.zone_org: self.zone = [i.split(\";\")[0] for i in self.zone",
"= self.default_TTL except AttributeError: self.error(\"Please check your zonfile. TTL not found\") self.handle(self.primKey, self.name,self.ttl,",
"file self.parser = _Parser(file) self.table = self.parser.Table self.TTL = self.parser.default_TTL self.zonename = path.basename(self.file)",
"# Possible: class, ttl, name but: entry[1] = {TTL//class} -> !name if entry[1]",
"Class = \"IN\", Type=\"AAAA\")[0][5] def mkSerial(self, check = True): \"\"\"Sets timestamp allone. If",
"if i != \"//\"] if \"/*\" in self.zone_org: self.pop = list() self.counter =",
"self.paranthese = 0 self.subt = 0 for i in range(len(self.zone)): i -= self.subt",
"you get all data -> api\"\"\" # later mySQL? self.Table.append([primKey, Name, TTL, Class,",
"import argv from os import path as path if len(argv) == 1: print(\"\"\"",
"isClass(self, object): \"\"\"returns True if obeject is a class like IN, eg.\"\"\" return",
"Error at {0}.\\nClass not found\".format(\" \".join(entry))) self.typeindex = entry.index(self.type) self.value = \" \".join(entry[self.typeindex+1:])",
"SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[1] def getSerial(self): \"\"\"Returns serial-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[2]",
"i[2]: continue if Class and Class != i[3]: continue if Type and Type",
"by merging\"\"\" self.count = 0 while [i for i in self.zone if \"(\"",
"if self.type: self.default_type = self.type else: try: self.type = self.default_type except NameError: self.error(\"Please",
"return [i for i in self.table if i[3] == Class] def getTTL(self, TTL):",
"self.table]) def getDefaultTTL(self): \"\"\"Returns last used TTL\"\"\" return self.TTL def getRecords(self, ID =",
"of fitting patter\"\"\" self.counter = 0 self.result = list() for i in range(self.zone_org.count(pattern)):",
"99 changes aren't supported per day.\"\"\" if len(self.serial) < 2: self.serial = \"0{0}\".format(self.serial)",
"sql.connect(file) self.cursor = self.connection.cursor() self.cursor.execute(\"drop table if exists '{0}'\".format(self.tableName)) # insecure !!! Problems:",
"no serial > 99 are supported\"\"\" self.old_time = self.getSerial()[:8] self.new_time = strftime(\"%Y%m%d\") if",
"zone\"\"\" self.zone = [i for i in self.zone if i and i[0] !=",
"= self.default_klasse except NameError: self.error(\"Please check your zonfile. Error at {0}.\\nClass not found\".format(\"",
"self.zone_org: self.zone = [i.split(\"//\")[0] for i in self.zone if i != \"//\"] if",
"< 3 else False def isTTLobj(self, object): \"\"\"Returns if given object is ttl.",
"getClasses(self): \"\"\"returns set of all available classes in the Zone\"\"\" return set([i[3] for",
"else: self.serial = str(int(self.getSerial()[8:]) + 1) if check: assert int(self.serial) < 100, \"\"\"More",
"if i[4] == Type] def getClass(self, Class): \"\"\"Returns entrys matching the given class\"\"\"",
"getClass(self, liste): \"\"\"returns class of given entry\"\"\" for i in liste: if self.isClass(i):",
"TTL!\".format(\" | \".join([str(y) for y in (self.primKey, self.name, entry[0], self.klasse, self.type, self.value)]))) #",
"set([i[4] for i in self.table]) def getClasses(self): \"\"\"returns set of all available classes",
"\"\"\"removes empty strings and lists from zone\"\"\" self.zone = [i for i in",
"\"\"\"Returns entrys matching the given class\"\"\" return [i for i in self.table if",
"for i in self.table]) def getDefaultTTL(self): \"\"\"Returns last used TTL\"\"\" return self.TTL def",
"\";\"] if \"#\" in self.zone_org: self.zone = [i.split(\"#\")[0] for i in self.zone if",
"connection object is returned\"\"\" import sqlite3 as sql if table: self.tableName = table",
"per line. Normally it should work, but you should use it carefull -",
"\"DNSKEY\", \"DS\", \"GPOS\", \"HINFO\", \"IPSECKEY\", \"ISDN\", \"KEY\", \"KX\", \"LOC\", \"MX\", \"NAPTR\", \"NSAP\", \"NS\",",
"== self.klasse: entry.pop() else: self.ttl = entry.pop() # Has to be ttl self.over",
"== Value] def getType(self, Type): \"\"\"Returns entrys matching the given type\"\"\" return [i",
"for i in range(len(self.zone))] def mergeParanthese(self): \"\"\"Merge every paranthes to one line\"\"\" self.paranthese",
"self.value)]))) # carefull!!! 123456d as dom -> undifined error self.ttl = entry.pop() else:",
"getID(self, ID): \"\"\"Returns entrys matching the given ID\"\"\" return [i for i in",
"in self.table: if ID and ID != i[0]: continue if not isinstance(ID, bool)",
"in i]: self.count += 1 self.rmParanthese() self.mergeParanthese() if self.count > 100: self.error(\"Paranthese Syntax:",
"self.zone_org: self.pop = list() self.counter = False for i in range(len(self.zone)): if \"/*\"",
"at {0}.\\nClass not found\".format(\" \".join(entry))) self.typeindex = entry.index(self.type) self.value = \" \".join(entry[self.typeindex+1:]) entry",
"= entry.index(self.type) self.value = \" \".join(entry[self.typeindex+1:]) entry = entry[:self.typeindex] # left: probatly name,",
"read brackets in brackets - avoid using more then one bracket per line.",
"== 3: if entry.pop(2) != self.klasse: self.error(\"There occured a fatal logical error at",
"- returns list of matching rows\"\"\" self.result = list() for i in self.table:",
"1 class Parser(): \"\"\"Paser - Friendly User API\"\"\" def __init__(self, file): import os.path",
"entry in self.zone: if self.isTTL(entry): self.default_TTL = entry[1] # default ttl continue self.type",
"= [i.split(\";\")[0] for i in self.zone if i != \";\"] if \"#\" in",
"to compense the mapping collaps try: self.zone[i] except IndexError: break if \"(\" in",
"else False def isClass(self, object): \"\"\"returns True if obeject is a class like",
"brackets - avoid using more then one bracket per line. Normally it should",
"by differncing ttl/domaine, if domain[:-1].isdigit()\"\"\" VERSION = 1.1 DOMAIN_MAX_LENGHT = 255 CLASSES =",
"i[1] == Name] def getID(self, ID): \"\"\"Returns entrys matching the given ID\"\"\" return",
"day.\"\"\" if len(self.serial) < 2: self.serial = \"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time, self.serial) def refresh(self):",
"self.table = self.parser.Table self.TTL = self.parser.default_TTL self.zonename = path.basename(self.file) del self.parser # RAM",
"file, table = None, commit = True): \"\"\"Writes results to sql database. If",
"Type] def getClass(self, Class): \"\"\"Returns entrys matching the given class\"\"\" return [i for",
"of mapping for i in self.pop: self.zone.pop(i) def move(self, index): \"\"\"Merge index +",
"= entry[:self.typeindex] # left: probatly name, probatly ttl, probatly class self.over = len(entry)",
"False def isTTLobj(self, object): \"\"\"Returns if given object is ttl. Warning: it's just",
"in self.zone: if self.isTTL(entry): self.default_TTL = entry[1] # default ttl continue self.type =",
"self.default_TTL = entry[1] # default ttl continue self.type = self.getType(entry) self.klasse = self.getClass(entry)",
"\"\"\"returns set of all available TTLs in the Zone (Normaly one)\"\"\" return set([i[2]",
"retry time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self): \"\"\"Returns expire",
"object in RRsTYPES else False def isClass(self, object): \"\"\"returns True if obeject is",
"your zonfile. TTL not found\") self.handle(self.primKey, self.name,self.ttl, self.klasse, self.type, self.value) del self.value self.primKey",
"if table: self.tableName = table else: self.tableName = self.zonename self.connection = sql.connect(file) self.cursor",
"+= 1 def rmCompleteParanthese(self): \"\"\"removes every paranthes from zone by merging\"\"\" self.count =",
"convert2sqlite(self, file, table = None, commit = True): \"\"\"Writes results to sql database.",
"getTTL(self, TTL): \"\"\"Returns entrys matching the given TTL\"\"\" return [i for i in",
"self.table if i[2] == str(TTL)] def getName(self, Name): \"\"\"Returns entrys matching the given",
"committed to db, else connection object is returned\"\"\" import sqlite3 as sql if",
"self.getClass(entry) if self.type: self.default_type = self.type else: try: self.type = self.default_type except NameError:",
"Name): \"\"\"Returns entrys matching the given name\"\"\" return [i for i in self.table",
"self.stream.close() self.zone = self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese() self.split() self.cleanUp() self.parse() def error(self, error): \"\"\"returns",
"1: print(\"\"\" Bind Zonefile Parser ==================== Version: {0} Converts zone file to sqlite",
"elif self.isTTLobj(entry[0]): print(\"warning at {0}. I'll handle it as TTL!\".format(\" | \".join([str(y) for",
"\".join(entry))) self.typeindex = entry.index(self.type) self.value = \" \".join(entry[self.typeindex+1:]) entry = entry[:self.typeindex] # left:",
"NULL, type VARCHAR({3}) NOT NULL, value TEXT NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i) for i",
"+= \" \" + self.zone[index + 1] self.zone.pop(index + 1) def rmParanthese(self): \"\"\"removes",
"or more then more paranthese per line\") self.rmParanthese() del self.count def split(self): \"\"\"splits",
"Normally it should work, but you should use it carefull - problems by",
"\"RP\", \"PRSIG\", \"RT\", \"SIG\", \"SOA\", \"SPF\", \"SRV\", \"SSHFP\", \"TXT\", \"WKS\", \"X25\"] from time",
"else: try: self.type = self.default_type except NameError: self.error(\"Please check your zonfile. Error at",
"and len(liste) < 3 else False def isTTLobj(self, object): \"\"\"Returns if given object",
"= True) # To avoid collaps of mapping for i in self.pop: self.zone.pop(i)",
"in self.zone_org: self.zone = [i.split(\";\")[0] for i in self.zone if i != \";\"]",
"path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database to zone.sqlite\")",
"aren't supported per day.\"\"\" if len(self.serial) < 2: self.serial = \"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time,",
"for i in RRsTYPES]), max([len(i) for i in CLASSES]))) # also insecure self.cursor.executemany('INSERT",
"self.count > 100: self.error(\"Paranthese Syntax: Please avoid using Paranthese in Paranthese or more",
"== 0 and i[0] != 0: continue if Domain and Domain != i[1]:",
"\"LOC\", \"MX\", \"NAPTR\", \"NSAP\", \"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\", \"PX\", \"RP\", \"PRSIG\", \"RT\",",
"error at {0}.\\nPlease contact support for more information\".format(\" \".join(entry))) self.over = len(entry) if",
"a class like IN, eg.\"\"\" return True if object in CLASSES else False",
"self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self): \"\"\"Returns negative cache time - field of SOA record\"\"\" return",
"and lists from zone\"\"\" self.zone = [i for i in self.zone if i",
"class, ttl, name but: entry[1] = {TTL//class} -> !name if entry[1] == self.klasse:",
"try: self.type = self.default_type except NameError: self.error(\"Please check your zonfile. Error at {0}.\\nType",
"continue if \")\" in self.zone[i]: self.paranthese -= 1 self.move(self.use_index) self.subt += 1 continue",
"self.zone[i] = self.zone[i].split(\"/*\")[0] continue if \"*/\" in self.zone[i]: self.pop.append(i) # warnig: complete line",
"entry type like NS, eg.\"\"\" return True if object in RRsTYPES else False",
"Zonefile Parser ==================== Version: {0} Converts zone file to sqlite database Stand Alone",
"__init__(self, file): import os.path as path self.file = file self.parser = _Parser(file) self.table",
"it's just probatly correct\"\"\" return True if object[:-1].isdigit() else False # -1 because",
"if i[1] == Name] def getID(self, ID): \"\"\"Returns entrys matching the given ID\"\"\"",
"list() for i in self.table: if ID and ID != i[0]: continue if",
"def __init__(self, error, file): self.error = str(error) self.file = str(file) def __str__(self): return",
"in self.table]) def getDefaultTTL(self): \"\"\"Returns last used TTL\"\"\" return self.TTL def getRecords(self, ID",
"to db, else connection object is returned\"\"\" import sqlite3 as sql if table:",
"TTL not found\") self.handle(self.primKey, self.name,self.ttl, self.klasse, self.type, self.value) del self.value self.primKey += 1",
"commit = [True] chnages are automatic committed to db, else connection object is",
"i in self.table]) def getTypes(self): \"\"\"returns set of all available Types in the",
"i in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter)) self.counter = self.result[-1] + 1 return self.result def",
"self.mergeParanthese() if self.count > 100: self.error(\"Paranthese Syntax: Please avoid using Paranthese in Paranthese",
"from zone\"\"\" self.zone = [i for i in self.zone if i and i[0]",
"#, /**/, //)\"\"\" if \";\" in self.zone_org: self.zone = [i.split(\";\")[0] for i in",
"more then one bracket per line. Normally it should work, but you should",
"for i in range(len(self.zone)): if \"/*\" in self.zone[i]: self.counter = True self.zone[i] =",
"continue if Domain and Domain != i[1]: continue if TTL and TTL !=",
"self.zone = [i.split(\"//\")[0] for i in self.zone if i != \"//\"] if \"/*\"",
"from zone is TTL record\"\"\" return True if liste[0] == '$TTL' and len(liste)",
"= False, Class = False, Type = False, Value = False): \"\"\"MetaGer -",
"= strftime(\"%Y%m%d\") if self.old_time != self.new_time: self.serial = \"01\" else: self.serial = str(int(self.getSerial()[8:])",
"return [i for i in self.table if i[4] == Type] def getClass(self, Class):",
"is returned\"\"\" import sqlite3 as sql if table: self.tableName = table else: self.tableName",
"are supported\"\"\" self.old_time = self.getSerial()[:8] self.new_time = strftime(\"%Y%m%d\") if self.old_time != self.new_time: self.serial",
"parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database to zone.sqlite\") elif len(argv) == 3: assert path.isfile(argv[1]), \"Zonefile {0}",
"False for i in range(len(self.zone)): if \"/*\" in self.zone[i]: self.counter = True self.zone[i]",
"rmParanthese(self): \"\"\"removes paranthes if closed from zone file line\"\"\" self.zone = [self.zone[i].replace(\"(\", \"\").replace(\")\",",
"record\"\"\" return self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self): \"\"\"Returns retry time - field of SOA record\"\"\"",
"self.zone[i] except IndexError: break if \"(\" in self.zone[i]: self.paranthese += 1 self.use_index =",
"VERSION = 1.1 DOMAIN_MAX_LENGHT = 255 CLASSES = [\"IN\", \"HS\", \"CH\", \"CS\"] RRsTYPES",
"in self.zone[i]: self.pop.append(i) # warnig: complete line is removed. Problem with: /*comment\\nbla\\nbla*/command? self.counter",
"class, ttl if entry[0] == self.klasse: entry.pop() elif self.isTTLobj(entry[0]): print(\"warning at {0}. I'll",
"\"\"\"Return current IPv6 addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\",",
"ttl, class, type, value] self.stream = open(file) self.zone_org = self.stream.read() self.stream.close() self.zone =",
"return [i for i in self.table if i[0] == ID] def getMaster(self): \"\"\"Returns",
"i != \"//\"] if \"/*\" in self.zone_org: self.pop = list() self.counter = False",
"\"\"\"returns set of all available classes in the Zone\"\"\" return set([i[3] for i",
"max([len(i) for i in RRsTYPES]), max([len(i) for i in CLASSES]))) # also insecure",
"== Class] def getTTL(self, TTL): \"\"\"Returns entrys matching the given TTL\"\"\" return [i",
"\"HS\", \"CH\", \"CS\"] RRsTYPES = [\"A\",\"AAAA\", \"A6\", \"AFSDB\", \"APL\", \"CERT\", \"CNAME\", \"DHCID\", \"DNAME\",",
"i[4] == Type] def getClass(self, Class): \"\"\"Returns entrys matching the given class\"\"\" return",
"False, Type = False, Value = False): \"\"\"MetaGer - returns list of matching",
"i[3] == Class] def getTTL(self, TTL): \"\"\"Returns entrys matching the given TTL\"\"\" return",
"path self.file = file self.parser = _Parser(file) self.table = self.parser.Table self.TTL = self.parser.default_TTL",
"Type=\"AAAA\")[0][5] def mkSerial(self, check = True): \"\"\"Sets timestamp allone. If check, no serial",
"NS, eg.\"\"\" return True if object in RRsTYPES else False def isClass(self, object):",
"range(len(self.zone)): i -= self.subt # to compense the mapping collaps try: self.zone[i] except",
"-> undifined error self.ttl = entry.pop() else: self.name = entry[0] try: self.ttl =",
"if check: assert int(self.serial) < 100, \"\"\"More then 99 changes aren't supported per",
"{0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(argv[2]) print(\"wrote database to {0}\".format(argv[2])) else: print(\"To",
"for eg. def cleanUp(self): \"\"\"removes empty strings and lists from zone\"\"\" self.zone =",
"Syntax: Please avoid using Paranthese in Paranthese or more then more paranthese per",
"def getIDs(self): \"\"\"returns set of all available ID's // prim. keys of internal",
"continue if TTL and TTL != i[2]: continue if Class and Class !=",
"bracket per line. Normally it should work, but you should use it carefull",
"ttl INT, class VARCHAR({2}) NOT NULL, type VARCHAR({3}) NOT NULL, value TEXT NOT",
"with: /*comment\\nbla\\nbla*/command? self.counter = False continue if self.counter: self.pop.append(i) self.pop.sort(reverse = True) #",
"every paranthes to one line\"\"\" self.paranthese = 0 self.subt = 0 for i",
"strftime(\"%Y%m%d\") if self.old_time != self.new_time: self.serial = \"01\" else: self.serial = str(int(self.getSerial()[8:]) +",
"getType(self, liste): \"\"\"returns type of given entry\"\"\" for i in liste: if self.isType(i):",
"be ttl self.over = len(entry) if self.over == 1: # possible: name, class,",
"- avoid using more then one bracket per line. Normally it should work,",
"name, class, ttl if entry[0] == self.klasse: entry.pop() elif self.isTTLobj(entry[0]): print(\"warning at {0}.",
"i[0] != ''] def getType(self, liste): \"\"\"returns type of given entry\"\"\" for i",
"API\"\"\" def __init__(self, file): import os.path as path self.file = file self.parser =",
"# later mySQL? self.Table.append([primKey, Name, TTL, Class, Type, Value]) def isType(self, object): \"\"\"returns",
"\"//\" in self.zone_org: self.zone = [i.split(\"//\")[0] for i in self.zone if i !=",
"the Zone\"\"\" return set([i[1] for i in self.table]) def getIDs(self): \"\"\"returns set of",
"entrys matching the given class\"\"\" return [i for i in self.table if i[3]",
"type of given entry\"\"\" for i in liste: if self.isType(i): return i def",
"record\"\"\" return self.getType(\"SOA\")[0][5].split()[1] def getSerial(self): \"\"\"Returns serial-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[2] def",
"[i.split() for i in self.zone] def handle(self, primKey, Name, TTL, Class, Type, Value):",
"True if given list from zone is TTL record\"\"\" return True if liste[0]",
"Parser(): \"\"\"Paser - Friendly User API\"\"\" def __init__(self, file): import os.path as path",
"getRecords(self, ID = False, Domain = False, TTL = False, Class = False,",
"complete zone\"\"\" self.__init__(self.file) def convert2sqlite(self, file, table = None, commit = True): \"\"\"Writes",
"clean def getValues(self): \"\"\"returns set of all available Values in the Zone\"\"\" return",
"as TTL!\".format(\" | \".join([str(y) for y in (self.primKey, self.name, entry[0], self.klasse, self.type, self.value)])))",
"#!/usr/bin/env python3 \"\"\" Limits: - can't read brackets in brackets - avoid using",
"error(self, error): \"\"\"returns error\"\"\" raise ZoneFileError(error, self.file) def getIndexe(self, pattern): \"\"\"return every index",
"if Class and Class != i[3]: continue if Type and Type != i[4]:",
"zone is TTL record\"\"\" return True if liste[0] == '$TTL' and len(liste) <",
"range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter)) self.counter = self.result[-1] + 1 return self.result def rmComment(self): \"\"\"Removes",
"it as TTL!\".format(\" | \".join([str(y) for y in (self.primKey, self.name, entry[0], self.klasse, self.type,",
"def getMaster(self): \"\"\"Returns Master-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self): \"\"\"Returns contact-field",
"return self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self): \"\"\"Returns refersh time - field of SOA record\"\"\" return",
"returns list of matching rows\"\"\" self.result = list() for i in self.table: if",
"!name if entry[1] == self.klasse: entry.pop() else: self.ttl = entry.pop() # Has to",
"Paranthese or more then more paranthese per line\") self.rmParanthese() del self.count def split(self):",
"INT, class VARCHAR({2}) NOT NULL, type VARCHAR({3}) NOT NULL, value TEXT NOT NULL)\"\"\".format(self.tableName,",
"if commit: self.connection.commit() self.cursor.close() else: return self.connection if __name__ == \"__main__\": from sys",
"if object is a entry type like NS, eg.\"\"\" return True if object",
"\"#\" in self.zone_org: self.zone = [i.split(\"#\")[0] for i in self.zone if i !=",
"is a class like IN, eg.\"\"\" return True if object in CLASSES else",
"raise ZoneFileError(error, self.file) def getIndexe(self, pattern): \"\"\"return every index of fitting patter\"\"\" self.counter",
"> 100: self.error(\"Paranthese Syntax: Please avoid using Paranthese in Paranthese or more then",
"\"NSAP\", \"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\", \"PX\", \"RP\", \"PRSIG\", \"RT\", \"SIG\", \"SOA\", \"SPF\",",
"all data -> api\"\"\" # later mySQL? self.Table.append([primKey, Name, TTL, Class, Type, Value])",
"self.isTTLobj(entry[0]): print(\"warning at {0}. I'll handle it as TTL!\".format(\" | \".join([str(y) for y",
"\"A6\", \"AFSDB\", \"APL\", \"CERT\", \"CNAME\", \"DHCID\", \"DNAME\", \"DNSKEY\", \"DS\", \"GPOS\", \"HINFO\", \"IPSECKEY\", \"ISDN\",",
"primKey, Name, TTL, Class, Type, Value): \"\"\"Handler for parser return. Here you get",
"available Types in the Zone\"\"\" return set([i[4] for i in self.table]) def getClasses(self):",
"0 self.subt = 0 for i in range(len(self.zone)): i -= self.subt # to",
"prim. keys of internal table\"\"\" return set([i[0] for i in self.table]) def getDefaultTTL(self):",
"error self.cursor.execute(\"\"\"CREATE TABLE '{0}' (id INT, domain VARCHAR({1}) NOT NULL, ttl INT, class",
"self.zone[i] for i in range(len(self.zone))] def mergeParanthese(self): \"\"\"Merge every paranthes to one line\"\"\"",
"Type, Value): \"\"\"Handler for parser return. Here you get all data -> api\"\"\"",
"If check, no serial > 99 are supported\"\"\" self.old_time = self.getSerial()[:8] self.new_time =",
"left: probatly name, probatly ttl, probatly class self.over = len(entry) if self.over ==",
"self.serial = str(int(self.getSerial()[8:]) + 1) if check: assert int(self.serial) < 100, \"\"\"More then",
"in the Zone\"\"\" return set([i[5] for i in self.table]) def getTypes(self): \"\"\"returns set",
"sys import argv from os import path as path if len(argv) == 1:",
"self.pop.append(i) self.pop.sort(reverse = True) # To avoid collaps of mapping for i in",
"False def isTTL(self, liste): \"\"\"returns True if given list from zone is TTL",
"DOMAIN_MAX_LENGHT, max([len(i) for i in RRsTYPES]), max([len(i) for i in CLASSES]))) # also",
"\"\"\"returns True if given list from zone is TTL record\"\"\" return True if",
"\" + self.zone[index + 1] self.zone.pop(index + 1) def rmParanthese(self): \"\"\"removes paranthes if",
"for i in liste: if self.isType(i): return i def getClass(self, liste): \"\"\"returns class",
"DOMAIN_MAX_LENGHT = 255 CLASSES = [\"IN\", \"HS\", \"CH\", \"CS\"] RRsTYPES = [\"A\",\"AAAA\", \"A6\",",
"complete line is removed. Problem with: /*comment\\nbla\\nbla*/command? self.counter = False continue if self.counter:",
"cleanUp(self): \"\"\"removes empty strings and lists from zone\"\"\" self.zone = [i for i",
"if self.zone[i].count(\"(\") == self.zone[i].count(\")\") else self.zone[i] for i in range(len(self.zone))] def mergeParanthese(self): \"\"\"Merge",
"self.serial = \"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time, self.serial) def refresh(self): \"\"\"Reloads complete zone\"\"\" self.__init__(self.file) def",
"self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self): \"\"\"Return current IPv4 addr of origin\"\"\" return self.getRecords(Domain = \"@\",",
"available classes in the Zone\"\"\" return set([i[3] for i in self.table]) def getTTLs(self):",
"parser = Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database to zone.sqlite\") elif len(argv) == 3: assert",
"error): \"\"\"returns error\"\"\" raise ZoneFileError(error, self.file) def getIndexe(self, pattern): \"\"\"return every index of",
"\"\"\"return every index of fitting patter\"\"\" self.counter = 0 self.result = list() for",
"matching the given TTL\"\"\" return [i for i in self.table if i[2] ==",
"self.value = \" \".join(entry[self.typeindex+1:]) entry = entry[:self.typeindex] # left: probatly name, probatly ttl,",
"self.ttl = self.default_TTL except AttributeError: self.error(\"Please check your zonfile. TTL not found\") self.handle(self.primKey,",
"TTL and TTL != i[2]: continue if Class and Class != i[3]: continue",
"import strftime class ZoneFileError(Exception): \"\"\"Simple Exception handler\"\"\" def __init__(self, error, file): self.error =",
"self.over = len(entry) if self.over == 1: # possible: name, class, ttl if",
"self.table]) def getIDs(self): \"\"\"returns set of all available ID's // prim. keys of",
"def rmComment(self): \"\"\"Removes comments from zone (;, #, /**/, //)\"\"\" if \";\" in",
"self.cleanUp() self.parse() def error(self, error): \"\"\"returns error\"\"\" raise ZoneFileError(error, self.file) def getIndexe(self, pattern):",
"i != \";\"] if \"#\" in self.zone_org: self.zone = [i.split(\"#\")[0] for i in",
"index.\"\"\" self.zone[index] += \" \" + self.zone[index + 1] self.zone.pop(index + 1) def",
"[i for i in self.table if i[4] == Type] def getClass(self, Class): \"\"\"Returns",
"def mergeParanthese(self): \"\"\"Merge every paranthes to one line\"\"\" self.paranthese = 0 self.subt =",
"split(self): \"\"\"splits zone to fields\"\"\" self.zone = [i.split() for i in self.zone] def",
"object[:-1].isdigit() else False # -1 because of 23h for eg. def cleanUp(self): \"\"\"removes",
"ZoneFileError(error, self.file) def getIndexe(self, pattern): \"\"\"return every index of fitting patter\"\"\" self.counter =",
"\"\"\"Handler for parser return. Here you get all data -> api\"\"\" # later",
"(id INT, domain VARCHAR({1}) NOT NULL, ttl INT, class VARCHAR({2}) NOT NULL, type",
"self.table]) def getDomains(self): \"\"\"returns set of all available Domains in the Zone\"\"\" return",
"then one bracket per line. Normally it should work, but you should use",
"if self.paranthese: self.move(self.use_index) self.subt += 1 def rmCompleteParanthese(self): \"\"\"removes every paranthes from zone",
"return i def getClass(self, liste): \"\"\"returns class of given entry\"\"\" for i in",
"of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self): \"\"\"Returns negative cache time - field",
"Name, TTL, Class, Type, Value]) def isType(self, object): \"\"\"returns true if object is",
"found\") self.handle(self.primKey, self.name,self.ttl, self.klasse, self.type, self.value) del self.value self.primKey += 1 class Parser():",
"Type != i[4]: continue if Value and Value != i[5]: continue self.result.append(i) return",
"Error at {0}.\\nType not found\".format(\" \".join(entry))) if self.klasse: self.default_klasse = self.klasse else: try:",
"\"KEY\", \"KX\", \"LOC\", \"MX\", \"NAPTR\", \"NSAP\", \"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\", \"PX\", \"RP\",",
"insecure self.cursor.executemany('INSERT INTO \"{0}\" VALUES (?,?,?,?,?,?)' .format(self.tableName), self.table) if commit: self.connection.commit() self.cursor.close() else:",
"collaps of mapping for i in self.pop: self.zone.pop(i) def move(self, index): \"\"\"Merge index",
"i in self.zone if i != \"#\"] if \"//\" in self.zone_org: self.zone =",
"using Paranthese in Paranthese or more then more paranthese per line\") self.rmParanthese() del",
"zonename is used if commit = [True] chnages are automatic committed to db,",
"import os.path as path self.file = file self.parser = _Parser(file) self.table = self.parser.Table",
"one bracket per line. Normally it should work, but you should use it",
"Class = False, Type = False, Value = False): \"\"\"MetaGer - returns list",
"False): \"\"\"MetaGer - returns list of matching rows\"\"\" self.result = list() for i",
"i[5] == Value] def getType(self, Type): \"\"\"Returns entrys matching the given type\"\"\" return",
"record\"\"\" return self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self): \"\"\"Returns refersh time - field of SOA record\"\"\"",
"Warning: it's just probatly correct\"\"\" return True if object[:-1].isdigit() else False # -1",
"= [\"A\",\"AAAA\", \"A6\", \"AFSDB\", \"APL\", \"CERT\", \"CNAME\", \"DHCID\", \"DNAME\", \"DNSKEY\", \"DS\", \"GPOS\", \"HINFO\",",
"self.TTL = self.parser.default_TTL self.zonename = path.basename(self.file) del self.parser # RAM clean def getValues(self):",
"list() self.Table = list() # format: [primKey, name, ttl, class, type, value] self.stream",
"try: self.ttl = self.default_TTL except AttributeError: self.error(\"Please check your zonfile. TTL not found\")",
"for i in self.zone if i and i[0] != ''] def getType(self, liste):",
"# To avoid collaps of mapping for i in self.pop: self.zone.pop(i) def move(self,",
"object is returned\"\"\" import sqlite3 as sql if table: self.tableName = table else:",
"object is a entry type like NS, eg.\"\"\" return True if object in",
"if \"#\" in self.zone_org: self.zone = [i.split(\"#\")[0] for i in self.zone if i",
"all available classes in the Zone\"\"\" return set([i[3] for i in self.table]) def",
"self.table if i[5] == Value] def getType(self, Type): \"\"\"Returns entrys matching the given",
"self.counter = 0 self.result = list() for i in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter)) self.counter",
"just probatly correct\"\"\" return True if object[:-1].isdigit() else False # -1 because of",
"self.error(\"Please check your zonfile. TTL not found\") self.handle(self.primKey, self.name,self.ttl, self.klasse, self.type, self.value) del",
"try: self.zone[i] except IndexError: break if \"(\" in self.zone[i]: self.paranthese += 1 self.use_index",
"self.table]) def getTTLs(self): \"\"\"returns set of all available TTLs in the Zone (Normaly",
"\"\"\"returns set of all available Types in the Zone\"\"\" return set([i[4] for i",
"def mkSerial(self, check = True): \"\"\"Sets timestamp allone. If check, no serial >",
"!= self.new_time: self.serial = \"01\" else: self.serial = str(int(self.getSerial()[8:]) + 1) if check:",
"occured: {1}\"\"\".format(self.file, self.error) class _Parser(): \"\"\"Main Parser\"\"\" def __init__(self, file): self.file = file",
"def getDomains(self): \"\"\"returns set of all available Domains in the Zone\"\"\" return set([i[1]",
"self.over == 3: if entry.pop(2) != self.klasse: self.error(\"There occured a fatal logical error",
"self.klasse, self.type, self.value) del self.value self.primKey += 1 class Parser(): \"\"\"Paser - Friendly",
"getTTLs(self): \"\"\"returns set of all available TTLs in the Zone (Normaly one)\"\"\" return",
"self.type = self.getType(entry) self.klasse = self.getClass(entry) if self.type: self.default_type = self.type else: try:",
"in range(len(self.zone)): if \"/*\" in self.zone[i]: self.counter = True self.zone[i] = self.zone[i].split(\"/*\")[0] continue",
"1 with index.\"\"\" self.zone[index] += \" \" + self.zone[index + 1] self.zone.pop(index +",
"Zone (Normaly one)\"\"\" return set([i[2] for i in self.table]) def getDomains(self): \"\"\"returns set",
"else self.zone[i] for i in range(len(self.zone))] def mergeParanthese(self): \"\"\"Merge every paranthes to one",
"compense the mapping collaps try: self.zone[i] except IndexError: break if \"(\" in self.zone[i]:",
"self.klasse: self.error(\"There occured a fatal logical error at {0}.\\nPlease contact support for more",
"Type): \"\"\"Returns entrys matching the given type\"\"\" return [i for i in self.table",
"self.table if i[1] == Name] def getID(self, ID): \"\"\"Returns entrys matching the given",
"# -1 because of 23h for eg. def cleanUp(self): \"\"\"removes empty strings and",
"automatic committed to db, else connection object is returned\"\"\" import sqlite3 as sql",
"NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i) for i in RRsTYPES]), max([len(i) for i in CLASSES])))",
"zone file to sqlite database Stand Alone Usage: ./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv)",
"= str(int(self.getSerial()[8:]) + 1) if check: assert int(self.serial) < 100, \"\"\"More then 99",
"if given list from zone is TTL record\"\"\" return True if liste[0] ==",
"def getValue(self, Value): \"\"\"Returns entrys matching the given value\"\"\" return [i for i",
"# warnig: complete line is removed. Problem with: /*comment\\nbla\\nbla*/command? self.counter = False continue",
"getRetryTime(self): \"\"\"Returns retry time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self):",
"getName(self, Name): \"\"\"Returns entrys matching the given name\"\"\" return [i for i in",
"or \")\" in i]: self.count += 1 self.rmParanthese() self.mergeParanthese() if self.count > 100:",
"Please avoid using Paranthese in Paranthese or more then more paranthese per line\")",
"== \"__main__\": from sys import argv from os import path as path if",
"class _Parser(): \"\"\"Main Parser\"\"\" def __init__(self, file): self.file = file self.zone = list()",
"\")\" in i]: self.count += 1 self.rmParanthese() self.mergeParanthese() if self.count > 100: self.error(\"Paranthese",
"for y in (self.primKey, self.name, entry[0], self.klasse, self.type, self.value)]))) # carefull!!! 123456d as",
"= self.parser.Table self.TTL = self.parser.default_TTL self.zonename = path.basename(self.file) del self.parser # RAM clean",
"self.rmCompleteParanthese() self.split() self.cleanUp() self.parse() def error(self, error): \"\"\"returns error\"\"\" raise ZoneFileError(error, self.file) def",
"of all available ID's // prim. keys of internal table\"\"\" return set([i[0] for",
"table if exists '{0}'\".format(self.tableName)) # insecure !!! Problems: \"db.mydomain.local\".count(\".\") != 0 -> mySQL",
"self.file = file self.parser = _Parser(file) self.table = self.parser.Table self.TTL = self.parser.default_TTL self.zonename",
"patter\"\"\" self.counter = 0 self.result = list() for i in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter))",
"True if obeject is a class like IN, eg.\"\"\" return True if object",
"the given class\"\"\" return [i for i in self.table if i[3] == Class]",
"for i in self.zone if i != \"#\"] if \"//\" in self.zone_org: self.zone",
"of matching rows\"\"\" self.result = list() for i in self.table: if ID and",
"AttributeError: self.error(\"Please check your zonfile. TTL not found\") self.handle(self.primKey, self.name,self.ttl, self.klasse, self.type, self.value)",
"\"DHCID\", \"DNAME\", \"DNSKEY\", \"DS\", \"GPOS\", \"HINFO\", \"IPSECKEY\", \"ISDN\", \"KEY\", \"KX\", \"LOC\", \"MX\", \"NAPTR\",",
"RRsTYPES]), max([len(i) for i in CLASSES]))) # also insecure self.cursor.executemany('INSERT INTO \"{0}\" VALUES",
"\"@\", Class = \"IN\", Type=\"AAAA\")[0][5] def mkSerial(self, check = True): \"\"\"Sets timestamp allone.",
"for i in self.zone if i != \"//\"] if \"/*\" in self.zone_org: self.pop",
"\"\"\"More then 99 changes aren't supported per day.\"\"\" if len(self.serial) < 2: self.serial",
"len(argv) == 3: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(argv[2])",
"[i for i in self.table if i[3] == Class] def getTTL(self, TTL): \"\"\"Returns",
"of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self): \"\"\"Return current IPv4 addr of origin\"\"\"",
"self.error) class _Parser(): \"\"\"Main Parser\"\"\" def __init__(self, file): self.file = file self.zone =",
"zonfile. Error at {0}.\\nType not found\".format(\" \".join(entry))) if self.klasse: self.default_klasse = self.klasse else:",
"if closed from zone file line\"\"\" self.zone = [self.zone[i].replace(\"(\", \"\").replace(\")\", \"\") if self.zone[i].count(\"(\")",
"0 and i[0] != 0: continue if Domain and Domain != i[1]: continue",
"self.cursor = self.connection.cursor() self.cursor.execute(\"drop table if exists '{0}'\".format(self.tableName)) # insecure !!! Problems: \"db.mydomain.local\".count(\".\")",
"a entry type like NS, eg.\"\"\" return True if object in RRsTYPES else",
"time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self): \"\"\"Returns negative cache",
"= path.basename(self.file) del self.parser # RAM clean def getValues(self): \"\"\"returns set of all",
"self.zone = [i for i in self.zone if i and i[0] != '']",
"i in self.table if i[3] == Class] def getTTL(self, TTL): \"\"\"Returns entrys matching",
"in i or \")\" in i]: self.count += 1 self.rmParanthese() self.mergeParanthese() if self.count",
"elif len(argv) == 2: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1])",
"Version: {0} Converts zone file to sqlite database Stand Alone Usage: ./parser.py zonefile",
"given list from zone is TTL record\"\"\" return True if liste[0] == '$TTL'",
"./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv) == 2: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1])",
"\"SIG\", \"SOA\", \"SPF\", \"SRV\", \"SSHFP\", \"TXT\", \"WKS\", \"X25\"] from time import strftime class",
"= 0 self.result = list() for i in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter)) self.counter =",
"i in self.table if i[1] == Name] def getID(self, ID): \"\"\"Returns entrys matching",
"\"IPSECKEY\", \"ISDN\", \"KEY\", \"KX\", \"LOC\", \"MX\", \"NAPTR\", \"NSAP\", \"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\",",
"matching the given value\"\"\" return [i for i in self.table if i[5] ==",
"len(argv) == 2: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\")",
"\"\"\"Return current IPv4 addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\",",
"self.counter)) self.counter = self.result[-1] + 1 return self.result def rmComment(self): \"\"\"Removes comments from",
"self.result = list() for i in self.table: if ID and ID != i[0]:",
"liste: if self.isClass(i): return i def parse(self): \"\"\"Main Parser\"\"\" self.primKey = 0 for",
"\"/*\" in self.zone[i]: self.counter = True self.zone[i] = self.zone[i].split(\"/*\")[0] continue if \"*/\" in",
"for i in self.zone if \"(\" in i or \")\" in i]: self.count",
"self.subt += 1 def rmCompleteParanthese(self): \"\"\"removes every paranthes from zone by merging\"\"\" self.count",
"# left: probatly name, probatly ttl, probatly class self.over = len(entry) if self.over",
"self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self): \"\"\"Returns refersh time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[3]",
"self.zone = self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese() self.split() self.cleanUp() self.parse() def error(self, error): \"\"\"returns error\"\"\"",
"ID and ID != i[0]: continue if not isinstance(ID, bool) and ID ==",
"self.rmParanthese() self.mergeParanthese() if self.count > 100: self.error(\"Paranthese Syntax: Please avoid using Paranthese in",
"format: [primKey, name, ttl, class, type, value] self.stream = open(file) self.zone_org = self.stream.read()",
"\"\"\"Merge every paranthes to one line\"\"\" self.paranthese = 0 self.subt = 0 for",
"one line\"\"\" self.paranthese = 0 self.subt = 0 for i in range(len(self.zone)): i",
"to be ttl self.over = len(entry) if self.over == 1: # possible: name,",
"print(\"wrote database to zone.sqlite\") elif len(argv) == 3: assert path.isfile(argv[1]), \"Zonefile {0} not",
"time import strftime class ZoneFileError(Exception): \"\"\"Simple Exception handler\"\"\" def __init__(self, error, file): self.error",
"self.klasse: entry.pop() else: self.ttl = entry.pop() # Has to be ttl self.over =",
"self.__init__(self.file) def convert2sqlite(self, file, table = None, commit = True): \"\"\"Writes results to",
"\"\"\"returns set of all available Values in the Zone\"\"\" return set([i[5] for i",
"undifined error self.ttl = entry.pop() else: self.name = entry[0] try: self.ttl = self.default_TTL",
"i in self.table]) def getDomains(self): \"\"\"returns set of all available Domains in the",
"given value\"\"\" return [i for i in self.table if i[5] == Value] def",
"zonfile. TTL not found\") self.handle(self.primKey, self.name,self.ttl, self.klasse, self.type, self.value) del self.value self.primKey +=",
"= entry.pop() else: self.name = entry[0] try: self.ttl = self.default_TTL except AttributeError: self.error(\"Please",
"probatly name, probatly ttl, probatly class self.over = len(entry) if self.over == 3:",
"+= 1 self.use_index = i continue if \")\" in self.zone[i]: self.paranthese -= 1",
"= self.parser.default_TTL self.zonename = path.basename(self.file) del self.parser # RAM clean def getValues(self): \"\"\"returns",
"def getClass(self, liste): \"\"\"returns class of given entry\"\"\" for i in liste: if",
"except NameError: self.error(\"Please check your zonfile. Error at {0}.\\nType not found\".format(\" \".join(entry))) if",
"i in self.pop: self.zone.pop(i) def move(self, index): \"\"\"Merge index + 1 with index.\"\"\"",
"self.zone if i and i[0] != ''] def getType(self, liste): \"\"\"returns type of",
"self.connection = sql.connect(file) self.cursor = self.connection.cursor() self.cursor.execute(\"drop table if exists '{0}'\".format(self.tableName)) # insecure",
"for i in self.table if i[3] == Class] def getTTL(self, TTL): \"\"\"Returns entrys",
"self.klasse = self.getClass(entry) if self.type: self.default_type = self.type else: try: self.type = self.default_type",
"2: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database",
"= [True] chnages are automatic committed to db, else connection object is returned\"\"\"",
"parser return. Here you get all data -> api\"\"\" # later mySQL? self.Table.append([primKey,",
"your zonfile. Error at {0}.\\nType not found\".format(\" \".join(entry))) if self.klasse: self.default_klasse = self.klasse",
"self.error = str(error) self.file = str(file) def __str__(self): return \"\"\"Please check the given",
"supported\"\"\" self.old_time = self.getSerial()[:8] self.new_time = strftime(\"%Y%m%d\") if self.old_time != self.new_time: self.serial =",
"else: return self.connection if __name__ == \"__main__\": from sys import argv from os",
"123456d as dom -> undifined error self.ttl = entry.pop() else: self.name = entry[0]",
"i and i[0] != ''] def getType(self, liste): \"\"\"returns type of given entry\"\"\"",
"zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv) == 2: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser",
"NameError: self.error(\"Please check your zonfile. Error at {0}.\\nClass not found\".format(\" \".join(entry))) self.typeindex =",
"self.parser = _Parser(file) self.table = self.parser.Table self.TTL = self.parser.default_TTL self.zonename = path.basename(self.file) del",
"Value]) def isType(self, object): \"\"\"returns true if object is a entry type like",
"False # -1 because of 23h for eg. def cleanUp(self): \"\"\"removes empty strings",
"SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self): \"\"\"Return current IPv4 addr of origin\"\"\" return",
"probatly class self.over = len(entry) if self.over == 3: if entry.pop(2) != self.klasse:",
"self.handle(self.primKey, self.name,self.ttl, self.klasse, self.type, self.value) del self.value self.primKey += 1 class Parser(): \"\"\"Paser",
"= list() # format: [primKey, name, ttl, class, type, value] self.stream = open(file)",
"Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database to zone.sqlite\") elif len(argv) == 3: assert path.isfile(argv[1]), \"Zonefile",
"for i in self.table if i[0] == ID] def getMaster(self): \"\"\"Returns Master-field of",
"1) def rmParanthese(self): \"\"\"removes paranthes if closed from zone file line\"\"\" self.zone =",
"def move(self, index): \"\"\"Merge index + 1 with index.\"\"\" self.zone[index] += \" \"",
"record\"\"\" return self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self): \"\"\"Returns expire time - field of SOA record\"\"\"",
"i in range(len(self.zone)): i -= self.subt # to compense the mapping collaps try:",
"Domain = False, TTL = False, Class = False, Type = False, Value",
"def getSerial(self): \"\"\"Returns serial-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self): \"\"\"Returns refersh",
"ZoneFileError(Exception): \"\"\"Simple Exception handler\"\"\" def __init__(self, error, file): self.error = str(error) self.file =",
"Problem with: /*comment\\nbla\\nbla*/command? self.counter = False continue if self.counter: self.pop.append(i) self.pop.sort(reverse = True)",
"path.basename(self.file) del self.parser # RAM clean def getValues(self): \"\"\"returns set of all available",
"class of given entry\"\"\" for i in liste: if self.isClass(i): return i def",
"eg.\"\"\" return True if object in RRsTYPES else False def isClass(self, object): \"\"\"returns",
"!= \";\"] if \"#\" in self.zone_org: self.zone = [i.split(\"#\")[0] for i in self.zone",
"return self.result def getValue(self, Value): \"\"\"Returns entrys matching the given value\"\"\" return [i",
"zone.sqlite\") elif len(argv) == 3: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser =",
"True): \"\"\"Writes results to sql database. If table not given, zonename is used",
"\"\"\"returns true if object is a entry type like NS, eg.\"\"\" return True",
"if \"//\" in self.zone_org: self.zone = [i.split(\"//\")[0] for i in self.zone if i",
"addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"AAAA\")[0][5] def mkSerial(self,",
"to zone.sqlite\") elif len(argv) == 3: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser",
"for i in self.table: if ID and ID != i[0]: continue if not",
"\"\"\"Writes results to sql database. If table not given, zonename is used if",
"\"PTR\", \"PX\", \"RP\", \"PRSIG\", \"RT\", \"SIG\", \"SOA\", \"SPF\", \"SRV\", \"SSHFP\", \"TXT\", \"WKS\", \"X25\"]",
"= False): \"\"\"MetaGer - returns list of matching rows\"\"\" self.result = list() for",
"def getClass(self, Class): \"\"\"Returns entrys matching the given class\"\"\" return [i for i",
"True if liste[0] == '$TTL' and len(liste) < 3 else False def isTTLobj(self,",
"self.serial) def refresh(self): \"\"\"Reloads complete zone\"\"\" self.__init__(self.file) def convert2sqlite(self, file, table = None,",
"entry[1] == self.klasse: entry.pop() else: self.ttl = entry.pop() # Has to be ttl",
"path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(argv[2]) print(\"wrote database to {0}\".format(argv[2]))",
"i in range(len(self.zone))] def mergeParanthese(self): \"\"\"Merge every paranthes to one line\"\"\" self.paranthese =",
"if i and i[0] != ''] def getType(self, liste): \"\"\"returns type of given",
"False, Value = False): \"\"\"MetaGer - returns list of matching rows\"\"\" self.result =",
"self.subt += 1 continue if self.paranthese: self.move(self.use_index) self.subt += 1 def rmCompleteParanthese(self): \"\"\"removes",
"if \")\" in self.zone[i]: self.paranthese -= 1 self.move(self.use_index) self.subt += 1 continue if",
"CLASSES = [\"IN\", \"HS\", \"CH\", \"CS\"] RRsTYPES = [\"A\",\"AAAA\", \"A6\", \"AFSDB\", \"APL\", \"CERT\",",
"\"\"\"Please check the given zone file {0}.\\nFollowing Error occured: {1}\"\"\".format(self.file, self.error) class _Parser():",
"field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self): \"\"\"Return current IPv4 addr of",
"self.over == 2: # Possible: class, ttl, name but: entry[1] = {TTL//class} ->",
"= \"01\" else: self.serial = str(int(self.getSerial()[8:]) + 1) if check: assert int(self.serial) <",
"if i[0] == ID] def getMaster(self): \"\"\"Returns Master-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[0]",
"as sql if table: self.tableName = table else: self.tableName = self.zonename self.connection =",
"if Domain and Domain != i[1]: continue if TTL and TTL != i[2]:",
"\"\"\"Returns entrys matching the given type\"\"\" return [i for i in self.table if",
"\"\"\"Returns entrys matching the given ID\"\"\" return [i for i in self.table if",
"class like IN, eg.\"\"\" return True if object in CLASSES else False def",
"every paranthes from zone by merging\"\"\" self.count = 0 while [i for i",
"def getNegativeCache(self): \"\"\"Returns negative cache time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[6]",
"= \"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time, self.serial) def refresh(self): \"\"\"Reloads complete zone\"\"\" self.__init__(self.file) def convert2sqlite(self,",
"getClass(self, Class): \"\"\"Returns entrys matching the given class\"\"\" return [i for i in",
"else False # -1 because of 23h for eg. def cleanUp(self): \"\"\"removes empty",
"handle it as TTL!\".format(\" | \".join([str(y) for y in (self.primKey, self.name, entry[0], self.klasse,",
"self.cursor.execute(\"\"\"CREATE TABLE '{0}' (id INT, domain VARCHAR({1}) NOT NULL, ttl INT, class VARCHAR({2})",
"== 3: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(argv[2]) print(\"wrote",
"def getType(self, Type): \"\"\"Returns entrys matching the given type\"\"\" return [i for i",
"\"\"\"returns class of given entry\"\"\" for i in liste: if self.isClass(i): return i",
"all available Domains in the Zone\"\"\" return set([i[1] for i in self.table]) def",
"- field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self): \"\"\"Returns retry time -",
"all available Types in the Zone\"\"\" return set([i[4] for i in self.table]) def",
"\"{0}{1}\".format(self.new_time, self.serial) def refresh(self): \"\"\"Reloads complete zone\"\"\" self.__init__(self.file) def convert2sqlite(self, file, table =",
"\"\"\"MetaGer - returns list of matching rows\"\"\" self.result = list() for i in",
"-> api\"\"\" # later mySQL? self.Table.append([primKey, Name, TTL, Class, Type, Value]) def isType(self,",
"in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter)) self.counter = self.result[-1] + 1 return self.result def rmComment(self):",
"carefull - problems by differncing ttl/domaine, if domain[:-1].isdigit()\"\"\" VERSION = 1.1 DOMAIN_MAX_LENGHT =",
"if \"/*\" in self.zone_org: self.pop = list() self.counter = False for i in",
"true if object is a entry type like NS, eg.\"\"\" return True if",
"if liste[0] == '$TTL' and len(liste) < 3 else False def isTTLobj(self, object):",
"obeject is a class like IN, eg.\"\"\" return True if object in CLASSES",
"''] def getType(self, liste): \"\"\"returns type of given entry\"\"\" for i in liste:",
"fitting patter\"\"\" self.counter = 0 self.result = list() for i in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern,",
"\"ISDN\", \"KEY\", \"KX\", \"LOC\", \"MX\", \"NAPTR\", \"NSAP\", \"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\", \"PX\",",
"Type = False, Value = False): \"\"\"MetaGer - returns list of matching rows\"\"\"",
"return i def parse(self): \"\"\"Main Parser\"\"\" self.primKey = 0 for entry in self.zone:",
"field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self): \"\"\"Returns expire time - field",
"class self.over = len(entry) if self.over == 3: if entry.pop(2) != self.klasse: self.error(\"There",
"use it carefull - problems by differncing ttl/domaine, if domain[:-1].isdigit()\"\"\" VERSION = 1.1",
"parse(self): \"\"\"Main Parser\"\"\" self.primKey = 0 for entry in self.zone: if self.isTTL(entry): self.default_TTL",
"\"\"\"Merge index + 1 with index.\"\"\" self.zone[index] += \" \" + self.zone[index +",
"every index of fitting patter\"\"\" self.counter = 0 self.result = list() for i",
"= \"IN\", Type=\"AAAA\")[0][5] def mkSerial(self, check = True): \"\"\"Sets timestamp allone. If check,",
"Bind Zonefile Parser ==================== Version: {0} Converts zone file to sqlite database Stand",
"if \"*/\" in self.zone[i]: self.pop.append(i) # warnig: complete line is removed. Problem with:",
"Zone\"\"\" return set([i[4] for i in self.table]) def getClasses(self): \"\"\"returns set of all",
"RRsTYPES else False def isClass(self, object): \"\"\"returns True if obeject is a class",
"logical error at {0}.\\nPlease contact support for more information\".format(\" \".join(entry))) self.over = len(entry)",
"= \"@\", Class = \"IN\", Type=\"A\")[0][5] def getIPv6(self): \"\"\"Return current IPv6 addr of",
"return [i for i in self.table if i[2] == str(TTL)] def getName(self, Name):",
"return self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self): \"\"\"Returns expire time - field of SOA record\"\"\" return",
"name, probatly ttl, probatly class self.over = len(entry) if self.over == 3: if",
"given entry\"\"\" for i in liste: if self.isType(i): return i def getClass(self, liste):",
"Alone Usage: ./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv) == 2: assert path.isfile(argv[1]), \"Zonefile {0}",
"os import path as path if len(argv) == 1: print(\"\"\" Bind Zonefile Parser",
"for parser return. Here you get all data -> api\"\"\" # later mySQL?",
"like NS, eg.\"\"\" return True if object in RRsTYPES else False def isClass(self,",
"self.Table = list() # format: [primKey, name, ttl, class, type, value] self.stream =",
"and Value != i[5]: continue self.result.append(i) return self.result def getValue(self, Value): \"\"\"Returns entrys",
"self.value self.primKey += 1 class Parser(): \"\"\"Paser - Friendly User API\"\"\" def __init__(self,",
"self.pop.sort(reverse = True) # To avoid collaps of mapping for i in self.pop:",
"Syntax error self.cursor.execute(\"\"\"CREATE TABLE '{0}' (id INT, domain VARCHAR({1}) NOT NULL, ttl INT,",
"self.counter: self.pop.append(i) self.pop.sort(reverse = True) # To avoid collaps of mapping for i",
"not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database to zone.sqlite\") elif len(argv) ==",
"time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self): \"\"\"Returns expire time",
"\";\" in self.zone_org: self.zone = [i.split(\";\")[0] for i in self.zone if i !=",
"i[2] == str(TTL)] def getName(self, Name): \"\"\"Returns entrys matching the given name\"\"\" return",
"as path if len(argv) == 1: print(\"\"\" Bind Zonefile Parser ==================== Version: {0}",
"3 else False def isTTLobj(self, object): \"\"\"Returns if given object is ttl. Warning:",
"negative cache time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self): \"\"\"Return",
"refresh(self): \"\"\"Reloads complete zone\"\"\" self.__init__(self.file) def convert2sqlite(self, file, table = None, commit =",
"== Type] def getClass(self, Class): \"\"\"Returns entrys matching the given class\"\"\" return [i",
"# also insecure self.cursor.executemany('INSERT INTO \"{0}\" VALUES (?,?,?,?,?,?)' .format(self.tableName), self.table) if commit: self.connection.commit()",
"= 255 CLASSES = [\"IN\", \"HS\", \"CH\", \"CS\"] RRsTYPES = [\"A\",\"AAAA\", \"A6\", \"AFSDB\",",
"if object in CLASSES else False def isTTL(self, liste): \"\"\"returns True if given",
"found\".format(\" \".join(entry))) if self.klasse: self.default_klasse = self.klasse else: try: self.klasse = self.default_klasse except",
"\"HINFO\", \"IPSECKEY\", \"ISDN\", \"KEY\", \"KX\", \"LOC\", \"MX\", \"NAPTR\", \"NSAP\", \"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\",",
"commit = True): \"\"\"Writes results to sql database. If table not given, zonename",
"problems by differncing ttl/domaine, if domain[:-1].isdigit()\"\"\" VERSION = 1.1 DOMAIN_MAX_LENGHT = 255 CLASSES",
"entrys matching the given value\"\"\" return [i for i in self.table if i[5]",
"Value] def getType(self, Type): \"\"\"Returns entrys matching the given type\"\"\" return [i for",
"if __name__ == \"__main__\": from sys import argv from os import path as",
"Domain != i[1]: continue if TTL and TTL != i[2]: continue if Class",
"in self.table]) def getTTLs(self): \"\"\"returns set of all available TTLs in the Zone",
"self.counter = self.result[-1] + 1 return self.result def rmComment(self): \"\"\"Removes comments from zone",
"\"\"\"Removes comments from zone (;, #, /**/, //)\"\"\" if \";\" in self.zone_org: self.zone",
"1 def rmCompleteParanthese(self): \"\"\"removes every paranthes from zone by merging\"\"\" self.count = 0",
"\".join(entry))) if self.klasse: self.default_klasse = self.klasse else: try: self.klasse = self.default_klasse except NameError:",
"(Normaly one)\"\"\" return set([i[2] for i in self.table]) def getDomains(self): \"\"\"returns set of",
"self.default_klasse = self.klasse else: try: self.klasse = self.default_klasse except NameError: self.error(\"Please check your",
"but you should use it carefull - problems by differncing ttl/domaine, if domain[:-1].isdigit()\"\"\"",
"if i[5] == Value] def getType(self, Type): \"\"\"Returns entrys matching the given type\"\"\"",
"_Parser(file) self.table = self.parser.Table self.TTL = self.parser.default_TTL self.zonename = path.basename(self.file) del self.parser #",
"chnages are automatic committed to db, else connection object is returned\"\"\" import sqlite3",
"for i in self.table]) def getDomains(self): \"\"\"returns set of all available Domains in",
"in (self.primKey, self.name, entry[0], self.klasse, self.type, self.value)]))) # carefull!!! 123456d as dom ->",
"if \"/*\" in self.zone[i]: self.counter = True self.zone[i] = self.zone[i].split(\"/*\")[0] continue if \"*/\"",
"= len(entry) if self.over == 1: # possible: name, class, ttl if entry[0]",
"\"//\"] if \"/*\" in self.zone_org: self.pop = list() self.counter = False for i",
"assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database to",
"database to zone.sqlite\") elif len(argv) == 3: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1])",
"def __init__(self, file): self.file = file self.zone = list() self.Table = list() #",
"argv from os import path as path if len(argv) == 1: print(\"\"\" Bind",
"[primKey, name, ttl, class, type, value] self.stream = open(file) self.zone_org = self.stream.read() self.stream.close()",
"from zone by merging\"\"\" self.count = 0 while [i for i in self.zone",
"[i for i in self.table if i[0] == ID] def getMaster(self): \"\"\"Returns Master-field",
"self.zone[index + 1] self.zone.pop(index + 1) def rmParanthese(self): \"\"\"removes paranthes if closed from",
"entry = entry[:self.typeindex] # left: probatly name, probatly ttl, probatly class self.over =",
"in the Zone\"\"\" return set([i[3] for i in self.table]) def getTTLs(self): \"\"\"returns set",
"to sql database. If table not given, zonename is used if commit =",
"Zone\"\"\" return set([i[5] for i in self.table]) def getTypes(self): \"\"\"returns set of all",
"used if commit = [True] chnages are automatic committed to db, else connection",
"\"\"\"returns set of all available ID's // prim. keys of internal table\"\"\" return",
"available ID's // prim. keys of internal table\"\"\" return set([i[0] for i in",
"assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(argv[2]) print(\"wrote database to",
"{1}\"\"\".format(self.file, self.error) class _Parser(): \"\"\"Main Parser\"\"\" def __init__(self, file): self.file = file self.zone",
"it should work, but you should use it carefull - problems by differncing",
"= False, Domain = False, TTL = False, Class = False, Type =",
"keys of internal table\"\"\" return set([i[0] for i in self.table]) def getDefaultTTL(self): \"\"\"Returns",
"Converts zone file to sqlite database Stand Alone Usage: ./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif",
"rmComment(self): \"\"\"Removes comments from zone (;, #, /**/, //)\"\"\" if \";\" in self.zone_org:",
"0 for i in range(len(self.zone)): i -= self.subt # to compense the mapping",
"liste[0] == '$TTL' and len(liste) < 3 else False def isTTLobj(self, object): \"\"\"Returns",
"database Stand Alone Usage: ./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv) == 2: assert path.isfile(argv[1]),",
"2: self.serial = \"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time, self.serial) def refresh(self): \"\"\"Reloads complete zone\"\"\" self.__init__(self.file)",
"continue if \"*/\" in self.zone[i]: self.pop.append(i) # warnig: complete line is removed. Problem",
"in self.pop: self.zone.pop(i) def move(self, index): \"\"\"Merge index + 1 with index.\"\"\" self.zone[index]",
"self.zonename = path.basename(self.file) del self.parser # RAM clean def getValues(self): \"\"\"returns set of",
"self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self): \"\"\"Returns retry time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[4]",
"self.connection.commit() self.cursor.close() else: return self.connection if __name__ == \"__main__\": from sys import argv",
"1 self.rmParanthese() self.mergeParanthese() if self.count > 100: self.error(\"Paranthese Syntax: Please avoid using Paranthese",
"not isinstance(ID, bool) and ID == 0 and i[0] != 0: continue if",
"else: self.tableName = self.zonename self.connection = sql.connect(file) self.cursor = self.connection.cursor() self.cursor.execute(\"drop table if",
"return True if object[:-1].isdigit() else False # -1 because of 23h for eg.",
"entrys matching the given ID\"\"\" return [i for i in self.table if i[0]",
"INT, domain VARCHAR({1}) NOT NULL, ttl INT, class VARCHAR({2}) NOT NULL, type VARCHAR({3})",
"then more paranthese per line\") self.rmParanthese() del self.count def split(self): \"\"\"splits zone to",
"max([len(i) for i in CLASSES]))) # also insecure self.cursor.executemany('INSERT INTO \"{0}\" VALUES (?,?,?,?,?,?)'",
"entry.pop() elif self.isTTLobj(entry[0]): print(\"warning at {0}. I'll handle it as TTL!\".format(\" | \".join([str(y)",
"from os import path as path if len(argv) == 1: print(\"\"\" Bind Zonefile",
"== str(TTL)] def getName(self, Name): \"\"\"Returns entrys matching the given name\"\"\" return [i",
"| \".join([str(y) for y in (self.primKey, self.name, entry[0], self.klasse, self.type, self.value)]))) # carefull!!!",
"False continue if self.counter: self.pop.append(i) self.pop.sort(reverse = True) # To avoid collaps of",
"merging\"\"\" self.count = 0 while [i for i in self.zone if \"(\" in",
"Value != i[5]: continue self.result.append(i) return self.result def getValue(self, Value): \"\"\"Returns entrys matching",
"= entry[1] # default ttl continue self.type = self.getType(entry) self.klasse = self.getClass(entry) if",
"check your zonfile. Error at {0}.\\nClass not found\".format(\" \".join(entry))) self.typeindex = entry.index(self.type) self.value",
"sql database. If table not given, zonename is used if commit = [True]",
"getMaster(self): \"\"\"Returns Master-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self): \"\"\"Returns contact-field of",
"in self.zone[i]: self.paranthese += 1 self.use_index = i continue if \")\" in self.zone[i]:",
"list() for i in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter)) self.counter = self.result[-1] + 1 return",
"del self.count def split(self): \"\"\"splits zone to fields\"\"\" self.zone = [i.split() for i",
"origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"A\")[0][5] def getIPv6(self): \"\"\"Return current",
"str(error) self.file = str(file) def __str__(self): return \"\"\"Please check the given zone file",
"= False continue if self.counter: self.pop.append(i) self.pop.sort(reverse = True) # To avoid collaps",
"of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self): \"\"\"Returns expire time - field of",
"len(entry) if self.over == 3: if entry.pop(2) != self.klasse: self.error(\"There occured a fatal",
"+ 1) def rmParanthese(self): \"\"\"removes paranthes if closed from zone file line\"\"\" self.zone",
"i def parse(self): \"\"\"Main Parser\"\"\" self.primKey = 0 for entry in self.zone: if",
"of all available TTLs in the Zone (Normaly one)\"\"\" return set([i[2] for i",
"= list() for i in self.table: if ID and ID != i[0]: continue",
"\"APL\", \"CERT\", \"CNAME\", \"DHCID\", \"DNAME\", \"DNSKEY\", \"DS\", \"GPOS\", \"HINFO\", \"IPSECKEY\", \"ISDN\", \"KEY\", \"KX\",",
"return self.connection if __name__ == \"__main__\": from sys import argv from os import",
"given entry\"\"\" for i in liste: if self.isClass(i): return i def parse(self): \"\"\"Main",
"for i in self.zone if i != \";\"] if \"#\" in self.zone_org: self.zone",
"\"(\" in i or \")\" in i]: self.count += 1 self.rmParanthese() self.mergeParanthese() if",
"mapping for i in self.pop: self.zone.pop(i) def move(self, index): \"\"\"Merge index + 1",
"for i in CLASSES]))) # also insecure self.cursor.executemany('INSERT INTO \"{0}\" VALUES (?,?,?,?,?,?)' .format(self.tableName),",
"\"NAPTR\", \"NSAP\", \"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\", \"PX\", \"RP\", \"PRSIG\", \"RT\", \"SIG\", \"SOA\",",
"\".join(entry[self.typeindex+1:]) entry = entry[:self.typeindex] # left: probatly name, probatly ttl, probatly class self.over",
"Zone\"\"\" return set([i[1] for i in self.table]) def getIDs(self): \"\"\"returns set of all",
"if self.over == 1: # possible: name, class, ttl if entry[0] == self.klasse:",
"= list() self.Table = list() # format: [primKey, name, ttl, class, type, value]",
"commit: self.connection.commit() self.cursor.close() else: return self.connection if __name__ == \"__main__\": from sys import",
"supported per day.\"\"\" if len(self.serial) < 2: self.serial = \"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time, self.serial)",
"[\"A\",\"AAAA\", \"A6\", \"AFSDB\", \"APL\", \"CERT\", \"CNAME\", \"DHCID\", \"DNAME\", \"DNSKEY\", \"DS\", \"GPOS\", \"HINFO\", \"IPSECKEY\",",
"!= \"//\"] if \"/*\" in self.zone_org: self.pop = list() self.counter = False for",
"check your zonfile. Error at {0}.\\nType not found\".format(\" \".join(entry))) if self.klasse: self.default_klasse =",
"self.getType(entry) self.klasse = self.getClass(entry) if self.type: self.default_type = self.type else: try: self.type =",
"99 are supported\"\"\" self.old_time = self.getSerial()[:8] self.new_time = strftime(\"%Y%m%d\") if self.old_time != self.new_time:",
"fatal logical error at {0}.\\nPlease contact support for more information\".format(\" \".join(entry))) self.over =",
"used TTL\"\"\" return self.TTL def getRecords(self, ID = False, Domain = False, TTL",
"i in self.table]) def getIDs(self): \"\"\"returns set of all available ID's // prim.",
"!= i[1]: continue if TTL and TTL != i[2]: continue if Class and",
"set([i[5] for i in self.table]) def getTypes(self): \"\"\"returns set of all available Types",
"self.stream.read() self.stream.close() self.zone = self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese() self.split() self.cleanUp() self.parse() def error(self, error):",
"in liste: if self.isClass(i): return i def parse(self): \"\"\"Main Parser\"\"\" self.primKey = 0",
"from zone file line\"\"\" self.zone = [self.zone[i].replace(\"(\", \"\").replace(\")\", \"\") if self.zone[i].count(\"(\") == self.zone[i].count(\")\")",
"= self.getClass(entry) if self.type: self.default_type = self.type else: try: self.type = self.default_type except",
"return self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self): \"\"\"Returns retry time - field of SOA record\"\"\" return",
"at {0}.\\nType not found\".format(\" \".join(entry))) if self.klasse: self.default_klasse = self.klasse else: try: self.klasse",
"with index.\"\"\" self.zone[index] += \" \" + self.zone[index + 1] self.zone.pop(index + 1)",
"path as path if len(argv) == 1: print(\"\"\" Bind Zonefile Parser ==================== Version:",
"= True self.zone[i] = self.zone[i].split(\"/*\")[0] continue if \"*/\" in self.zone[i]: self.pop.append(i) # warnig:",
"= self.zone[i].split(\"/*\")[0] continue if \"*/\" in self.zone[i]: self.pop.append(i) # warnig: complete line is",
"check: assert int(self.serial) < 100, \"\"\"More then 99 changes aren't supported per day.\"\"\"",
"found\".format(\" \".join(entry))) self.typeindex = entry.index(self.type) self.value = \" \".join(entry[self.typeindex+1:]) entry = entry[:self.typeindex] #",
"and TTL != i[2]: continue if Class and Class != i[3]: continue if",
"[\"IN\", \"HS\", \"CH\", \"CS\"] RRsTYPES = [\"A\",\"AAAA\", \"A6\", \"AFSDB\", \"APL\", \"CERT\", \"CNAME\", \"DHCID\",",
"< 2: self.serial = \"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time, self.serial) def refresh(self): \"\"\"Reloads complete zone\"\"\"",
"of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self): \"\"\"Returns retry time - field of",
"carefull!!! 123456d as dom -> undifined error self.ttl = entry.pop() else: self.name =",
"{0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database to zone.sqlite\") elif len(argv)",
"rmCompleteParanthese(self): \"\"\"removes every paranthes from zone by merging\"\"\" self.count = 0 while [i",
"\"\"\"Returns if given object is ttl. Warning: it's just probatly correct\"\"\" return True",
"= table else: self.tableName = self.zonename self.connection = sql.connect(file) self.cursor = self.connection.cursor() self.cursor.execute(\"drop",
"probatly ttl, probatly class self.over = len(entry) if self.over == 3: if entry.pop(2)",
"at {0}.\\nPlease contact support for more information\".format(\" \".join(entry))) self.over = len(entry) if self.over",
"return self.result def rmComment(self): \"\"\"Removes comments from zone (;, #, /**/, //)\"\"\" if",
"name\"\"\" return [i for i in self.table if i[1] == Name] def getID(self,",
"self.klasse else: try: self.klasse = self.default_klasse except NameError: self.error(\"Please check your zonfile. Error",
"zonfile. Error at {0}.\\nClass not found\".format(\" \".join(entry))) self.typeindex = entry.index(self.type) self.value = \"",
"True) # To avoid collaps of mapping for i in self.pop: self.zone.pop(i) def",
"\"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time, self.serial) def refresh(self): \"\"\"Reloads complete zone\"\"\" self.__init__(self.file) def convert2sqlite(self, file,",
"= 0 self.subt = 0 for i in range(len(self.zone)): i -= self.subt #",
"given type\"\"\" return [i for i in self.table if i[4] == Type] def",
"self.connection.cursor() self.cursor.execute(\"drop table if exists '{0}'\".format(self.tableName)) # insecure !!! Problems: \"db.mydomain.local\".count(\".\") != 0",
"= [i.split(\"#\")[0] for i in self.zone if i != \"#\"] if \"//\" in",
"avoid using Paranthese in Paranthese or more then more paranthese per line\") self.rmParanthese()",
"{0}.\\nFollowing Error occured: {1}\"\"\".format(self.file, self.error) class _Parser(): \"\"\"Main Parser\"\"\" def __init__(self, file): self.file",
"= \"IN\", Type=\"A\")[0][5] def getIPv6(self): \"\"\"Return current IPv6 addr of origin\"\"\" return self.getRecords(Domain",
"of all available classes in the Zone\"\"\" return set([i[3] for i in self.table])",
"type, value] self.stream = open(file) self.zone_org = self.stream.read() self.stream.close() self.zone = self.zone_org.splitlines() self.rmComment()",
"of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[1] def getSerial(self): \"\"\"Returns serial-field of SOA record\"\"\" return",
"\"PRSIG\", \"RT\", \"SIG\", \"SOA\", \"SPF\", \"SRV\", \"SSHFP\", \"TXT\", \"WKS\", \"X25\"] from time import",
"class ZoneFileError(Exception): \"\"\"Simple Exception handler\"\"\" def __init__(self, error, file): self.error = str(error) self.file",
"but: entry[1] = {TTL//class} -> !name if entry[1] == self.klasse: entry.pop() else: self.ttl",
"Type=\"A\")[0][5] def getIPv6(self): \"\"\"Return current IPv6 addr of origin\"\"\" return self.getRecords(Domain = \"@\",",
"> 99 are supported\"\"\" self.old_time = self.getSerial()[:8] self.new_time = strftime(\"%Y%m%d\") if self.old_time !=",
"i in self.table if i[2] == str(TTL)] def getName(self, Name): \"\"\"Returns entrys matching",
"def isClass(self, object): \"\"\"returns True if obeject is a class like IN, eg.\"\"\"",
"self.subt # to compense the mapping collaps try: self.zone[i] except IndexError: break if",
"self.zone_org = self.stream.read() self.stream.close() self.zone = self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese() self.split() self.cleanUp() self.parse() def",
"in self.zone if i != \"#\"] if \"//\" in self.zone_org: self.zone = [i.split(\"//\")[0]",
"then 99 changes aren't supported per day.\"\"\" if len(self.serial) < 2: self.serial =",
"type like NS, eg.\"\"\" return True if object in RRsTYPES else False def",
"sql if table: self.tableName = table else: self.tableName = self.zonename self.connection = sql.connect(file)",
"allone. If check, no serial > 99 are supported\"\"\" self.old_time = self.getSerial()[:8] self.new_time",
"self.cursor.executemany('INSERT INTO \"{0}\" VALUES (?,?,?,?,?,?)' .format(self.tableName), self.table) if commit: self.connection.commit() self.cursor.close() else: return",
"os.path as path self.file = file self.parser = _Parser(file) self.table = self.parser.Table self.TTL",
"+ 1] self.zone.pop(index + 1) def rmParanthese(self): \"\"\"removes paranthes if closed from zone",
"Zone\"\"\" return set([i[3] for i in self.table]) def getTTLs(self): \"\"\"returns set of all",
"self.isClass(i): return i def parse(self): \"\"\"Main Parser\"\"\" self.primKey = 0 for entry in",
"Parser\"\"\" def __init__(self, file): self.file = file self.zone = list() self.Table = list()",
"i in self.zone if i != \"//\"] if \"/*\" in self.zone_org: self.pop =",
"paranthes if closed from zone file line\"\"\" self.zone = [self.zone[i].replace(\"(\", \"\").replace(\")\", \"\") if",
"Class] def getTTL(self, TTL): \"\"\"Returns entrys matching the given TTL\"\"\" return [i for",
"given TTL\"\"\" return [i for i in self.table if i[2] == str(TTL)] def",
"field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self): \"\"\"Returns negative cache time -",
"ttl. Warning: it's just probatly correct\"\"\" return True if object[:-1].isdigit() else False #",
"def getIPv6(self): \"\"\"Return current IPv6 addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class",
"error self.ttl = entry.pop() else: self.name = entry[0] try: self.ttl = self.default_TTL except",
"getRefreshTime(self): \"\"\"Returns refersh time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self):",
"getZoneContact(self): \"\"\"Returns contact-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[1] def getSerial(self): \"\"\"Returns serial-field of",
"{0}.\\nClass not found\".format(\" \".join(entry))) self.typeindex = entry.index(self.type) self.value = \" \".join(entry[self.typeindex+1:]) entry =",
"mergeParanthese(self): \"\"\"Merge every paranthes to one line\"\"\" self.paranthese = 0 self.subt = 0",
"and Class != i[3]: continue if Type and Type != i[4]: continue if",
"IN, eg.\"\"\" return True if object in CLASSES else False def isTTL(self, liste):",
"liste): \"\"\"returns True if given list from zone is TTL record\"\"\" return True",
"def getValues(self): \"\"\"returns set of all available Values in the Zone\"\"\" return set([i[5]",
"the given ID\"\"\" return [i for i in self.table if i[0] == ID]",
"\" \".join(entry[self.typeindex+1:]) entry = entry[:self.typeindex] # left: probatly name, probatly ttl, probatly class",
"SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self): \"\"\"Returns refersh time - field of SOA",
"\"\"\"splits zone to fields\"\"\" self.zone = [i.split() for i in self.zone] def handle(self,",
"TTLs in the Zone (Normaly one)\"\"\" return set([i[2] for i in self.table]) def",
"'{0}' (id INT, domain VARCHAR({1}) NOT NULL, ttl INT, class VARCHAR({2}) NOT NULL,",
"ID): \"\"\"Returns entrys matching the given ID\"\"\" return [i for i in self.table",
"in self.table]) def getTypes(self): \"\"\"returns set of all available Types in the Zone\"\"\"",
".format(self.tableName), self.table) if commit: self.connection.commit() self.cursor.close() else: return self.connection if __name__ == \"__main__\":",
"self.count def split(self): \"\"\"splits zone to fields\"\"\" self.zone = [i.split() for i in",
"assert int(self.serial) < 100, \"\"\"More then 99 changes aren't supported per day.\"\"\" if",
"the mapping collaps try: self.zone[i] except IndexError: break if \"(\" in self.zone[i]: self.paranthese",
"self.isType(i): return i def getClass(self, liste): \"\"\"returns class of given entry\"\"\" for i",
"+= 1 class Parser(): \"\"\"Paser - Friendly User API\"\"\" def __init__(self, file): import",
"return \"{0}{1}\".format(self.new_time, self.serial) def refresh(self): \"\"\"Reloads complete zone\"\"\" self.__init__(self.file) def convert2sqlite(self, file, table",
"object): \"\"\"returns true if object is a entry type like NS, eg.\"\"\" return",
"self.result.append(self.zone_org.find(pattern, self.counter)) self.counter = self.result[-1] + 1 return self.result def rmComment(self): \"\"\"Removes comments",
"in RRsTYPES]), max([len(i) for i in CLASSES]))) # also insecure self.cursor.executemany('INSERT INTO \"{0}\"",
"[database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv) == 2: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser =",
"available Domains in the Zone\"\"\" return set([i[1] for i in self.table]) def getIDs(self):",
"type\"\"\" return [i for i in self.table if i[4] == Type] def getClass(self,",
"[True] chnages are automatic committed to db, else connection object is returned\"\"\" import",
"Master-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self): \"\"\"Returns contact-field of SOA record\"\"\"",
"value] self.stream = open(file) self.zone_org = self.stream.read() self.stream.close() self.zone = self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese()",
"line\"\"\" self.zone = [self.zone[i].replace(\"(\", \"\").replace(\")\", \"\") if self.zone[i].count(\"(\") == self.zone[i].count(\")\") else self.zone[i] for",
"self.default_type = self.type else: try: self.type = self.default_type except NameError: self.error(\"Please check your",
"as dom -> undifined error self.ttl = entry.pop() else: self.name = entry[0] try:",
"- Friendly User API\"\"\" def __init__(self, file): import os.path as path self.file =",
"To avoid collaps of mapping for i in self.pop: self.zone.pop(i) def move(self, index):",
"Parser ==================== Version: {0} Converts zone file to sqlite database Stand Alone Usage:",
"self.klasse: self.default_klasse = self.klasse else: try: self.klasse = self.default_klasse except NameError: self.error(\"Please check",
"\")\" in self.zone[i]: self.paranthese -= 1 self.move(self.use_index) self.subt += 1 continue if self.paranthese:",
"\"\"\"removes paranthes if closed from zone file line\"\"\" self.zone = [self.zone[i].replace(\"(\", \"\").replace(\")\", \"\")",
"self.paranthese -= 1 self.move(self.use_index) self.subt += 1 continue if self.paranthese: self.move(self.use_index) self.subt +=",
"in RRsTYPES else False def isClass(self, object): \"\"\"returns True if obeject is a",
"self.error(\"There occured a fatal logical error at {0}.\\nPlease contact support for more information\".format(\"",
"available Values in the Zone\"\"\" return set([i[5] for i in self.table]) def getTypes(self):",
"line\") self.rmParanthese() del self.count def split(self): \"\"\"splits zone to fields\"\"\" self.zone = [i.split()",
"and Type != i[4]: continue if Value and Value != i[5]: continue self.result.append(i)",
"classes in the Zone\"\"\" return set([i[3] for i in self.table]) def getTTLs(self): \"\"\"returns",
"self.table: if ID and ID != i[0]: continue if not isinstance(ID, bool) and",
"self.file = file self.zone = list() self.Table = list() # format: [primKey, name,",
"get all data -> api\"\"\" # later mySQL? self.Table.append([primKey, Name, TTL, Class, Type,",
"correct\"\"\" return True if object[:-1].isdigit() else False # -1 because of 23h for",
"contact-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[1] def getSerial(self): \"\"\"Returns serial-field of SOA record\"\"\"",
"self.parse() def error(self, error): \"\"\"returns error\"\"\" raise ZoneFileError(error, self.file) def getIndexe(self, pattern): \"\"\"return",
"!= i[0]: continue if not isinstance(ID, bool) and ID == 0 and i[0]",
"self.getSerial()[:8] self.new_time = strftime(\"%Y%m%d\") if self.old_time != self.new_time: self.serial = \"01\" else: self.serial",
"comments from zone (;, #, /**/, //)\"\"\" if \";\" in self.zone_org: self.zone =",
"= self.getType(entry) self.klasse = self.getClass(entry) if self.type: self.default_type = self.type else: try: self.type",
"matching the given name\"\"\" return [i for i in self.table if i[1] ==",
"CLASSES]))) # also insecure self.cursor.executemany('INSERT INTO \"{0}\" VALUES (?,?,?,?,?,?)' .format(self.tableName), self.table) if commit:",
"in self.table]) def getClasses(self): \"\"\"returns set of all available classes in the Zone\"\"\"",
"1: # possible: name, class, ttl if entry[0] == self.klasse: entry.pop() elif self.isTTLobj(entry[0]):",
"self.zone[i]: self.paranthese -= 1 self.move(self.use_index) self.subt += 1 continue if self.paranthese: self.move(self.use_index) self.subt",
"handler\"\"\" def __init__(self, error, file): self.error = str(error) self.file = str(file) def __str__(self):",
"= len(entry) if self.over == 2: # Possible: class, ttl, name but: entry[1]",
"def getIndexe(self, pattern): \"\"\"return every index of fitting patter\"\"\" self.counter = 0 self.result",
"def __init__(self, file): import os.path as path self.file = file self.parser = _Parser(file)",
"False, Domain = False, TTL = False, Class = False, Type = False,",
"and ID != i[0]: continue if not isinstance(ID, bool) and ID == 0",
"0 self.result = list() for i in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter)) self.counter = self.result[-1]",
"can't read brackets in brackets - avoid using more then one bracket per",
"\"*/\" in self.zone[i]: self.pop.append(i) # warnig: complete line is removed. Problem with: /*comment\\nbla\\nbla*/command?",
"getNegativeCache(self): \"\"\"Returns negative cache time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[6] def",
"-= 1 self.move(self.use_index) self.subt += 1 continue if self.paranthese: self.move(self.use_index) self.subt += 1",
"continue if self.counter: self.pop.append(i) self.pop.sort(reverse = True) # To avoid collaps of mapping",
"self.error(\"Please check your zonfile. Error at {0}.\\nClass not found\".format(\" \".join(entry))) self.typeindex = entry.index(self.type)",
"# Has to be ttl self.over = len(entry) if self.over == 1: #",
"def __str__(self): return \"\"\"Please check the given zone file {0}.\\nFollowing Error occured: {1}\"\"\".format(self.file,",
"given, zonename is used if commit = [True] chnages are automatic committed to",
"return [i for i in self.table if i[5] == Value] def getType(self, Type):",
"= 0 for entry in self.zone: if self.isTTL(entry): self.default_TTL = entry[1] # default",
"the given TTL\"\"\" return [i for i in self.table if i[2] == str(TTL)]",
"def getRetryTime(self): \"\"\"Returns retry time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[4] def",
"IPv6 addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"AAAA\")[0][5] def",
"in liste: if self.isType(i): return i def getClass(self, liste): \"\"\"returns class of given",
"\"CNAME\", \"DHCID\", \"DNAME\", \"DNSKEY\", \"DS\", \"GPOS\", \"HINFO\", \"IPSECKEY\", \"ISDN\", \"KEY\", \"KX\", \"LOC\", \"MX\",",
"-> !name if entry[1] == self.klasse: entry.pop() else: self.ttl = entry.pop() # Has",
"using more then one bracket per line. Normally it should work, but you",
"= True): \"\"\"Writes results to sql database. If table not given, zonename is",
"isTTL(self, liste): \"\"\"returns True if given list from zone is TTL record\"\"\" return",
"of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self): \"\"\"Returns contact-field of SOA record\"\"\" return",
"entry\"\"\" for i in liste: if self.isClass(i): return i def parse(self): \"\"\"Main Parser\"\"\"",
"# possible: name, class, ttl if entry[0] == self.klasse: entry.pop() elif self.isTTLobj(entry[0]): print(\"warning",
"i def getClass(self, liste): \"\"\"returns class of given entry\"\"\" for i in liste:",
"if self.counter: self.pop.append(i) self.pop.sort(reverse = True) # To avoid collaps of mapping for",
"self.default_type except NameError: self.error(\"Please check your zonfile. Error at {0}.\\nType not found\".format(\" \".join(entry)))",
"mapping collaps try: self.zone[i] except IndexError: break if \"(\" in self.zone[i]: self.paranthese +=",
"= str(file) def __str__(self): return \"\"\"Please check the given zone file {0}.\\nFollowing Error",
"!= i[3]: continue if Type and Type != i[4]: continue if Value and",
"1 self.move(self.use_index) self.subt += 1 continue if self.paranthese: self.move(self.use_index) self.subt += 1 def",
"self.zone[index] += \" \" + self.zone[index + 1] self.zone.pop(index + 1) def rmParanthese(self):",
"in self.zone_org: self.zone = [i.split(\"#\")[0] for i in self.zone if i != \"#\"]",
"is removed. Problem with: /*comment\\nbla\\nbla*/command? self.counter = False continue if self.counter: self.pop.append(i) self.pop.sort(reverse",
"= False for i in range(len(self.zone)): if \"/*\" in self.zone[i]: self.counter = True",
"strftime class ZoneFileError(Exception): \"\"\"Simple Exception handler\"\"\" def __init__(self, error, file): self.error = str(error)",
"self.zone[i].count(\")\") else self.zone[i] for i in range(len(self.zone))] def mergeParanthese(self): \"\"\"Merge every paranthes to",
"range(len(self.zone))] def mergeParanthese(self): \"\"\"Merge every paranthes to one line\"\"\" self.paranthese = 0 self.subt",
"if object in RRsTYPES else False def isClass(self, object): \"\"\"returns True if obeject",
"i in liste: if self.isType(i): return i def getClass(self, liste): \"\"\"returns class of",
"Class, Type, Value): \"\"\"Handler for parser return. Here you get all data ->",
"\"@\", Class = \"IN\", Type=\"A\")[0][5] def getIPv6(self): \"\"\"Return current IPv6 addr of origin\"\"\"",
"if given object is ttl. Warning: it's just probatly correct\"\"\" return True if",
"self.result[-1] + 1 return self.result def rmComment(self): \"\"\"Removes comments from zone (;, #,",
"and ID == 0 and i[0] != 0: continue if Domain and Domain",
"[i for i in self.table if i[2] == str(TTL)] def getName(self, Name): \"\"\"Returns",
"\"DNAME\", \"DNSKEY\", \"DS\", \"GPOS\", \"HINFO\", \"IPSECKEY\", \"ISDN\", \"KEY\", \"KX\", \"LOC\", \"MX\", \"NAPTR\", \"NSAP\",",
"i[3]: continue if Type and Type != i[4]: continue if Value and Value",
"def refresh(self): \"\"\"Reloads complete zone\"\"\" self.__init__(self.file) def convert2sqlite(self, file, table = None, commit",
"self.table if i[4] == Type] def getClass(self, Class): \"\"\"Returns entrys matching the given",
"check your zonfile. TTL not found\") self.handle(self.primKey, self.name,self.ttl, self.klasse, self.type, self.value) del self.value",
"rows\"\"\" self.result = list() for i in self.table: if ID and ID !=",
"self.counter = False for i in range(len(self.zone)): if \"/*\" in self.zone[i]: self.counter =",
"1 continue if self.paranthese: self.move(self.use_index) self.subt += 1 def rmCompleteParanthese(self): \"\"\"removes every paranthes",
"name, ttl, class, type, value] self.stream = open(file) self.zone_org = self.stream.read() self.stream.close() self.zone",
"def cleanUp(self): \"\"\"removes empty strings and lists from zone\"\"\" self.zone = [i for",
"possible: name, class, ttl if entry[0] == self.klasse: entry.pop() elif self.isTTLobj(entry[0]): print(\"warning at",
"[i.split(\"//\")[0] for i in self.zone if i != \"//\"] if \"/*\" in self.zone_org:",
"entrys matching the given name\"\"\" return [i for i in self.table if i[1]",
"i in RRsTYPES]), max([len(i) for i in CLASSES]))) # also insecure self.cursor.executemany('INSERT INTO",
"!= 0 -> mySQL Syntax error self.cursor.execute(\"\"\"CREATE TABLE '{0}' (id INT, domain VARCHAR({1})",
"SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self): \"\"\"Returns retry time - field of SOA",
"!= i[2]: continue if Class and Class != i[3]: continue if Type and",
"Class): \"\"\"Returns entrys matching the given class\"\"\" return [i for i in self.table",
"!= \"#\"] if \"//\" in self.zone_org: self.zone = [i.split(\"//\")[0] for i in self.zone",
"self.rmParanthese() del self.count def split(self): \"\"\"splits zone to fields\"\"\" self.zone = [i.split() for",
"set([i[1] for i in self.table]) def getIDs(self): \"\"\"returns set of all available ID's",
"for i in self.pop: self.zone.pop(i) def move(self, index): \"\"\"Merge index + 1 with",
"= i continue if \")\" in self.zone[i]: self.paranthese -= 1 self.move(self.use_index) self.subt +=",
"continue if Type and Type != i[4]: continue if Value and Value !=",
"should use it carefull - problems by differncing ttl/domaine, if domain[:-1].isdigit()\"\"\" VERSION =",
"0 for entry in self.zone: if self.isTTL(entry): self.default_TTL = entry[1] # default ttl",
"dom -> undifined error self.ttl = entry.pop() else: self.name = entry[0] try: self.ttl",
"file): import os.path as path self.file = file self.parser = _Parser(file) self.table =",
"getDefaultTTL(self): \"\"\"Returns last used TTL\"\"\" return self.TTL def getRecords(self, ID = False, Domain",
"time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self): \"\"\"Returns retry time",
"__init__(self, error, file): self.error = str(error) self.file = str(file) def __str__(self): return \"\"\"Please",
"- field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self): \"\"\"Returns expire time -",
"len(liste) < 3 else False def isTTLobj(self, object): \"\"\"Returns if given object is",
"in self.zone if i != \"//\"] if \"/*\" in self.zone_org: self.pop = list()",
"str(int(self.getSerial()[8:]) + 1) if check: assert int(self.serial) < 100, \"\"\"More then 99 changes",
"# format: [primKey, name, ttl, class, type, value] self.stream = open(file) self.zone_org =",
"getTypes(self): \"\"\"returns set of all available Types in the Zone\"\"\" return set([i[4] for",
"except NameError: self.error(\"Please check your zonfile. Error at {0}.\\nClass not found\".format(\" \".join(entry))) self.typeindex",
"if self.count > 100: self.error(\"Paranthese Syntax: Please avoid using Paranthese in Paranthese or",
"as path self.file = file self.parser = _Parser(file) self.table = self.parser.Table self.TTL =",
"def rmCompleteParanthese(self): \"\"\"removes every paranthes from zone by merging\"\"\" self.count = 0 while",
"database. If table not given, zonename is used if commit = [True] chnages",
"in self.zone if i != \";\"] if \"#\" in self.zone_org: self.zone = [i.split(\"#\")[0]",
"Class, Type, Value]) def isType(self, object): \"\"\"returns true if object is a entry",
"TABLE '{0}' (id INT, domain VARCHAR({1}) NOT NULL, ttl INT, class VARCHAR({2}) NOT",
"self.result def rmComment(self): \"\"\"Removes comments from zone (;, #, /**/, //)\"\"\" if \";\"",
"entry.index(self.type) self.value = \" \".join(entry[self.typeindex+1:]) entry = entry[:self.typeindex] # left: probatly name, probatly",
"entry[0], self.klasse, self.type, self.value)]))) # carefull!!! 123456d as dom -> undifined error self.ttl",
"def split(self): \"\"\"splits zone to fields\"\"\" self.zone = [i.split() for i in self.zone]",
"self.use_index = i continue if \")\" in self.zone[i]: self.paranthese -= 1 self.move(self.use_index) self.subt",
"== self.klasse: entry.pop() elif self.isTTLobj(entry[0]): print(\"warning at {0}. I'll handle it as TTL!\".format(\"",
"in self.zone_org: self.zone = [i.split(\"//\")[0] for i in self.zone if i != \"//\"]",
"list of matching rows\"\"\" self.result = list() for i in self.table: if ID",
"continue if self.paranthese: self.move(self.use_index) self.subt += 1 def rmCompleteParanthese(self): \"\"\"removes every paranthes from",
"avoid using more then one bracket per line. Normally it should work, but",
"like IN, eg.\"\"\" return True if object in CLASSES else False def isTTL(self,",
"\"__main__\": from sys import argv from os import path as path if len(argv)",
"len(argv) == 1: print(\"\"\" Bind Zonefile Parser ==================== Version: {0} Converts zone file",
"1.1 DOMAIN_MAX_LENGHT = 255 CLASSES = [\"IN\", \"HS\", \"CH\", \"CS\"] RRsTYPES = [\"A\",\"AAAA\",",
"i continue if \")\" in self.zone[i]: self.paranthese -= 1 self.move(self.use_index) self.subt += 1",
"VARCHAR({2}) NOT NULL, type VARCHAR({3}) NOT NULL, value TEXT NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i)",
"should work, but you should use it carefull - problems by differncing ttl/domaine,",
"i in self.zone if i and i[0] != ''] def getType(self, liste): \"\"\"returns",
"zone file line\"\"\" self.zone = [self.zone[i].replace(\"(\", \"\").replace(\")\", \"\") if self.zone[i].count(\"(\") == self.zone[i].count(\")\") else",
"\"\"\"Returns entrys matching the given name\"\"\" return [i for i in self.table if",
"if \"(\" in i or \")\" in i]: self.count += 1 self.rmParanthese() self.mergeParanthese()",
"'$TTL' and len(liste) < 3 else False def isTTLobj(self, object): \"\"\"Returns if given",
"= len(entry) if self.over == 3: if entry.pop(2) != self.klasse: self.error(\"There occured a",
"self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self): \"\"\"Returns contact-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[1] def getSerial(self): \"\"\"Returns",
"(;, #, /**/, //)\"\"\" if \";\" in self.zone_org: self.zone = [i.split(\";\")[0] for i",
"-1 because of 23h for eg. def cleanUp(self): \"\"\"removes empty strings and lists",
"record\"\"\" return self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self): \"\"\"Returns contact-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[1] def",
"return set([i[2] for i in self.table]) def getDomains(self): \"\"\"returns set of all available",
"sqlite3 as sql if table: self.tableName = table else: self.tableName = self.zonename self.connection",
"!= 0: continue if Domain and Domain != i[1]: continue if TTL and",
"23h for eg. def cleanUp(self): \"\"\"removes empty strings and lists from zone\"\"\" self.zone",
"return self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self): \"\"\"Returns contact-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[1] def getSerial(self):",
"_Parser(): \"\"\"Main Parser\"\"\" def __init__(self, file): self.file = file self.zone = list() self.Table",
"not found\".format(\" \".join(entry))) if self.klasse: self.default_klasse = self.klasse else: try: self.klasse = self.default_klasse",
"\"\") if self.zone[i].count(\"(\") == self.zone[i].count(\")\") else self.zone[i] for i in range(len(self.zone))] def mergeParanthese(self):",
"INTO \"{0}\" VALUES (?,?,?,?,?,?)' .format(self.tableName), self.table) if commit: self.connection.commit() self.cursor.close() else: return self.connection",
"\"CH\", \"CS\"] RRsTYPES = [\"A\",\"AAAA\", \"A6\", \"AFSDB\", \"APL\", \"CERT\", \"CNAME\", \"DHCID\", \"DNAME\", \"DNSKEY\",",
"# default ttl continue self.type = self.getType(entry) self.klasse = self.getClass(entry) if self.type: self.default_type",
"\"\"\"Returns expire time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self): \"\"\"Returns",
"== 2: # Possible: class, ttl, name but: entry[1] = {TTL//class} -> !name",
"zone file {0}.\\nFollowing Error occured: {1}\"\"\".format(self.file, self.error) class _Parser(): \"\"\"Main Parser\"\"\" def __init__(self,",
"return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"A\")[0][5] def getIPv6(self): \"\"\"Return current IPv6",
"serial-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self): \"\"\"Returns refersh time - field",
"in self.table]) def getDomains(self): \"\"\"returns set of all available Domains in the Zone\"\"\"",
"self.tableName = self.zonename self.connection = sql.connect(file) self.cursor = self.connection.cursor() self.cursor.execute(\"drop table if exists",
"= file self.zone = list() self.Table = list() # format: [primKey, name, ttl,",
"self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self): \"\"\"Returns expire time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[5]",
"isTTLobj(self, object): \"\"\"Returns if given object is ttl. Warning: it's just probatly correct\"\"\"",
"ID\"\"\" return [i for i in self.table if i[0] == ID] def getMaster(self):",
"(?,?,?,?,?,?)' .format(self.tableName), self.table) if commit: self.connection.commit() self.cursor.close() else: return self.connection if __name__ ==",
"import path as path if len(argv) == 1: print(\"\"\" Bind Zonefile Parser ====================",
"Here you get all data -> api\"\"\" # later mySQL? self.Table.append([primKey, Name, TTL,",
"def handle(self, primKey, Name, TTL, Class, Type, Value): \"\"\"Handler for parser return. Here",
"last used TTL\"\"\" return self.TTL def getRecords(self, ID = False, Domain = False,",
"self.zone_org: self.zone = [i.split(\";\")[0] for i in self.zone if i != \";\"] if",
"self.zone[i]: self.pop.append(i) # warnig: complete line is removed. Problem with: /*comment\\nbla\\nbla*/command? self.counter =",
"1] self.zone.pop(index + 1) def rmParanthese(self): \"\"\"removes paranthes if closed from zone file",
"of all available Types in the Zone\"\"\" return set([i[4] for i in self.table])",
"3: if entry.pop(2) != self.klasse: self.error(\"There occured a fatal logical error at {0}.\\nPlease",
"self.Table.append([primKey, Name, TTL, Class, Type, Value]) def isType(self, object): \"\"\"returns true if object",
"def isTTL(self, liste): \"\"\"returns True if given list from zone is TTL record\"\"\"",
"def getTTLs(self): \"\"\"returns set of all available TTLs in the Zone (Normaly one)\"\"\"",
"self.subt = 0 for i in range(len(self.zone)): i -= self.subt # to compense",
"i]: self.count += 1 self.rmParanthese() self.mergeParanthese() if self.count > 100: self.error(\"Paranthese Syntax: Please",
"of all available Domains in the Zone\"\"\" return set([i[1] for i in self.table])",
"\"\").replace(\")\", \"\") if self.zone[i].count(\"(\") == self.zone[i].count(\")\") else self.zone[i] for i in range(len(self.zone))] def",
"field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self): \"\"\"Returns retry time - field",
"for i in liste: if self.isClass(i): return i def parse(self): \"\"\"Main Parser\"\"\" self.primKey",
"self.zone[i]: self.paranthese += 1 self.use_index = i continue if \")\" in self.zone[i]: self.paranthese",
"if entry.pop(2) != self.klasse: self.error(\"There occured a fatal logical error at {0}.\\nPlease contact",
"all available ID's // prim. keys of internal table\"\"\" return set([i[0] for i",
"Value): \"\"\"Handler for parser return. Here you get all data -> api\"\"\" #",
"else: self.name = entry[0] try: self.ttl = self.default_TTL except AttributeError: self.error(\"Please check your",
"= False, Value = False): \"\"\"MetaGer - returns list of matching rows\"\"\" self.result",
"-> mySQL Syntax error self.cursor.execute(\"\"\"CREATE TABLE '{0}' (id INT, domain VARCHAR({1}) NOT NULL,",
"SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self): \"\"\"Returns negative cache time - field of",
"return True if object in RRsTYPES else False def isClass(self, object): \"\"\"returns True",
"100, \"\"\"More then 99 changes aren't supported per day.\"\"\" if len(self.serial) < 2:",
"if TTL and TTL != i[2]: continue if Class and Class != i[3]:",
"for i in self.table]) def getTypes(self): \"\"\"returns set of all available Types in",
"in the Zone\"\"\" return set([i[1] for i in self.table]) def getIDs(self): \"\"\"returns set",
"self.getType(\"SOA\")[0][5].split()[1] def getSerial(self): \"\"\"Returns serial-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self): \"\"\"Returns",
"the given value\"\"\" return [i for i in self.table if i[5] == Value]",
"self.parser # RAM clean def getValues(self): \"\"\"returns set of all available Values in",
"zone by merging\"\"\" self.count = 0 while [i for i in self.zone if",
"return set([i[1] for i in self.table]) def getIDs(self): \"\"\"returns set of all available",
"timestamp allone. If check, no serial > 99 are supported\"\"\" self.old_time = self.getSerial()[:8]",
"+ 1) if check: assert int(self.serial) < 100, \"\"\"More then 99 changes aren't",
"!!! Problems: \"db.mydomain.local\".count(\".\") != 0 -> mySQL Syntax error self.cursor.execute(\"\"\"CREATE TABLE '{0}' (id",
"if self.isTTL(entry): self.default_TTL = entry[1] # default ttl continue self.type = self.getType(entry) self.klasse",
"not found\") self.handle(self.primKey, self.name,self.ttl, self.klasse, self.type, self.value) del self.value self.primKey += 1 class",
"self.isTTL(entry): self.default_TTL = entry[1] # default ttl continue self.type = self.getType(entry) self.klasse =",
"+ 1 return self.result def rmComment(self): \"\"\"Removes comments from zone (;, #, /**/,",
"entry[1] = {TTL//class} -> !name if entry[1] == self.klasse: entry.pop() else: self.ttl =",
"domain[:-1].isdigit()\"\"\" VERSION = 1.1 DOMAIN_MAX_LENGHT = 255 CLASSES = [\"IN\", \"HS\", \"CH\", \"CS\"]",
"from sys import argv from os import path as path if len(argv) ==",
"= self.result[-1] + 1 return self.result def rmComment(self): \"\"\"Removes comments from zone (;,",
"self.zone.pop(i) def move(self, index): \"\"\"Merge index + 1 with index.\"\"\" self.zone[index] += \"",
"self.table if i[0] == ID] def getMaster(self): \"\"\"Returns Master-field of SOA record\"\"\" return",
"in self.zone_org: self.pop = list() self.counter = False for i in range(len(self.zone)): if",
"per day.\"\"\" if len(self.serial) < 2: self.serial = \"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time, self.serial) def",
"\"KX\", \"LOC\", \"MX\", \"NAPTR\", \"NSAP\", \"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\", \"PX\", \"RP\", \"PRSIG\",",
"Name] def getID(self, ID): \"\"\"Returns entrys matching the given ID\"\"\" return [i for",
"\"/*\" in self.zone_org: self.pop = list() self.counter = False for i in range(len(self.zone)):",
"VARCHAR({3}) NOT NULL, value TEXT NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i) for i in RRsTYPES]),",
"return self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self): \"\"\"Return current IPv4 addr of origin\"\"\" return self.getRecords(Domain =",
"== 1: print(\"\"\" Bind Zonefile Parser ==================== Version: {0} Converts zone file to",
"time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self): \"\"\"Return current IPv4",
"self.table]) def getClasses(self): \"\"\"returns set of all available classes in the Zone\"\"\" return",
"self.zone_org: self.zone = [i.split(\"#\")[0] for i in self.zone if i != \"#\"] if",
"ttl continue self.type = self.getType(entry) self.klasse = self.getClass(entry) if self.type: self.default_type = self.type",
"Value and Value != i[5]: continue self.result.append(i) return self.result def getValue(self, Value): \"\"\"Returns",
"occured a fatal logical error at {0}.\\nPlease contact support for more information\".format(\" \".join(entry)))",
"\"IN\", Type=\"A\")[0][5] def getIPv6(self): \"\"\"Return current IPv6 addr of origin\"\"\" return self.getRecords(Domain =",
"else connection object is returned\"\"\" import sqlite3 as sql if table: self.tableName =",
"= self.klasse else: try: self.klasse = self.default_klasse except NameError: self.error(\"Please check your zonfile.",
"def getTypes(self): \"\"\"returns set of all available Types in the Zone\"\"\" return set([i[4]",
"= None, commit = True): \"\"\"Writes results to sql database. If table not",
"if commit = [True] chnages are automatic committed to db, else connection object",
"self.count = 0 while [i for i in self.zone if \"(\" in i",
"def error(self, error): \"\"\"returns error\"\"\" raise ZoneFileError(error, self.file) def getIndexe(self, pattern): \"\"\"return every",
"continue self.type = self.getType(entry) self.klasse = self.getClass(entry) if self.type: self.default_type = self.type else:",
"i[1]: continue if TTL and TTL != i[2]: continue if Class and Class",
"\"\"\"Returns entrys matching the given value\"\"\" return [i for i in self.table if",
"self.type, self.value)]))) # carefull!!! 123456d as dom -> undifined error self.ttl = entry.pop()",
"\"SSHFP\", \"TXT\", \"WKS\", \"X25\"] from time import strftime class ZoneFileError(Exception): \"\"\"Simple Exception handler\"\"\"",
"in CLASSES else False def isTTL(self, liste): \"\"\"returns True if given list from",
"NOT NULL, value TEXT NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i) for i in RRsTYPES]), max([len(i)",
"'{0}'\".format(self.tableName)) # insecure !!! Problems: \"db.mydomain.local\".count(\".\") != 0 -> mySQL Syntax error self.cursor.execute(\"\"\"CREATE",
"value TEXT NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i) for i in RRsTYPES]), max([len(i) for i",
"not given, zonename is used if commit = [True] chnages are automatic committed",
"Possible: class, ttl, name but: entry[1] = {TTL//class} -> !name if entry[1] ==",
"== 1: # possible: name, class, ttl if entry[0] == self.klasse: entry.pop() elif",
"del self.value self.primKey += 1 class Parser(): \"\"\"Paser - Friendly User API\"\"\" def",
"if object[:-1].isdigit() else False # -1 because of 23h for eg. def cleanUp(self):",
"zone\"\"\" self.__init__(self.file) def convert2sqlite(self, file, table = None, commit = True): \"\"\"Writes results",
"\"\"\"Returns negative cache time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self):",
"self.stream = open(file) self.zone_org = self.stream.read() self.stream.close() self.zone = self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese() self.split()",
"in self.table if i[4] == Type] def getClass(self, Class): \"\"\"Returns entrys matching the",
"empty strings and lists from zone\"\"\" self.zone = [i for i in self.zone",
"\"\"\"Returns serial-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[2] def getRefreshTime(self): \"\"\"Returns refersh time -",
"in self.table if i[5] == Value] def getType(self, Type): \"\"\"Returns entrys matching the",
"def getClasses(self): \"\"\"returns set of all available classes in the Zone\"\"\" return set([i[3]",
"self.zone if i != \"//\"] if \"/*\" in self.zone_org: self.pop = list() self.counter",
"collaps try: self.zone[i] except IndexError: break if \"(\" in self.zone[i]: self.paranthese += 1",
"object): \"\"\"returns True if obeject is a class like IN, eg.\"\"\" return True",
"set([i[0] for i in self.table]) def getDefaultTTL(self): \"\"\"Returns last used TTL\"\"\" return self.TTL",
"given object is ttl. Warning: it's just probatly correct\"\"\" return True if object[:-1].isdigit()",
"\"AFSDB\", \"APL\", \"CERT\", \"CNAME\", \"DHCID\", \"DNAME\", \"DNSKEY\", \"DS\", \"GPOS\", \"HINFO\", \"IPSECKEY\", \"ISDN\", \"KEY\",",
"self.new_time = strftime(\"%Y%m%d\") if self.old_time != self.new_time: self.serial = \"01\" else: self.serial =",
"i[0] != 0: continue if Domain and Domain != i[1]: continue if TTL",
"= \" \".join(entry[self.typeindex+1:]) entry = entry[:self.typeindex] # left: probatly name, probatly ttl, probatly",
"len(entry) if self.over == 1: # possible: name, class, ttl if entry[0] ==",
"self.ttl = entry.pop() else: self.name = entry[0] try: self.ttl = self.default_TTL except AttributeError:",
"= False, TTL = False, Class = False, Type = False, Value =",
"entrys matching the given type\"\"\" return [i for i in self.table if i[4]",
"Name, TTL, Class, Type, Value): \"\"\"Handler for parser return. Here you get all",
"= str(error) self.file = str(file) def __str__(self): return \"\"\"Please check the given zone",
"str(TTL)] def getName(self, Name): \"\"\"Returns entrys matching the given name\"\"\" return [i for",
"self.default_klasse except NameError: self.error(\"Please check your zonfile. Error at {0}.\\nClass not found\".format(\" \".join(entry)))",
"= 1.1 DOMAIN_MAX_LENGHT = 255 CLASSES = [\"IN\", \"HS\", \"CH\", \"CS\"] RRsTYPES =",
"# to compense the mapping collaps try: self.zone[i] except IndexError: break if \"(\"",
"self.klasse, self.type, self.value)]))) # carefull!!! 123456d as dom -> undifined error self.ttl =",
"zone to fields\"\"\" self.zone = [i.split() for i in self.zone] def handle(self, primKey,",
"if self.over == 2: # Possible: class, ttl, name but: entry[1] = {TTL//class}",
"+ 1 with index.\"\"\" self.zone[index] += \" \" + self.zone[index + 1] self.zone.pop(index",
"of origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"AAAA\")[0][5] def mkSerial(self, check",
"self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"AAAA\")[0][5] def mkSerial(self, check = True): \"\"\"Sets",
"python3 \"\"\" Limits: - can't read brackets in brackets - avoid using more",
"__init__(self, file): self.file = file self.zone = list() self.Table = list() # format:",
"refersh time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[3] def getRetryTime(self): \"\"\"Returns retry",
"\"#\"] if \"//\" in self.zone_org: self.zone = [i.split(\"//\")[0] for i in self.zone if",
"!= i[5]: continue self.result.append(i) return self.result def getValue(self, Value): \"\"\"Returns entrys matching the",
"your zonfile. Error at {0}.\\nClass not found\".format(\" \".join(entry))) self.typeindex = entry.index(self.type) self.value =",
"more information\".format(\" \".join(entry))) self.over = len(entry) if self.over == 2: # Possible: class,",
"True): \"\"\"Sets timestamp allone. If check, no serial > 99 are supported\"\"\" self.old_time",
"if i[3] == Class] def getTTL(self, TTL): \"\"\"Returns entrys matching the given TTL\"\"\"",
"def getDefaultTTL(self): \"\"\"Returns last used TTL\"\"\" return self.TTL def getRecords(self, ID = False,",
"\"SRV\", \"SSHFP\", \"TXT\", \"WKS\", \"X25\"] from time import strftime class ZoneFileError(Exception): \"\"\"Simple Exception",
"= entry[0] try: self.ttl = self.default_TTL except AttributeError: self.error(\"Please check your zonfile. TTL",
"self.pop.append(i) # warnig: complete line is removed. Problem with: /*comment\\nbla\\nbla*/command? self.counter = False",
"entry[1] # default ttl continue self.type = self.getType(entry) self.klasse = self.getClass(entry) if self.type:",
"liste): \"\"\"returns type of given entry\"\"\" for i in liste: if self.isType(i): return",
"if len(self.serial) < 2: self.serial = \"0{0}\".format(self.serial) return \"{0}{1}\".format(self.new_time, self.serial) def refresh(self): \"\"\"Reloads",
"break if \"(\" in self.zone[i]: self.paranthese += 1 self.use_index = i continue if",
"==================== Version: {0} Converts zone file to sqlite database Stand Alone Usage: ./parser.py",
"except IndexError: break if \"(\" in self.zone[i]: self.paranthese += 1 self.use_index = i",
"\"db.mydomain.local\".count(\".\") != 0 -> mySQL Syntax error self.cursor.execute(\"\"\"CREATE TABLE '{0}' (id INT, domain",
"to one line\"\"\" self.paranthese = 0 self.subt = 0 for i in range(len(self.zone)):",
"\"01\" else: self.serial = str(int(self.getSerial()[8:]) + 1) if check: assert int(self.serial) < 100,",
"IPv4 addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"A\")[0][5] def",
"self.primKey = 0 for entry in self.zone: if self.isTTL(entry): self.default_TTL = entry[1] #",
"i -= self.subt # to compense the mapping collaps try: self.zone[i] except IndexError:",
"matching the given class\"\"\" return [i for i in self.table if i[3] ==",
"matching rows\"\"\" self.result = list() for i in self.table: if ID and ID",
"api\"\"\" # later mySQL? self.Table.append([primKey, Name, TTL, Class, Type, Value]) def isType(self, object):",
"self.zone] def handle(self, primKey, Name, TTL, Class, Type, Value): \"\"\"Handler for parser return.",
"entry.pop() else: self.name = entry[0] try: self.ttl = self.default_TTL except AttributeError: self.error(\"Please check",
"Stand Alone Usage: ./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv) == 2: assert path.isfile(argv[1]), \"Zonefile",
"= [i.split() for i in self.zone] def handle(self, primKey, Name, TTL, Class, Type,",
"VALUES (?,?,?,?,?,?)' .format(self.tableName), self.table) if commit: self.connection.commit() self.cursor.close() else: return self.connection if __name__",
"+ self.zone[index + 1] self.zone.pop(index + 1) def rmParanthese(self): \"\"\"removes paranthes if closed",
"self.file = str(file) def __str__(self): return \"\"\"Please check the given zone file {0}.\\nFollowing",
"data -> api\"\"\" # later mySQL? self.Table.append([primKey, Name, TTL, Class, Type, Value]) def",
"print(\"warning at {0}. I'll handle it as TTL!\".format(\" | \".join([str(y) for y in",
"name but: entry[1] = {TTL//class} -> !name if entry[1] == self.klasse: entry.pop() else:",
"def isTTLobj(self, object): \"\"\"Returns if given object is ttl. Warning: it's just probatly",
"== '$TTL' and len(liste) < 3 else False def isTTLobj(self, object): \"\"\"Returns if",
"self.error(\"Paranthese Syntax: Please avoid using Paranthese in Paranthese or more then more paranthese",
"\"\"\"Paser - Friendly User API\"\"\" def __init__(self, file): import os.path as path self.file",
"self.new_time: self.serial = \"01\" else: self.serial = str(int(self.getSerial()[8:]) + 1) if check: assert",
"RRsTYPES = [\"A\",\"AAAA\", \"A6\", \"AFSDB\", \"APL\", \"CERT\", \"CNAME\", \"DHCID\", \"DNAME\", \"DNSKEY\", \"DS\", \"GPOS\",",
"to fields\"\"\" self.zone = [i.split() for i in self.zone] def handle(self, primKey, Name,",
"paranthes to one line\"\"\" self.paranthese = 0 self.subt = 0 for i in",
"if \";\" in self.zone_org: self.zone = [i.split(\";\")[0] for i in self.zone if i",
"return set([i[0] for i in self.table]) def getDefaultTTL(self): \"\"\"Returns last used TTL\"\"\" return",
"in Paranthese or more then more paranthese per line\") self.rmParanthese() del self.count def",
"for more information\".format(\" \".join(entry))) self.over = len(entry) if self.over == 2: # Possible:",
"continue self.result.append(i) return self.result def getValue(self, Value): \"\"\"Returns entrys matching the given value\"\"\"",
"liste): \"\"\"returns class of given entry\"\"\" for i in liste: if self.isClass(i): return",
"return. Here you get all data -> api\"\"\" # later mySQL? self.Table.append([primKey, Name,",
"0 -> mySQL Syntax error self.cursor.execute(\"\"\"CREATE TABLE '{0}' (id INT, domain VARCHAR({1}) NOT",
"from time import strftime class ZoneFileError(Exception): \"\"\"Simple Exception handler\"\"\" def __init__(self, error, file):",
"TEXT NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i) for i in RRsTYPES]), max([len(i) for i in",
"except AttributeError: self.error(\"Please check your zonfile. TTL not found\") self.handle(self.primKey, self.name,self.ttl, self.klasse, self.type,",
"entry[:self.typeindex] # left: probatly name, probatly ttl, probatly class self.over = len(entry) if",
"{0}.\\nPlease contact support for more information\".format(\" \".join(entry))) self.over = len(entry) if self.over ==",
"= self.type else: try: self.type = self.default_type except NameError: self.error(\"Please check your zonfile.",
"SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self): \"\"\"Returns expire time - field of SOA",
"i in self.table: if ID and ID != i[0]: continue if not isinstance(ID,",
"addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"A\")[0][5] def getIPv6(self):",
"isinstance(ID, bool) and ID == 0 and i[0] != 0: continue if Domain",
"def getTTL(self, TTL): \"\"\"Returns entrys matching the given TTL\"\"\" return [i for i",
"internal table\"\"\" return set([i[0] for i in self.table]) def getDefaultTTL(self): \"\"\"Returns last used",
"return self.TTL def getRecords(self, ID = False, Domain = False, TTL = False,",
"file line\"\"\" self.zone = [self.zone[i].replace(\"(\", \"\").replace(\")\", \"\") if self.zone[i].count(\"(\") == self.zone[i].count(\")\") else self.zone[i]",
"current IPv4 addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"A\")[0][5]",
"True if object[:-1].isdigit() else False # -1 because of 23h for eg. def",
"table = None, commit = True): \"\"\"Writes results to sql database. If table",
"= entry.pop() # Has to be ttl self.over = len(entry) if self.over ==",
"\"RT\", \"SIG\", \"SOA\", \"SPF\", \"SRV\", \"SSHFP\", \"TXT\", \"WKS\", \"X25\"] from time import strftime",
"= _Parser(file) self.table = self.parser.Table self.TTL = self.parser.default_TTL self.zonename = path.basename(self.file) del self.parser",
"self.zone = [i.split(\"#\")[0] for i in self.zone if i != \"#\"] if \"//\"",
"continue if Class and Class != i[3]: continue if Type and Type !=",
"mkSerial(self, check = True): \"\"\"Sets timestamp allone. If check, no serial > 99",
"TTL\"\"\" return [i for i in self.table if i[2] == str(TTL)] def getName(self,",
"IndexError: break if \"(\" in self.zone[i]: self.paranthese += 1 self.use_index = i continue",
"= list() for i in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter)) self.counter = self.result[-1] + 1",
"False def isClass(self, object): \"\"\"returns True if obeject is a class like IN,",
"set of all available Domains in the Zone\"\"\" return set([i[1] for i in",
"i in liste: if self.isClass(i): return i def parse(self): \"\"\"Main Parser\"\"\" self.primKey =",
"def getIPv4(self): \"\"\"Return current IPv4 addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class",
"return True if object in CLASSES else False def isTTL(self, liste): \"\"\"returns True",
"self.zone if i != \";\"] if \"#\" in self.zone_org: self.zone = [i.split(\"#\")[0] for",
"getIPv4(self): \"\"\"Return current IPv4 addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class =",
"1 self.use_index = i continue if \")\" in self.zone[i]: self.paranthese -= 1 self.move(self.use_index)",
"else False def isTTL(self, liste): \"\"\"returns True if given list from zone is",
"range(len(self.zone)): if \"/*\" in self.zone[i]: self.counter = True self.zone[i] = self.zone[i].split(\"/*\")[0] continue if",
"the Zone\"\"\" return set([i[5] for i in self.table]) def getTypes(self): \"\"\"returns set of",
"- can't read brackets in brackets - avoid using more then one bracket",
"getIPv6(self): \"\"\"Return current IPv6 addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class =",
"table else: self.tableName = self.zonename self.connection = sql.connect(file) self.cursor = self.connection.cursor() self.cursor.execute(\"drop table",
"self.over == 1: # possible: name, class, ttl if entry[0] == self.klasse: entry.pop()",
"\"\"\"Returns last used TTL\"\"\" return self.TTL def getRecords(self, ID = False, Domain =",
"self.ttl = entry.pop() # Has to be ttl self.over = len(entry) if self.over",
"given class\"\"\" return [i for i in self.table if i[3] == Class] def",
"def getID(self, ID): \"\"\"Returns entrys matching the given ID\"\"\" return [i for i",
"if domain[:-1].isdigit()\"\"\" VERSION = 1.1 DOMAIN_MAX_LENGHT = 255 CLASSES = [\"IN\", \"HS\", \"CH\",",
"= True): \"\"\"Sets timestamp allone. If check, no serial > 99 are supported\"\"\"",
"2: # Possible: class, ttl, name but: entry[1] = {TTL//class} -> !name if",
"\"\"\"Returns retry time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[4] def getExpireTime(self): \"\"\"Returns",
"cache time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self): \"\"\"Return current",
"CLASSES else False def isTTL(self, liste): \"\"\"returns True if given list from zone",
"def parse(self): \"\"\"Main Parser\"\"\" self.primKey = 0 for entry in self.zone: if self.isTTL(entry):",
"NULL, value TEXT NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i) for i in RRsTYPES]), max([len(i) for",
"= file self.parser = _Parser(file) self.table = self.parser.Table self.TTL = self.parser.default_TTL self.zonename =",
"path if len(argv) == 1: print(\"\"\" Bind Zonefile Parser ==================== Version: {0} Converts",
"self.klasse = self.default_klasse except NameError: self.error(\"Please check your zonfile. Error at {0}.\\nClass not",
"del self.parser # RAM clean def getValues(self): \"\"\"returns set of all available Values",
"Has to be ttl self.over = len(entry) if self.over == 1: # possible:",
"\"\"\"Reloads complete zone\"\"\" self.__init__(self.file) def convert2sqlite(self, file, table = None, commit = True):",
"self.move(self.use_index) self.subt += 1 continue if self.paranthese: self.move(self.use_index) self.subt += 1 def rmCompleteParanthese(self):",
"self.type, self.value) del self.value self.primKey += 1 class Parser(): \"\"\"Paser - Friendly User",
"TTL, Class, Type, Value): \"\"\"Handler for parser return. Here you get all data",
"object in CLASSES else False def isTTL(self, liste): \"\"\"returns True if given list",
"= [i for i in self.zone if i and i[0] != ''] def",
"\"\"\"Returns contact-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[1] def getSerial(self): \"\"\"Returns serial-field of SOA",
"line is removed. Problem with: /*comment\\nbla\\nbla*/command? self.counter = False continue if self.counter: self.pop.append(i)",
"i != \"#\"] if \"//\" in self.zone_org: self.zone = [i.split(\"//\")[0] for i in",
"open(file) self.zone_org = self.stream.read() self.stream.close() self.zone = self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese() self.split() self.cleanUp() self.parse()",
"[i for i in self.zone if \"(\" in i or \")\" in i]:",
"- problems by differncing ttl/domaine, if domain[:-1].isdigit()\"\"\" VERSION = 1.1 DOMAIN_MAX_LENGHT = 255",
"ID == 0 and i[0] != 0: continue if Domain and Domain !=",
"fields\"\"\" self.zone = [i.split() for i in self.zone] def handle(self, primKey, Name, TTL,",
"\"SOA\", \"SPF\", \"SRV\", \"SSHFP\", \"TXT\", \"WKS\", \"X25\"] from time import strftime class ZoneFileError(Exception):",
"not found\".format(\" \".join(entry))) self.typeindex = entry.index(self.type) self.value = \" \".join(entry[self.typeindex+1:]) entry = entry[:self.typeindex]",
"file self.zone = list() self.Table = list() # format: [primKey, name, ttl, class,",
"1) if check: assert int(self.serial) < 100, \"\"\"More then 99 changes aren't supported",
"\"TXT\", \"WKS\", \"X25\"] from time import strftime class ZoneFileError(Exception): \"\"\"Simple Exception handler\"\"\" def",
"of given entry\"\"\" for i in liste: if self.isType(i): return i def getClass(self,",
"Paranthese in Paranthese or more then more paranthese per line\") self.rmParanthese() del self.count",
"self.counter = True self.zone[i] = self.zone[i].split(\"/*\")[0] continue if \"*/\" in self.zone[i]: self.pop.append(i) #",
"more then more paranthese per line\") self.rmParanthese() del self.count def split(self): \"\"\"splits zone",
"bool) and ID == 0 and i[0] != 0: continue if Domain and",
"i in self.zone] def handle(self, primKey, Name, TTL, Class, Type, Value): \"\"\"Handler for",
"mySQL Syntax error self.cursor.execute(\"\"\"CREATE TABLE '{0}' (id INT, domain VARCHAR({1}) NOT NULL, ttl",
"True self.zone[i] = self.zone[i].split(\"/*\")[0] continue if \"*/\" in self.zone[i]: self.pop.append(i) # warnig: complete",
"return set([i[5] for i in self.table]) def getTypes(self): \"\"\"returns set of all available",
"work, but you should use it carefull - problems by differncing ttl/domaine, if",
"set([i[2] for i in self.table]) def getDomains(self): \"\"\"returns set of all available Domains",
"\"\"\"returns type of given entry\"\"\" for i in liste: if self.isType(i): return i",
"removed. Problem with: /*comment\\nbla\\nbla*/command? self.counter = False continue if self.counter: self.pop.append(i) self.pop.sort(reverse =",
"ttl/domaine, if domain[:-1].isdigit()\"\"\" VERSION = 1.1 DOMAIN_MAX_LENGHT = 255 CLASSES = [\"IN\", \"HS\",",
"= {TTL//class} -> !name if entry[1] == self.klasse: entry.pop() else: self.ttl = entry.pop()",
"the Zone (Normaly one)\"\"\" return set([i[2] for i in self.table]) def getDomains(self): \"\"\"returns",
"available TTLs in the Zone (Normaly one)\"\"\" return set([i[2] for i in self.table])",
"!= self.klasse: self.error(\"There occured a fatal logical error at {0}.\\nPlease contact support for",
"list() self.counter = False for i in range(len(self.zone)): if \"/*\" in self.zone[i]: self.counter",
"If table not given, zonename is used if commit = [True] chnages are",
"self.value) del self.value self.primKey += 1 class Parser(): \"\"\"Paser - Friendly User API\"\"\"",
"None, commit = True): \"\"\"Writes results to sql database. If table not given,",
"probatly correct\"\"\" return True if object[:-1].isdigit() else False # -1 because of 23h",
"and i[0] != ''] def getType(self, liste): \"\"\"returns type of given entry\"\"\" for",
"set of all available Types in the Zone\"\"\" return set([i[4] for i in",
"in self.table]) def getIDs(self): \"\"\"returns set of all available ID's // prim. keys",
"self.type: self.default_type = self.type else: try: self.type = self.default_type except NameError: self.error(\"Please check",
"if Value and Value != i[5]: continue self.result.append(i) return self.result def getValue(self, Value):",
"Parser\"\"\" self.primKey = 0 for entry in self.zone: if self.isTTL(entry): self.default_TTL = entry[1]",
"getType(self, Type): \"\"\"Returns entrys matching the given type\"\"\" return [i for i in",
"warnig: complete line is removed. Problem with: /*comment\\nbla\\nbla*/command? self.counter = False continue if",
"== Name] def getID(self, ID): \"\"\"Returns entrys matching the given ID\"\"\" return [i",
"of internal table\"\"\" return set([i[0] for i in self.table]) def getDefaultTTL(self): \"\"\"Returns last",
"it carefull - problems by differncing ttl/domaine, if domain[:-1].isdigit()\"\"\" VERSION = 1.1 DOMAIN_MAX_LENGHT",
"self.counter = False continue if self.counter: self.pop.append(i) self.pop.sort(reverse = True) # To avoid",
"__name__ == \"__main__\": from sys import argv from os import path as path",
"getValue(self, Value): \"\"\"Returns entrys matching the given value\"\"\" return [i for i in",
"self.parser.default_TTL self.zonename = path.basename(self.file) del self.parser # RAM clean def getValues(self): \"\"\"returns set",
"[i for i in self.zone if i and i[0] != ''] def getType(self,",
"self.zone = list() self.Table = list() # format: [primKey, name, ttl, class, type,",
"i in self.table if i[0] == ID] def getMaster(self): \"\"\"Returns Master-field of SOA",
"+= 1 continue if self.paranthese: self.move(self.use_index) self.subt += 1 def rmCompleteParanthese(self): \"\"\"removes every",
"entry.pop() # Has to be ttl self.over = len(entry) if self.over == 1:",
"if self.klasse: self.default_klasse = self.klasse else: try: self.klasse = self.default_klasse except NameError: self.error(\"Please",
"= [\"IN\", \"HS\", \"CH\", \"CS\"] RRsTYPES = [\"A\",\"AAAA\", \"A6\", \"AFSDB\", \"APL\", \"CERT\", \"CNAME\",",
"\"\"\"returns error\"\"\" raise ZoneFileError(error, self.file) def getIndexe(self, pattern): \"\"\"return every index of fitting",
"self.pop: self.zone.pop(i) def move(self, index): \"\"\"Merge index + 1 with index.\"\"\" self.zone[index] +=",
"in self.table if i[3] == Class] def getTTL(self, TTL): \"\"\"Returns entrys matching the",
"handle(self, primKey, Name, TTL, Class, Type, Value): \"\"\"Handler for parser return. Here you",
"print(\"\"\" Bind Zonefile Parser ==================== Version: {0} Converts zone file to sqlite database",
"== 2: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote",
"set of all available Values in the Zone\"\"\" return set([i[5] for i in",
"entry\"\"\" for i in liste: if self.isType(i): return i def getClass(self, liste): \"\"\"returns",
"current IPv6 addr of origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"AAAA\")[0][5]",
"== self.zone[i].count(\")\") else self.zone[i] for i in range(len(self.zone))] def mergeParanthese(self): \"\"\"Merge every paranthes",
"matching the given ID\"\"\" return [i for i in self.table if i[0] ==",
"NULL, ttl INT, class VARCHAR({2}) NOT NULL, type VARCHAR({3}) NOT NULL, value TEXT",
"y in (self.primKey, self.name, entry[0], self.klasse, self.type, self.value)]))) # carefull!!! 123456d as dom",
"self.name,self.ttl, self.klasse, self.type, self.value) del self.value self.primKey += 1 class Parser(): \"\"\"Paser -",
"def getZoneContact(self): \"\"\"Returns contact-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[1] def getSerial(self): \"\"\"Returns serial-field",
"table: self.tableName = table else: self.tableName = self.zonename self.connection = sql.connect(file) self.cursor =",
"self.old_time != self.new_time: self.serial = \"01\" else: self.serial = str(int(self.getSerial()[8:]) + 1) if",
"domain VARCHAR({1}) NOT NULL, ttl INT, class VARCHAR({2}) NOT NULL, type VARCHAR({3}) NOT",
"self.type = self.default_type except NameError: self.error(\"Please check your zonfile. Error at {0}.\\nType not",
"Usage: ./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv) == 2: assert path.isfile(argv[1]), \"Zonefile {0} not",
"all available Values in the Zone\"\"\" return set([i[5] for i in self.table]) def",
"lists from zone\"\"\" self.zone = [i for i in self.zone if i and",
"check, no serial > 99 are supported\"\"\" self.old_time = self.getSerial()[:8] self.new_time = strftime(\"%Y%m%d\")",
"self.zone[i].split(\"/*\")[0] continue if \"*/\" in self.zone[i]: self.pop.append(i) # warnig: complete line is removed.",
"in self.zone[i]: self.counter = True self.zone[i] = self.zone[i].split(\"/*\")[0] continue if \"*/\" in self.zone[i]:",
"__str__(self): return \"\"\"Please check the given zone file {0}.\\nFollowing Error occured: {1}\"\"\".format(self.file, self.error)",
"ID = False, Domain = False, TTL = False, Class = False, Type",
"not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(argv[2]) print(\"wrote database to {0}\".format(argv[2])) else: print(\"To many",
"self.result.append(i) return self.result def getValue(self, Value): \"\"\"Returns entrys matching the given value\"\"\" return",
"for i in self.table if i[5] == Value] def getType(self, Type): \"\"\"Returns entrys",
"- field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self): \"\"\"Returns negative cache time",
"self.split() self.cleanUp() self.parse() def error(self, error): \"\"\"returns error\"\"\" raise ZoneFileError(error, self.file) def getIndexe(self,",
"is ttl. Warning: it's just probatly correct\"\"\" return True if object[:-1].isdigit() else False",
"{0}.\\nType not found\".format(\" \".join(entry))) if self.klasse: self.default_klasse = self.klasse else: try: self.klasse =",
"Class != i[3]: continue if Type and Type != i[4]: continue if Value",
"if self.old_time != self.new_time: self.serial = \"01\" else: self.serial = str(int(self.getSerial()[8:]) + 1)",
"i[0] == ID] def getMaster(self): \"\"\"Returns Master-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[0] def",
"\"CS\"] RRsTYPES = [\"A\",\"AAAA\", \"A6\", \"AFSDB\", \"APL\", \"CERT\", \"CNAME\", \"DHCID\", \"DNAME\", \"DNSKEY\", \"DS\",",
"i[5]: continue self.result.append(i) return self.result def getValue(self, Value): \"\"\"Returns entrys matching the given",
"i in range(len(self.zone)): if \"/*\" in self.zone[i]: self.counter = True self.zone[i] = self.zone[i].split(\"/*\")[0]",
"class Parser(): \"\"\"Paser - Friendly User API\"\"\" def __init__(self, file): import os.path as",
"0: continue if Domain and Domain != i[1]: continue if TTL and TTL",
"- field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self): \"\"\"Return current IPv4 addr",
"getExpireTime(self): \"\"\"Returns expire time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self):",
"self.result def getValue(self, Value): \"\"\"Returns entrys matching the given value\"\"\" return [i for",
"in CLASSES]))) # also insecure self.cursor.executemany('INSERT INTO \"{0}\" VALUES (?,?,?,?,?,?)' .format(self.tableName), self.table) if",
"\"NXT\", \"PTR\", \"PX\", \"RP\", \"PRSIG\", \"RT\", \"SIG\", \"SOA\", \"SPF\", \"SRV\", \"SSHFP\", \"TXT\", \"WKS\",",
"Class = \"IN\", Type=\"A\")[0][5] def getIPv6(self): \"\"\"Return current IPv6 addr of origin\"\"\" return",
"self.over = len(entry) if self.over == 3: if entry.pop(2) != self.klasse: self.error(\"There occured",
"self.tableName = table else: self.tableName = self.zonename self.connection = sql.connect(file) self.cursor = self.connection.cursor()",
"set of all available classes in the Zone\"\"\" return set([i[3] for i in",
"\"\"\"Main Parser\"\"\" def __init__(self, file): self.file = file self.zone = list() self.Table =",
"\".join([str(y) for y in (self.primKey, self.name, entry[0], self.klasse, self.type, self.value)]))) # carefull!!! 123456d",
"TTL, Class, Type, Value]) def isType(self, object): \"\"\"returns true if object is a",
"\"PX\", \"RP\", \"PRSIG\", \"RT\", \"SIG\", \"SOA\", \"SPF\", \"SRV\", \"SSHFP\", \"TXT\", \"WKS\", \"X25\"] from",
"\"SPF\", \"SRV\", \"SSHFP\", \"TXT\", \"WKS\", \"X25\"] from time import strftime class ZoneFileError(Exception): \"\"\"Simple",
"/*comment\\nbla\\nbla*/command? self.counter = False continue if self.counter: self.pop.append(i) self.pop.sort(reverse = True) # To",
"\".join(entry))) self.over = len(entry) if self.over == 2: # Possible: class, ttl, name",
"in range(len(self.zone)): i -= self.subt # to compense the mapping collaps try: self.zone[i]",
"!= i[4]: continue if Value and Value != i[5]: continue self.result.append(i) return self.result",
"Friendly User API\"\"\" def __init__(self, file): import os.path as path self.file = file",
"i in self.table if i[4] == Type] def getClass(self, Class): \"\"\"Returns entrys matching",
"of origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"A\")[0][5] def getIPv6(self): \"\"\"Return",
"list() # format: [primKey, name, ttl, class, type, value] self.stream = open(file) self.zone_org",
"record\"\"\" return self.getType(\"SOA\")[0][5].split()[6] def getIPv4(self): \"\"\"Return current IPv4 addr of origin\"\"\" return self.getRecords(Domain",
"self.zone[i]: self.counter = True self.zone[i] = self.zone[i].split(\"/*\")[0] continue if \"*/\" in self.zone[i]: self.pop.append(i)",
"list from zone is TTL record\"\"\" return True if liste[0] == '$TTL' and",
"in self.zone if i and i[0] != ''] def getType(self, liste): \"\"\"returns type",
"origin\"\"\" return self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"AAAA\")[0][5] def mkSerial(self, check =",
"100: self.error(\"Paranthese Syntax: Please avoid using Paranthese in Paranthese or more then more",
"= False, Type = False, Value = False): \"\"\"MetaGer - returns list of",
"later mySQL? self.Table.append([primKey, Name, TTL, Class, Type, Value]) def isType(self, object): \"\"\"returns true",
"of given entry\"\"\" for i in liste: if self.isClass(i): return i def parse(self):",
"= self.stream.read() self.stream.close() self.zone = self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese() self.split() self.cleanUp() self.parse() def error(self,",
"return \"\"\"Please check the given zone file {0}.\\nFollowing Error occured: {1}\"\"\".format(self.file, self.error) class",
"[i for i in self.table if i[1] == Name] def getID(self, ID): \"\"\"Returns",
"while [i for i in self.zone if \"(\" in i or \")\" in",
"at {0}. I'll handle it as TTL!\".format(\" | \".join([str(y) for y in (self.primKey,",
"# insecure !!! Problems: \"db.mydomain.local\".count(\".\") != 0 -> mySQL Syntax error self.cursor.execute(\"\"\"CREATE TABLE",
"int(self.serial) < 100, \"\"\"More then 99 changes aren't supported per day.\"\"\" if len(self.serial)",
"sqlite database Stand Alone Usage: ./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv) == 2: assert",
"class, type, value] self.stream = open(file) self.zone_org = self.stream.read() self.stream.close() self.zone = self.zone_org.splitlines()",
"isType(self, object): \"\"\"returns true if object is a entry type like NS, eg.\"\"\"",
"matching the given type\"\"\" return [i for i in self.table if i[4] ==",
"for i in self.table if i[4] == Type] def getClass(self, Class): \"\"\"Returns entrys",
"brackets in brackets - avoid using more then one bracket per line. Normally",
"\"\"\"returns set of all available Domains in the Zone\"\"\" return set([i[1] for i",
"\"\"\"Simple Exception handler\"\"\" def __init__(self, error, file): self.error = str(error) self.file = str(file)",
"SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self): \"\"\"Returns contact-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[1]",
"if i != \";\"] if \"#\" in self.zone_org: self.zone = [i.split(\"#\")[0] for i",
"self.zone if i != \"#\"] if \"//\" in self.zone_org: self.zone = [i.split(\"//\")[0] for",
"self.table if i[3] == Class] def getTTL(self, TTL): \"\"\"Returns entrys matching the given",
"\"CERT\", \"CNAME\", \"DHCID\", \"DNAME\", \"DNSKEY\", \"DS\", \"GPOS\", \"HINFO\", \"IPSECKEY\", \"ISDN\", \"KEY\", \"KX\", \"LOC\",",
"\"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\", \"PX\", \"RP\", \"PRSIG\", \"RT\", \"SIG\", \"SOA\", \"SPF\", \"SRV\", \"SSHFP\",",
"//)\"\"\" if \";\" in self.zone_org: self.zone = [i.split(\";\")[0] for i in self.zone if",
"\"\"\"returns True if obeject is a class like IN, eg.\"\"\" return True if",
"return self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self): \"\"\"Returns negative cache time - field of SOA record\"\"\"",
"class VARCHAR({2}) NOT NULL, type VARCHAR({3}) NOT NULL, value TEXT NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT,",
"self.zone.pop(index + 1) def rmParanthese(self): \"\"\"removes paranthes if closed from zone file line\"\"\"",
"Values in the Zone\"\"\" return set([i[5] for i in self.table]) def getTypes(self): \"\"\"returns",
"for i in self.table]) def getIDs(self): \"\"\"returns set of all available ID's //",
"\"\"\"Returns entrys matching the given TTL\"\"\" return [i for i in self.table if",
"= 0 while [i for i in self.zone if \"(\" in i or",
"self.count += 1 self.rmParanthese() self.mergeParanthese() if self.count > 100: self.error(\"Paranthese Syntax: Please avoid",
"self.type else: try: self.type = self.default_type except NameError: self.error(\"Please check your zonfile. Error",
"ttl, name but: entry[1] = {TTL//class} -> !name if entry[1] == self.klasse: entry.pop()",
"self.cursor.execute(\"drop table if exists '{0}'\".format(self.tableName)) # insecure !!! Problems: \"db.mydomain.local\".count(\".\") != 0 ->",
"def convert2sqlite(self, file, table = None, commit = True): \"\"\"Writes results to sql",
"def rmParanthese(self): \"\"\"removes paranthes if closed from zone file line\"\"\" self.zone = [self.zone[i].replace(\"(\",",
"\"WKS\", \"X25\"] from time import strftime class ZoneFileError(Exception): \"\"\"Simple Exception handler\"\"\" def __init__(self,",
"zone (;, #, /**/, //)\"\"\" if \";\" in self.zone_org: self.zone = [i.split(\";\")[0] for",
"False, Class = False, Type = False, Value = False): \"\"\"MetaGer - returns",
"type VARCHAR({3}) NOT NULL, value TEXT NOT NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i) for i in",
"i in self.table if i[5] == Value] def getType(self, Type): \"\"\"Returns entrys matching",
"continue if Value and Value != i[5]: continue self.result.append(i) return self.result def getValue(self,",
"== ID] def getMaster(self): \"\"\"Returns Master-field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[0] def getZoneContact(self):",
"in self.zone[i]: self.paranthese -= 1 self.move(self.use_index) self.subt += 1 continue if self.paranthese: self.move(self.use_index)",
"in the Zone (Normaly one)\"\"\" return set([i[2] for i in self.table]) def getDomains(self):",
"differncing ttl/domaine, if domain[:-1].isdigit()\"\"\" VERSION = 1.1 DOMAIN_MAX_LENGHT = 255 CLASSES = [\"IN\",",
"self.paranthese: self.move(self.use_index) self.subt += 1 def rmCompleteParanthese(self): \"\"\"removes every paranthes from zone by",
"\"GPOS\", \"HINFO\", \"IPSECKEY\", \"ISDN\", \"KEY\", \"KX\", \"LOC\", \"MX\", \"NAPTR\", \"NSAP\", \"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\",",
"more paranthese per line\") self.rmParanthese() del self.count def split(self): \"\"\"splits zone to fields\"\"\"",
"\"\"\"Main Parser\"\"\" self.primKey = 0 for entry in self.zone: if self.isTTL(entry): self.default_TTL =",
"TTL != i[2]: continue if Class and Class != i[3]: continue if Type",
"for i in self.zone] def handle(self, primKey, Name, TTL, Class, Type, Value): \"\"\"Handler",
"\"\"\" Limits: - can't read brackets in brackets - avoid using more then",
"self.result = list() for i in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter)) self.counter = self.result[-1] +",
"if self.isClass(i): return i def parse(self): \"\"\"Main Parser\"\"\" self.primKey = 0 for entry",
"the given zone file {0}.\\nFollowing Error occured: {1}\"\"\".format(self.file, self.error) class _Parser(): \"\"\"Main Parser\"\"\"",
"contact support for more information\".format(\" \".join(entry))) self.over = len(entry) if self.over == 2:",
"in range(len(self.zone))] def mergeParanthese(self): \"\"\"Merge every paranthes to one line\"\"\" self.paranthese = 0",
"for i in self.table if i[2] == str(TTL)] def getName(self, Name): \"\"\"Returns entrys",
"= self.connection.cursor() self.cursor.execute(\"drop table if exists '{0}'\".format(self.tableName)) # insecure !!! Problems: \"db.mydomain.local\".count(\".\") !=",
"i or \")\" in i]: self.count += 1 self.rmParanthese() self.mergeParanthese() if self.count >",
"pattern): \"\"\"return every index of fitting patter\"\"\" self.counter = 0 self.result = list()",
"entry[0] == self.klasse: entry.pop() elif self.isTTLobj(entry[0]): print(\"warning at {0}. I'll handle it as",
"TTL = False, Class = False, Type = False, Value = False): \"\"\"MetaGer",
"\"NS\", \"NSEC\", \"NSEC3\",\"NSEC3PARAM\", \"NXT\", \"PTR\", \"PX\", \"RP\", \"PRSIG\", \"RT\", \"SIG\", \"SOA\", \"SPF\", \"SRV\",",
"self.getRecords(Domain = \"@\", Class = \"IN\", Type=\"A\")[0][5] def getIPv6(self): \"\"\"Return current IPv6 addr",
"file to sqlite database Stand Alone Usage: ./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION)) elif len(argv) ==",
"if entry[0] == self.klasse: entry.pop() elif self.isTTLobj(entry[0]): print(\"warning at {0}. I'll handle it",
"object): \"\"\"Returns if given object is ttl. Warning: it's just probatly correct\"\"\" return",
"self.table]) def getTypes(self): \"\"\"returns set of all available Types in the Zone\"\"\" return",
"# carefull!!! 123456d as dom -> undifined error self.ttl = entry.pop() else: self.name",
"[i.split(\"#\")[0] for i in self.zone if i != \"#\"] if \"//\" in self.zone_org:",
"getValues(self): \"\"\"returns set of all available Values in the Zone\"\"\" return set([i[5] for",
"Type and Type != i[4]: continue if Value and Value != i[5]: continue",
"def isType(self, object): \"\"\"returns true if object is a entry type like NS,",
"= open(file) self.zone_org = self.stream.read() self.stream.close() self.zone = self.zone_org.splitlines() self.rmComment() self.rmCompleteParanthese() self.split() self.cleanUp()",
"try: self.klasse = self.default_klasse except NameError: self.error(\"Please check your zonfile. Error at {0}.\\nClass",
"for i in self.table]) def getClasses(self): \"\"\"returns set of all available classes in",
"you should use it carefull - problems by differncing ttl/domaine, if domain[:-1].isdigit()\"\"\" VERSION",
"NameError: self.error(\"Please check your zonfile. Error at {0}.\\nType not found\".format(\" \".join(entry))) if self.klasse:",
"entry[0] try: self.ttl = self.default_TTL except AttributeError: self.error(\"Please check your zonfile. TTL not",
"index): \"\"\"Merge index + 1 with index.\"\"\" self.zone[index] += \" \" + self.zone[index",
"return set([i[4] for i in self.table]) def getClasses(self): \"\"\"returns set of all available",
"also insecure self.cursor.executemany('INSERT INTO \"{0}\" VALUES (?,?,?,?,?,?)' .format(self.tableName), self.table) if commit: self.connection.commit() self.cursor.close()",
"\"(\" in self.zone[i]: self.paranthese += 1 self.use_index = i continue if \")\" in",
"self.zone = [i.split(\";\")[0] for i in self.zone if i != \";\"] if \"#\"",
"self.parser.Table self.TTL = self.parser.default_TTL self.zonename = path.basename(self.file) del self.parser # RAM clean def",
"self.klasse: entry.pop() elif self.isTTLobj(entry[0]): print(\"warning at {0}. I'll handle it as TTL!\".format(\" |",
"in self.zone if \"(\" in i or \")\" in i]: self.count += 1",
"self.old_time = self.getSerial()[:8] self.new_time = strftime(\"%Y%m%d\") if self.old_time != self.new_time: self.serial = \"01\"",
"the given type\"\"\" return [i for i in self.table if i[4] == Type]",
"are automatic committed to db, else connection object is returned\"\"\" import sqlite3 as",
"def getRecords(self, ID = False, Domain = False, TTL = False, Class =",
"move(self, index): \"\"\"Merge index + 1 with index.\"\"\" self.zone[index] += \" \" +",
"self.zone if \"(\" in i or \")\" in i]: self.count += 1 self.rmParanthese()",
"Value): \"\"\"Returns entrys matching the given value\"\"\" return [i for i in self.table",
"self.typeindex = entry.index(self.type) self.value = \" \".join(entry[self.typeindex+1:]) entry = entry[:self.typeindex] # left: probatly",
"self.over = len(entry) if self.over == 2: # Possible: class, ttl, name but:",
"results to sql database. If table not given, zonename is used if commit",
"file): self.file = file self.zone = list() self.Table = list() # format: [primKey,",
"(self.primKey, self.name, entry[0], self.klasse, self.type, self.value)]))) # carefull!!! 123456d as dom -> undifined",
"= self.default_type except NameError: self.error(\"Please check your zonfile. Error at {0}.\\nType not found\".format(\"",
"User API\"\"\" def __init__(self, file): import os.path as path self.file = file self.parser",
"table not given, zonename is used if commit = [True] chnages are automatic",
"is a entry type like NS, eg.\"\"\" return True if object in RRsTYPES",
"set of all available TTLs in the Zone (Normaly one)\"\"\" return set([i[2] for",
"found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(argv[2]) print(\"wrote database to {0}\".format(argv[2])) else: print(\"To many arguments\")",
"mySQL? self.Table.append([primKey, Name, TTL, Class, Type, Value]) def isType(self, object): \"\"\"returns true if",
"!= ''] def getType(self, liste): \"\"\"returns type of given entry\"\"\" for i in",
"for i in range(self.zone_org.count(pattern)): self.result.append(self.zone_org.find(pattern, self.counter)) self.counter = self.result[-1] + 1 return self.result",
"file): self.error = str(error) self.file = str(file) def __str__(self): return \"\"\"Please check the",
"{0}. I'll handle it as TTL!\".format(\" | \".join([str(y) for y in (self.primKey, self.name,",
"check = True): \"\"\"Sets timestamp allone. If check, no serial > 99 are",
"and Domain != i[1]: continue if TTL and TTL != i[2]: continue if",
"is used if commit = [True] chnages are automatic committed to db, else",
"self.pop = list() self.counter = False for i in range(len(self.zone)): if \"/*\" in",
"= Parser(argv[1]) parser.convert2sqlite(\"zone.sqlite\") print(\"wrote database to zone.sqlite\") elif len(argv) == 3: assert path.isfile(argv[1]),",
"Limits: - can't read brackets in brackets - avoid using more then one",
"record\"\"\" return True if liste[0] == '$TTL' and len(liste) < 3 else False",
"len(entry) if self.over == 2: # Possible: class, ttl, name but: entry[1] =",
"255 CLASSES = [\"IN\", \"HS\", \"CH\", \"CS\"] RRsTYPES = [\"A\",\"AAAA\", \"A6\", \"AFSDB\", \"APL\",",
"NULL)\"\"\".format(self.tableName, DOMAIN_MAX_LENGHT, max([len(i) for i in RRsTYPES]), max([len(i) for i in CLASSES]))) #",
"else: self.ttl = entry.pop() # Has to be ttl self.over = len(entry) if",
"self.move(self.use_index) self.subt += 1 def rmCompleteParanthese(self): \"\"\"removes every paranthes from zone by merging\"\"\"",
"of all available Values in the Zone\"\"\" return set([i[5] for i in self.table])",
"< 100, \"\"\"More then 99 changes aren't supported per day.\"\"\" if len(self.serial) <",
"3: assert path.isfile(argv[1]), \"Zonefile {0} not found\".format(argv[1]) parser = Parser(argv[1]) parser.convert2sqlite(argv[2]) print(\"wrote database",
"the Zone\"\"\" return set([i[4] for i in self.table]) def getClasses(self): \"\"\"returns set of",
"if exists '{0}'\".format(self.tableName)) # insecure !!! Problems: \"db.mydomain.local\".count(\".\") != 0 -> mySQL Syntax",
"self.zone = [self.zone[i].replace(\"(\", \"\").replace(\")\", \"\") if self.zone[i].count(\"(\") == self.zone[i].count(\")\") else self.zone[i] for i",
"Domains in the Zone\"\"\" return set([i[1] for i in self.table]) def getIDs(self): \"\"\"returns",
"\"DS\", \"GPOS\", \"HINFO\", \"IPSECKEY\", \"ISDN\", \"KEY\", \"KX\", \"LOC\", \"MX\", \"NAPTR\", \"NSAP\", \"NS\", \"NSEC\",",
"Class and Class != i[3]: continue if Type and Type != i[4]: continue",
"line\"\"\" self.paranthese = 0 self.subt = 0 for i in range(len(self.zone)): i -=",
"eg. def cleanUp(self): \"\"\"removes empty strings and lists from zone\"\"\" self.zone = [i",
"if i[2] == str(TTL)] def getName(self, Name): \"\"\"Returns entrys matching the given name\"\"\"",
"expire time - field of SOA record\"\"\" return self.getType(\"SOA\")[0][5].split()[5] def getNegativeCache(self): \"\"\"Returns negative",
"class\"\"\" return [i for i in self.table if i[3] == Class] def getTTL(self,",
"\"\"\"removes every paranthes from zone by merging\"\"\" self.count = 0 while [i for",
"{0} Converts zone file to sqlite database Stand Alone Usage: ./parser.py zonefile [database=zone.sqlite]\\n\"\"\".format(VERSION))",
"paranthese per line\") self.rmParanthese() del self.count def split(self): \"\"\"splits zone to fields\"\"\" self.zone"
] |
[
"= { \"factory\": { \"address\": \"0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95\", \"abi\": factoryAbi, }, \"exchange\": { \"abi\": exchangeAbi,",
"util.read_json(\"./uniswap/abi/Exchange.json\") factoryAbi = util.read_json(\"./uniswap/abi/Factory.json\") contracts = { \"factory\": { \"address\": \"0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95\", \"abi\": factoryAbi,",
"= util.read_json(\"./uniswap/abi/Factory.json\") contracts = { \"factory\": { \"address\": \"0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95\", \"abi\": factoryAbi, }, \"exchange\":",
"from .. import util exchangeAbi = util.read_json(\"./uniswap/abi/Exchange.json\") factoryAbi = util.read_json(\"./uniswap/abi/Factory.json\") contracts = {",
".. import util exchangeAbi = util.read_json(\"./uniswap/abi/Exchange.json\") factoryAbi = util.read_json(\"./uniswap/abi/Factory.json\") contracts = { \"factory\":",
"= util.read_json(\"./uniswap/abi/Exchange.json\") factoryAbi = util.read_json(\"./uniswap/abi/Factory.json\") contracts = { \"factory\": { \"address\": \"0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95\", \"abi\":",
"util.read_json(\"./uniswap/abi/Factory.json\") contracts = { \"factory\": { \"address\": \"0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95\", \"abi\": factoryAbi, }, \"exchange\": {",
"{ \"factory\": { \"address\": \"0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95\", \"abi\": factoryAbi, }, \"exchange\": { \"abi\": exchangeAbi, },",
"<gh_stars>1-10 from .. import util exchangeAbi = util.read_json(\"./uniswap/abi/Exchange.json\") factoryAbi = util.read_json(\"./uniswap/abi/Factory.json\") contracts =",
"util exchangeAbi = util.read_json(\"./uniswap/abi/Exchange.json\") factoryAbi = util.read_json(\"./uniswap/abi/Factory.json\") contracts = { \"factory\": { \"address\":",
"import util exchangeAbi = util.read_json(\"./uniswap/abi/Exchange.json\") factoryAbi = util.read_json(\"./uniswap/abi/Factory.json\") contracts = { \"factory\": {",
"exchangeAbi = util.read_json(\"./uniswap/abi/Exchange.json\") factoryAbi = util.read_json(\"./uniswap/abi/Factory.json\") contracts = { \"factory\": { \"address\": \"0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95\",",
"\"factory\": { \"address\": \"0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95\", \"abi\": factoryAbi, }, \"exchange\": { \"abi\": exchangeAbi, }, }",
"factoryAbi = util.read_json(\"./uniswap/abi/Factory.json\") contracts = { \"factory\": { \"address\": \"0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95\", \"abi\": factoryAbi, },",
"contracts = { \"factory\": { \"address\": \"0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95\", \"abi\": factoryAbi, }, \"exchange\": { \"abi\":"
] |
[
"input_shape: th.Union[th.Tuple[int], th.List[int]], input_clamp: th.Optional[th.Union[float, tuple]] = (-1., 1.), model_params: th.Optional[dict] = None,",
"typing as th import torchmetrics from .. import utils as ebad_utils class AnoTrainer(pl.LightningModule):",
"th import torchmetrics from .. import utils as ebad_utils class AnoTrainer(pl.LightningModule): def __init__(",
"random images and unseen examples inputs, targets = batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) * 2",
"self.noise_eps) if self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp if isinstance(self.hparams.input_clamp, tuple) else ( -self.hparams.input_clamp, self.hparams.input_clamp))) #",
"* reg_loss self.log(f'loss/regularization/train', reg_loss) cdiv_loss = samples_out.mean() - samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss +=",
"x): z = self.model(x) return z def training_step(self, batch, batch_idx: th.Optional[int] = None,",
"tuple) else ( -self.hparams.input_clamp, self.hparams.input_clamp))) # Obtain samples samples = self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device)",
"inputs, targets = batch if self.noise_eps: # add minimal noise to the original",
"as pl import torch import typing as th import torchmetrics from .. import",
"# add minimal noise to the original inputs to prevent the model from",
"= torch.cat([inputs, samples], dim=0) inputs_out, samples_out = self.model(all_inputs).chunk(2, dim=0) # Calculate losses loss",
"self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean()) return loss def validation_step(self, batch, batch_idx: th.Optional[int] = None,",
"= batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) * 2 - 1).mean()) scores = self.model(inputs) self.val_auroc( preds=-scores,",
"1).mean()) scores = self.model(inputs) self.val_auroc( preds=-scores, # auroc expects predictions to have higher",
"expects predictions to have higher values for the positive class targets=targets ) self.log('metrics/auroc/val',",
"self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp if isinstance(self.hparams.input_clamp, tuple) else ( -self.hparams.input_clamp, self.hparams.input_clamp))) # Obtain samples",
"None): # calculate the contrastive divergence between purely random images and unseen examples",
"between purely random images and unseen examples inputs, targets = batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs)",
"dict())) # metrics self.val_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) def forward(self,",
"as ebad_utils class AnoTrainer(pl.LightningModule): def __init__( self, model_cls: th.Union[str, torch.nn.Module], input_shape: th.Union[th.Tuple[int], th.List[int]],",
"ebad_utils class AnoTrainer(pl.LightningModule): def __init__( self, model_cls: th.Union[str, torch.nn.Module], input_shape: th.Union[th.Tuple[int], th.List[int]], input_clamp:",
"= torchmetrics.AUROC(num_classes=2, pos_label=1) def forward(self, x): z = self.model(x) return z def training_step(self,",
"scores = self.model(inputs) self.val_auroc( preds=-scores, # auroc expects predictions to have higher values",
"2 - 1).mean()) scores = self.model(inputs) self.val_auroc( preds=-scores, # auroc expects predictions to",
"if self.regularizer_alpha: reg_loss = (inputs_out ** 2 + samples_out ** 2).mean() loss +=",
"# Calculate losses loss = 0. if self.regularizer_alpha: reg_loss = (inputs_out ** 2",
"the model from focusing on purely \"clean\" inputs inputs.add_(torch.randn_like(inputs) * self.noise_eps) if self.hparams.input_clamp:",
"optimizer_idx: th.Optional[int] = None): # calculate the contrastive divergence between purely random images",
"self.test_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) def forward(self, x): z = self.model(x) return z def",
"pos_label=1) def forward(self, x): z = self.model(x) return z def training_step(self, batch, batch_idx:",
"torchmetrics.AUROC(num_classes=2, pos_label=1) def forward(self, x): z = self.model(x) return z def training_step(self, batch,",
"None, **kwargs, ): super().__init__() self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict())) # metrics self.val_auroc =",
"batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): inputs, targets = batch",
"= None): # calculate the contrastive divergence between purely random images and unseen",
"= samples_out.mean() - samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss += cdiv_loss self.log(f'loss/train', loss) self.log(f'metrics/inputs/train', inputs_out.mean())",
"# metrics self.val_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) def forward(self, x):",
"+= self.regularizer_alpha * reg_loss self.log(f'loss/regularization/train', reg_loss) cdiv_loss = samples_out.mean() - samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss)",
"purely random images and unseen examples inputs, targets = batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) *",
"import pytorch_lightning as pl import torch import typing as th import torchmetrics from",
"th.List[int]], input_clamp: th.Optional[th.Union[float, tuple]] = (-1., 1.), model_params: th.Optional[dict] = None, **kwargs, ):",
"score for all images all_inputs = torch.cat([inputs, samples], dim=0) inputs_out, samples_out = self.model(all_inputs).chunk(2,",
"self.model(torch.rand_like(inputs) * 2 - 1).mean()) scores = self.model(inputs) self.val_auroc( preds=-scores, # auroc expects",
"= (inputs_out ** 2 + samples_out ** 2).mean() loss += self.regularizer_alpha * reg_loss",
"samples], dim=0) inputs_out, samples_out = self.model(all_inputs).chunk(2, dim=0) # Calculate losses loss = 0.",
"samples = self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device) # Predict energy score for all images all_inputs",
"dim=0) # Calculate losses loss = 0. if self.regularizer_alpha: reg_loss = (inputs_out **",
"# calculate the contrastive divergence between purely random images and unseen examples inputs,",
"torchmetrics from .. import utils as ebad_utils class AnoTrainer(pl.LightningModule): def __init__( self, model_cls:",
"contrastive divergence between purely random images and unseen examples inputs, targets = batch",
"device=inputs.device) # Predict energy score for all images all_inputs = torch.cat([inputs, samples], dim=0)",
"validation_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): # calculate the",
"self.noise_eps: # add minimal noise to the original inputs to prevent the model",
"def forward(self, x): z = self.model(x) return z def training_step(self, batch, batch_idx: th.Optional[int]",
"= self.model(inputs) self.val_auroc( preds=-scores, # auroc expects predictions to have higher values for",
"= None): inputs, targets = batch if self.noise_eps: # add minimal noise to",
"__init__( self, model_cls: th.Union[str, torch.nn.Module], input_shape: th.Union[th.Tuple[int], th.List[int]], input_clamp: th.Optional[th.Union[float, tuple]] = (-1.,",
"# Predict energy score for all images all_inputs = torch.cat([inputs, samples], dim=0) inputs_out,",
"reg_loss = (inputs_out ** 2 + samples_out ** 2).mean() loss += self.regularizer_alpha *",
"torch.nn.Module], input_shape: th.Union[th.Tuple[int], th.List[int]], input_clamp: th.Optional[th.Union[float, tuple]] = (-1., 1.), model_params: th.Optional[dict] =",
"purely \"clean\" inputs inputs.add_(torch.randn_like(inputs) * self.noise_eps) if self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp if isinstance(self.hparams.input_clamp, tuple)",
"samples_out.mean()) return loss def validation_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] =",
"self.model(inputs) self.val_auroc( preds=-scores, # auroc expects predictions to have higher values for the",
"*(self.hparams.input_clamp if isinstance(self.hparams.input_clamp, tuple) else ( -self.hparams.input_clamp, self.hparams.input_clamp))) # Obtain samples samples =",
"images all_inputs = torch.cat([inputs, samples], dim=0) inputs_out, samples_out = self.model(all_inputs).chunk(2, dim=0) # Calculate",
"( -self.hparams.input_clamp, self.hparams.input_clamp))) # Obtain samples samples = self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device) # Predict",
"ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict())) # metrics self.val_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1)",
"class AnoTrainer(pl.LightningModule): def __init__( self, model_cls: th.Union[str, torch.nn.Module], input_shape: th.Union[th.Tuple[int], th.List[int]], input_clamp: th.Optional[th.Union[float,",
"pos_label=1) self.test_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) def forward(self, x): z = self.model(x) return z",
"th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): inputs, targets = batch if self.noise_eps:",
"cdiv_loss) loss += cdiv_loss self.log(f'loss/train', loss) self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean()) return loss def",
"targets = batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) * 2 - 1).mean()) scores = self.model(inputs) self.val_auroc(",
"self.val_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) def forward(self, x): z =",
"focusing on purely \"clean\" inputs inputs.add_(torch.randn_like(inputs) * self.noise_eps) if self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp if",
"images and unseen examples inputs, targets = batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) * 2 -",
"self.hparams.input_clamp))) # Obtain samples samples = self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device) # Predict energy score",
"super().__init__() self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict())) # metrics self.val_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc",
"for all images all_inputs = torch.cat([inputs, samples], dim=0) inputs_out, samples_out = self.model(all_inputs).chunk(2, dim=0)",
"th.Optional[int] = None): inputs, targets = batch if self.noise_eps: # add minimal noise",
"all_inputs = torch.cat([inputs, samples], dim=0) inputs_out, samples_out = self.model(all_inputs).chunk(2, dim=0) # Calculate losses",
"pl import torch import typing as th import torchmetrics from .. import utils",
"0. if self.regularizer_alpha: reg_loss = (inputs_out ** 2 + samples_out ** 2).mean() loss",
"loss += cdiv_loss self.log(f'loss/train', loss) self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean()) return loss def validation_step(self,",
"optimizer_idx: th.Optional[int] = None): inputs, targets = batch if self.noise_eps: # add minimal",
"all images all_inputs = torch.cat([inputs, samples], dim=0) inputs_out, samples_out = self.model(all_inputs).chunk(2, dim=0) #",
"from .. import utils as ebad_utils class AnoTrainer(pl.LightningModule): def __init__( self, model_cls: th.Union[str,",
"forward(self, x): z = self.model(x) return z def training_step(self, batch, batch_idx: th.Optional[int] =",
"inputs_out, samples_out = self.model(all_inputs).chunk(2, dim=0) # Calculate losses loss = 0. if self.regularizer_alpha:",
"= batch if self.noise_eps: # add minimal noise to the original inputs to",
"None, optimizer_idx: th.Optional[int] = None): # calculate the contrastive divergence between purely random",
"self.val_auroc( preds=-scores, # auroc expects predictions to have higher values for the positive",
"import torch import typing as th import torchmetrics from .. import utils as",
"torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) def forward(self, x): z = self.model(x) return",
"# Obtain samples samples = self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device) # Predict energy score for",
"self.model(all_inputs).chunk(2, dim=0) # Calculate losses loss = 0. if self.regularizer_alpha: reg_loss = (inputs_out",
"return loss def validation_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None):",
"import utils as ebad_utils class AnoTrainer(pl.LightningModule): def __init__( self, model_cls: th.Union[str, torch.nn.Module], input_shape:",
".. import utils as ebad_utils class AnoTrainer(pl.LightningModule): def __init__( self, model_cls: th.Union[str, torch.nn.Module],",
"self.regularizer_alpha: reg_loss = (inputs_out ** 2 + samples_out ** 2).mean() loss += self.regularizer_alpha",
"+= cdiv_loss self.log(f'loss/train', loss) self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean()) return loss def validation_step(self, batch,",
"(-1., 1.), model_params: th.Optional[dict] = None, **kwargs, ): super().__init__() self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or",
"tuple]] = (-1., 1.), model_params: th.Optional[dict] = None, **kwargs, ): super().__init__() self.model =",
"- 1).mean()) scores = self.model(inputs) self.val_auroc( preds=-scores, # auroc expects predictions to have",
"from focusing on purely \"clean\" inputs inputs.add_(torch.randn_like(inputs) * self.noise_eps) if self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp",
"if self.noise_eps: # add minimal noise to the original inputs to prevent the",
"input_clamp: th.Optional[th.Union[float, tuple]] = (-1., 1.), model_params: th.Optional[dict] = None, **kwargs, ): super().__init__()",
"z def training_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): inputs,",
"loss def validation_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): #",
"and unseen examples inputs, targets = batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) * 2 - 1).mean())",
"reg_loss) cdiv_loss = samples_out.mean() - samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss += cdiv_loss self.log(f'loss/train', loss)",
"2 + samples_out ** 2).mean() loss += self.regularizer_alpha * reg_loss self.log(f'loss/regularization/train', reg_loss) cdiv_loss",
"or dict())) # metrics self.val_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) def",
"None): inputs, targets = batch if self.noise_eps: # add minimal noise to the",
"targets = batch if self.noise_eps: # add minimal noise to the original inputs",
"the contrastive divergence between purely random images and unseen examples inputs, targets =",
"self, model_cls: th.Union[str, torch.nn.Module], input_shape: th.Union[th.Tuple[int], th.List[int]], input_clamp: th.Optional[th.Union[float, tuple]] = (-1., 1.),",
"model_cls: th.Union[str, torch.nn.Module], input_shape: th.Union[th.Tuple[int], th.List[int]], input_clamp: th.Optional[th.Union[float, tuple]] = (-1., 1.), model_params:",
"self.log(f'metrics/samples/train', samples_out.mean()) return loss def validation_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int]",
"z = self.model(x) return z def training_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx:",
"th.Optional[dict] = None, **kwargs, ): super().__init__() self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict())) # metrics",
"reg_loss self.log(f'loss/regularization/train', reg_loss) cdiv_loss = samples_out.mean() - samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss += cdiv_loss",
"loss) self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean()) return loss def validation_step(self, batch, batch_idx: th.Optional[int] =",
"utils as ebad_utils class AnoTrainer(pl.LightningModule): def __init__( self, model_cls: th.Union[str, torch.nn.Module], input_shape: th.Union[th.Tuple[int],",
"= torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) def forward(self, x): z = self.model(x)",
"model_params: th.Optional[dict] = None, **kwargs, ): super().__init__() self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict())) #",
"to the original inputs to prevent the model from focusing on purely \"clean\"",
"energy score for all images all_inputs = torch.cat([inputs, samples], dim=0) inputs_out, samples_out =",
"1.), model_params: th.Optional[dict] = None, **kwargs, ): super().__init__() self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict()))",
"self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict())) # metrics self.val_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc =",
"inputs, targets = batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) * 2 - 1).mean()) scores = self.model(inputs)",
"inputs.clamp_( *(self.hparams.input_clamp if isinstance(self.hparams.input_clamp, tuple) else ( -self.hparams.input_clamp, self.hparams.input_clamp))) # Obtain samples samples",
"th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): # calculate the contrastive divergence between",
"= self.model(x) return z def training_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int]",
"def validation_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): # calculate",
"samples samples = self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device) # Predict energy score for all images",
"def training_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): inputs, targets",
"= 0. if self.regularizer_alpha: reg_loss = (inputs_out ** 2 + samples_out ** 2).mean()",
"= (-1., 1.), model_params: th.Optional[dict] = None, **kwargs, ): super().__init__() self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params",
"(inputs_out ** 2 + samples_out ** 2).mean() loss += self.regularizer_alpha * reg_loss self.log(f'loss/regularization/train',",
"import typing as th import torchmetrics from .. import utils as ebad_utils class",
"batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) * 2 - 1).mean()) scores = self.model(inputs) self.val_auroc( preds=-scores, #",
"pytorch_lightning as pl import torch import typing as th import torchmetrics from ..",
"samples_out = self.model(all_inputs).chunk(2, dim=0) # Calculate losses loss = 0. if self.regularizer_alpha: reg_loss",
"original inputs to prevent the model from focusing on purely \"clean\" inputs inputs.add_(torch.randn_like(inputs)",
"prevent the model from focusing on purely \"clean\" inputs inputs.add_(torch.randn_like(inputs) * self.noise_eps) if",
"AnoTrainer(pl.LightningModule): def __init__( self, model_cls: th.Union[str, torch.nn.Module], input_shape: th.Union[th.Tuple[int], th.List[int]], input_clamp: th.Optional[th.Union[float, tuple]]",
"** 2).mean() loss += self.regularizer_alpha * reg_loss self.log(f'loss/regularization/train', reg_loss) cdiv_loss = samples_out.mean() -",
"-self.hparams.input_clamp, self.hparams.input_clamp))) # Obtain samples samples = self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device) # Predict energy",
"samples_out ** 2).mean() loss += self.regularizer_alpha * reg_loss self.log(f'loss/regularization/train', reg_loss) cdiv_loss = samples_out.mean()",
"= None, **kwargs, ): super().__init__() self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict())) # metrics self.val_auroc",
"loss += self.regularizer_alpha * reg_loss self.log(f'loss/regularization/train', reg_loss) cdiv_loss = samples_out.mean() - samples_out.mean() self.log(f'loss/contrastive_divergence/train',",
"samples_out.mean() - samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss += cdiv_loss self.log(f'loss/train', loss) self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train',",
"self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss += cdiv_loss self.log(f'loss/train', loss) self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean()) return loss",
"* 2 - 1).mean()) scores = self.model(inputs) self.val_auroc( preds=-scores, # auroc expects predictions",
"inputs to prevent the model from focusing on purely \"clean\" inputs inputs.add_(torch.randn_like(inputs) *",
"\"clean\" inputs inputs.add_(torch.randn_like(inputs) * self.noise_eps) if self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp if isinstance(self.hparams.input_clamp, tuple) else",
"- samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss += cdiv_loss self.log(f'loss/train', loss) self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean())",
"batch if self.noise_eps: # add minimal noise to the original inputs to prevent",
"import torchmetrics from .. import utils as ebad_utils class AnoTrainer(pl.LightningModule): def __init__( self,",
"return z def training_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None):",
"inputs.add_(torch.randn_like(inputs) * self.noise_eps) if self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp if isinstance(self.hparams.input_clamp, tuple) else ( -self.hparams.input_clamp,",
"self.model(x) return z def training_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] =",
"the original inputs to prevent the model from focusing on purely \"clean\" inputs",
"model from focusing on purely \"clean\" inputs inputs.add_(torch.randn_like(inputs) * self.noise_eps) if self.hparams.input_clamp: inputs.clamp_(",
"* self.noise_eps) if self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp if isinstance(self.hparams.input_clamp, tuple) else ( -self.hparams.input_clamp, self.hparams.input_clamp)))",
"inputs inputs.add_(torch.randn_like(inputs) * self.noise_eps) if self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp if isinstance(self.hparams.input_clamp, tuple) else (",
"dim=0) inputs_out, samples_out = self.model(all_inputs).chunk(2, dim=0) # Calculate losses loss = 0. if",
"auroc expects predictions to have higher values for the positive class targets=targets )",
"as th import torchmetrics from .. import utils as ebad_utils class AnoTrainer(pl.LightningModule): def",
"calculate the contrastive divergence between purely random images and unseen examples inputs, targets",
"): super().__init__() self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict())) # metrics self.val_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1)",
"losses loss = 0. if self.regularizer_alpha: reg_loss = (inputs_out ** 2 + samples_out",
"= self.model(all_inputs).chunk(2, dim=0) # Calculate losses loss = 0. if self.regularizer_alpha: reg_loss =",
"metrics self.val_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) def forward(self, x): z",
"to prevent the model from focusing on purely \"clean\" inputs inputs.add_(torch.randn_like(inputs) * self.noise_eps)",
"self.regularizer_alpha * reg_loss self.log(f'loss/regularization/train', reg_loss) cdiv_loss = samples_out.mean() - samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss",
"self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device) # Predict energy score for all images all_inputs = torch.cat([inputs,",
"samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss += cdiv_loss self.log(f'loss/train', loss) self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean()) return",
"predictions to have higher values for the positive class targets=targets ) self.log('metrics/auroc/val', self.val_auroc,",
"if self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp if isinstance(self.hparams.input_clamp, tuple) else ( -self.hparams.input_clamp, self.hparams.input_clamp))) # Obtain",
"** 2 + samples_out ** 2).mean() loss += self.regularizer_alpha * reg_loss self.log(f'loss/regularization/train', reg_loss)",
"cdiv_loss self.log(f'loss/train', loss) self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean()) return loss def validation_step(self, batch, batch_idx:",
"divergence between purely random images and unseen examples inputs, targets = batch self.log(f'metrics/random/val',",
"minimal noise to the original inputs to prevent the model from focusing on",
"isinstance(self.hparams.input_clamp, tuple) else ( -self.hparams.input_clamp, self.hparams.input_clamp))) # Obtain samples samples = self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True,",
"**kwargs, ): super().__init__() self.model = ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict())) # metrics self.val_auroc = torchmetrics.AUROC(num_classes=2,",
"+ samples_out ** 2).mean() loss += self.regularizer_alpha * reg_loss self.log(f'loss/regularization/train', reg_loss) cdiv_loss =",
"th.Union[str, torch.nn.Module], input_shape: th.Union[th.Tuple[int], th.List[int]], input_clamp: th.Optional[th.Union[float, tuple]] = (-1., 1.), model_params: th.Optional[dict]",
"add minimal noise to the original inputs to prevent the model from focusing",
"loss = 0. if self.regularizer_alpha: reg_loss = (inputs_out ** 2 + samples_out **",
"self.log(f'loss/regularization/train', reg_loss) cdiv_loss = samples_out.mean() - samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss += cdiv_loss self.log(f'loss/train',",
"torch.cat([inputs, samples], dim=0) inputs_out, samples_out = self.model(all_inputs).chunk(2, dim=0) # Calculate losses loss =",
"= None, optimizer_idx: th.Optional[int] = None): inputs, targets = batch if self.noise_eps: #",
"= self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device) # Predict energy score for all images all_inputs =",
"training_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): inputs, targets =",
"torch import typing as th import torchmetrics from .. import utils as ebad_utils",
"noise to the original inputs to prevent the model from focusing on purely",
"if isinstance(self.hparams.input_clamp, tuple) else ( -self.hparams.input_clamp, self.hparams.input_clamp))) # Obtain samples samples = self.sampler.sample(sample_size=inputs.shape[0],",
"2).mean() loss += self.regularizer_alpha * reg_loss self.log(f'loss/regularization/train', reg_loss) cdiv_loss = samples_out.mean() - samples_out.mean()",
"examples inputs, targets = batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) * 2 - 1).mean()) scores =",
"# auroc expects predictions to have higher values for the positive class targets=targets",
"have higher values for the positive class targets=targets ) self.log('metrics/auroc/val', self.val_auroc, on_step=True, on_epoch=True)",
"else ( -self.hparams.input_clamp, self.hparams.input_clamp))) # Obtain samples samples = self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device) #",
"unseen examples inputs, targets = batch self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) * 2 - 1).mean()) scores",
"batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): # calculate the contrastive divergence",
"= None, optimizer_idx: th.Optional[int] = None): # calculate the contrastive divergence between purely",
"Obtain samples samples = self.sampler.sample(sample_size=inputs.shape[0], update_buffer=True, device=inputs.device) # Predict energy score for all",
"self.log(f'metrics/random/val', self.model(torch.rand_like(inputs) * 2 - 1).mean()) scores = self.model(inputs) self.val_auroc( preds=-scores, # auroc",
"self.log(f'loss/train', loss) self.log(f'metrics/inputs/train', inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean()) return loss def validation_step(self, batch, batch_idx: th.Optional[int]",
"batch, batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): # calculate the contrastive",
"None, optimizer_idx: th.Optional[int] = None): inputs, targets = batch if self.noise_eps: # add",
"cdiv_loss = samples_out.mean() - samples_out.mean() self.log(f'loss/contrastive_divergence/train', cdiv_loss) loss += cdiv_loss self.log(f'loss/train', loss) self.log(f'metrics/inputs/train',",
"update_buffer=True, device=inputs.device) # Predict energy score for all images all_inputs = torch.cat([inputs, samples],",
"def __init__( self, model_cls: th.Union[str, torch.nn.Module], input_shape: th.Union[th.Tuple[int], th.List[int]], input_clamp: th.Optional[th.Union[float, tuple]] =",
"th.Optional[int] = None): # calculate the contrastive divergence between purely random images and",
"= ebad_utils.get_value(self.hparams.model_cls)(**(self.hparams.model_params or dict())) # metrics self.val_auroc = torchmetrics.AUROC(num_classes=2, pos_label=1) self.test_auroc = torchmetrics.AUROC(num_classes=2,",
"Predict energy score for all images all_inputs = torch.cat([inputs, samples], dim=0) inputs_out, samples_out",
"on purely \"clean\" inputs inputs.add_(torch.randn_like(inputs) * self.noise_eps) if self.hparams.input_clamp: inputs.clamp_( *(self.hparams.input_clamp if isinstance(self.hparams.input_clamp,",
"Calculate losses loss = 0. if self.regularizer_alpha: reg_loss = (inputs_out ** 2 +",
"preds=-scores, # auroc expects predictions to have higher values for the positive class",
"inputs_out.mean()) self.log(f'metrics/samples/train', samples_out.mean()) return loss def validation_step(self, batch, batch_idx: th.Optional[int] = None, optimizer_idx:",
"th.Optional[th.Union[float, tuple]] = (-1., 1.), model_params: th.Optional[dict] = None, **kwargs, ): super().__init__() self.model",
"th.Union[th.Tuple[int], th.List[int]], input_clamp: th.Optional[th.Union[float, tuple]] = (-1., 1.), model_params: th.Optional[dict] = None, **kwargs,",
"to have higher values for the positive class targets=targets ) self.log('metrics/auroc/val', self.val_auroc, on_step=True,",
"batch_idx: th.Optional[int] = None, optimizer_idx: th.Optional[int] = None): inputs, targets = batch if"
] |
[
"= requests.get( self.url, headers=headers, timeout=self.timeout, stream=True, proxies=self.proxies ) url_data = r.content.decode('utf-8', 'ignore') soup",
"'Mozilla/5.0 (Windows NT 6.3; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113",
"return \"\" return self.soup.body.getText() def get_title(self): \"\"\" Get the title from a HTML",
"def __init__(self, url, timeout=3, parser='html5lib', proxies=None): self.url = url self.soup = None self.success",
"\\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/57.0.2987.133 Safari/537.36', ] parsed = urlparse.urlparse(self.url) headers",
"time import requests import logging import urllib.parse as urlparse from bs4 import BeautifulSoup",
"NT 6.1; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0",
"10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/57.0.2987.133 Safari/537.36', ] parsed",
"return self.soup.body.getText() def get_title(self): \"\"\" Get the title from a HTML content \"\"\"",
"x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0;",
"import time import requests import logging import urllib.parse as urlparse from bs4 import",
"= url self.soup = None self.success = None self.message = None self.timeout =",
"Facebook, Inc. and its affiliates. All Rights Reserved \"\"\" Given an URL in",
"urlparse from bs4 import BeautifulSoup class URLContentFetcher(object): def __init__(self, url, timeout=3, parser='html5lib', proxies=None):",
"hash(parsed.netloc + parsed.path) % len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\", } try: start_time =",
"of a HTML content \"\"\" if self.soup is None: self.read_and_soup() if not self.success",
"\\ Chrome/57.0.2987.133 Safari/537.36', ] parsed = urlparse.urlparse(self.url) headers = { \"User-Agent\": user_agent_list[ hash(parsed.netloc",
"None self.timeout = timeout self.parser = parser self.proxies = proxies self.running_time = 0",
"(KHTML, like Gecko) \\ Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) \\",
"= soup self.success = True except Exception as e: logging.error(repr(e) + \", url:",
"Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\",
"self.success = True except Exception as e: logging.error(repr(e) + \", url: {0}\".format(self.url)) self.success",
"content from a url \"\"\" user_agent_list = [ 'Mozilla/5.0 (Macintosh; Intel Mac OS",
"user_agent_list[ hash(parsed.netloc + parsed.path) % len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\", } try: start_time",
"timeout=self.timeout, stream=True, proxies=self.proxies ) url_data = r.content.decode('utf-8', 'ignore') soup = BeautifulSoup(url_data, self.parser) end_time",
"start_time = time.time() r = requests.get( self.url, headers=headers, timeout=self.timeout, stream=True, proxies=self.proxies ) url_data",
"as e: logging.error(repr(e) + \", url: {0}\".format(self.url)) self.success = False self.message = \"Modified",
"Rights Reserved \"\"\" Given an URL in string, make a request, fetch its",
"'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/57.0.2987.133",
"HTML content \"\"\" if self.soup is None: self.read_and_soup() if not self.success or self.soup.body",
"'Mozilla/5.0 (Windows NT 6.1; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.90",
"affiliates. All Rights Reserved \"\"\" Given an URL in string, make a request,",
"6.3; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows",
"import urllib.parse as urlparse from bs4 import BeautifulSoup class URLContentFetcher(object): def __init__(self, url,",
"parse using BeautifulSoup. \"\"\" import time import requests import logging import urllib.parse as",
"\\ Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\",
"Chrome/57.0.2987.133 Safari/537.36', ] parsed = urlparse.urlparse(self.url) headers = { \"User-Agent\": user_agent_list[ hash(parsed.netloc +",
"None self.message = None self.timeout = timeout self.parser = parser self.proxies = proxies",
"self.running_time = end_time - start_time self.soup = soup self.success = True except Exception",
"url: {0}\".format(self.url)) self.success = False self.message = \"Modified URL error: \" + str(e)",
"content, and parse using BeautifulSoup. \"\"\" import time import requests import logging import",
"\"\"\" if self.soup is None: self.read_and_soup() if not self.success or self.soup.body is None:",
"is None: self.read_and_soup() if not self.success or self.soup.body is None: return \"\" return",
"and parse using BeautifulSoup. \"\"\" import time import requests import logging import urllib.parse",
"fetch its content, and parse using BeautifulSoup. \"\"\" import time import requests import",
"requests import logging import urllib.parse as urlparse from bs4 import BeautifulSoup class URLContentFetcher(object):",
"Safari/537.36', ] parsed = urlparse.urlparse(self.url) headers = { \"User-Agent\": user_agent_list[ hash(parsed.netloc + parsed.path)",
"self.read_and_soup() if not self.success or self.soup.body is None: return \"\" return self.soup.body.getText() def",
"Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML,",
"(X11; Linux x86_64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows",
"(Windows NT 6.1; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.90 Safari/537.36',",
"like Gecko) \\ Chrome/57.0.2987.133 Safari/537.36', ] parsed = urlparse.urlparse(self.url) headers = { \"User-Agent\":",
"request, fetch its content, and parse using BeautifulSoup. \"\"\" import time import requests",
"time.time() self.running_time = end_time - start_time self.soup = soup self.success = True except",
"as urlparse from bs4 import BeautifulSoup class URLContentFetcher(object): def __init__(self, url, timeout=3, parser='html5lib',",
"if not self.success or self.soup.body is None: return \"\" return self.soup.body.getText() def get_title(self):",
"self.url = url self.soup = None self.success = None self.message = None self.timeout",
"= None self.timeout = timeout self.parser = parser self.proxies = proxies self.running_time =",
"All Rights Reserved \"\"\" Given an URL in string, make a request, fetch",
"a request, fetch its content, and parse using BeautifulSoup. \"\"\" import time import",
"X 10_9_3) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0 (Windows NT",
"NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/57.0.2987.133 Safari/537.36', ]",
"Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT",
"= True except Exception as e: logging.error(repr(e) + \", url: {0}\".format(self.url)) self.success =",
"\\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64;",
"like Gecko) \\ Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) \\ AppleWebKit/537.36 (KHTML, like",
"len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\", } try: start_time = time.time() r = requests.get(",
"\"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\", } try: start_time = time.time() r = requests.get( self.url,",
"= time.time() self.running_time = end_time - start_time self.soup = soup self.success = True",
"= end_time - start_time self.soup = soup self.success = True except Exception as",
"] parsed = urlparse.urlparse(self.url) headers = { \"User-Agent\": user_agent_list[ hash(parsed.netloc + parsed.path) %",
"Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko)",
"get_title(self): \"\"\" Get the title from a HTML content \"\"\" if self.soup is",
"AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"timeout=3, parser='html5lib', proxies=None): self.url = url self.soup = None self.success = None self.message",
"#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved",
"self.timeout = timeout self.parser = parser self.proxies = proxies self.running_time = 0 def",
"Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/57.0.2987.133 Safari/537.36', ] parsed =",
"\"gzip\", } try: start_time = time.time() r = requests.get( self.url, headers=headers, timeout=self.timeout, stream=True,",
"start_time self.soup = soup self.success = True except Exception as e: logging.error(repr(e) +",
"self.success or self.soup.body is None: return \"\" return self.soup.body.getText() def get_title(self): \"\"\" Get",
"Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\",
") url_data = r.content.decode('utf-8', 'ignore') soup = BeautifulSoup(url_data, self.parser) end_time = time.time() self.running_time",
"like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36",
"[ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \\ AppleWebKit/537.36 (KHTML, like Gecko)",
"x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64)",
"content \"\"\" if self.soup is None: self.read_and_soup() if not self.success or self.soup.title is",
"(Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36',",
"\"\"\" import time import requests import logging import urllib.parse as urlparse from bs4",
"= None self.success = None self.message = None self.timeout = timeout self.parser =",
"not self.success or self.soup.body is None: return \"\" return self.soup.body.getText() def get_title(self): \"\"\"",
"= parser self.proxies = proxies self.running_time = 0 def read_and_soup(self): \"\"\" Fetch content",
"timeout self.parser = parser self.proxies = proxies self.running_time = 0 def read_and_soup(self): \"\"\"",
"= timeout self.parser = parser self.proxies = proxies self.running_time = 0 def read_and_soup(self):",
"BeautifulSoup class URLContentFetcher(object): def __init__(self, url, timeout=3, parser='html5lib', proxies=None): self.url = url self.soup",
"NT 6.3; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0",
"headers=headers, timeout=self.timeout, stream=True, proxies=self.proxies ) url_data = r.content.decode('utf-8', 'ignore') soup = BeautifulSoup(url_data, self.parser)",
"HTML content \"\"\" if self.soup is None: self.read_and_soup() if not self.success or self.soup.title",
"10_9_3) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0;",
"\"\"\" user_agent_list = [ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \\ AppleWebKit/537.36",
"like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) \\ AppleWebKit/537.36",
"= urlparse.urlparse(self.url) headers = { \"User-Agent\": user_agent_list[ hash(parsed.netloc + parsed.path) % len(user_agent_list)], \"X-Requested-With\":",
"str(e) def get_body(self): \"\"\" Get the body of a HTML content \"\"\" if",
"url self.soup = None self.success = None self.message = None self.timeout = timeout",
"e: logging.error(repr(e) + \", url: {0}\".format(self.url)) self.success = False self.message = \"Modified URL",
"self.soup.body.getText() def get_title(self): \"\"\" Get the title from a HTML content \"\"\" if",
"\\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like",
"\"\"\" if self.soup is None: self.read_and_soup() if not self.success or self.soup.title is None:",
"= BeautifulSoup(url_data, self.parser) end_time = time.time() self.running_time = end_time - start_time self.soup =",
"r = requests.get( self.url, headers=headers, timeout=self.timeout, stream=True, proxies=self.proxies ) url_data = r.content.decode('utf-8', 'ignore')",
"'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113",
"0 def read_and_soup(self): \"\"\" Fetch content from a url \"\"\" user_agent_list = [",
"10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows",
"self.soup = soup self.success = True except Exception as e: logging.error(repr(e) + \",",
"soup self.success = True except Exception as e: logging.error(repr(e) + \", url: {0}\".format(self.url))",
"(Macintosh; Intel Mac OS X 10_9_3) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/35.0.1916.47",
"x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/57.0.2987.133 Safari/537.36', ] parsed = urlparse.urlparse(self.url)",
"\"Accept-Encoding\": \"gzip\", } try: start_time = time.time() r = requests.get( self.url, headers=headers, timeout=self.timeout,",
"'ignore') soup = BeautifulSoup(url_data, self.parser) end_time = time.time() self.running_time = end_time - start_time",
"Gecko) \\ Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML,",
"self.soup = None self.success = None self.message = None self.timeout = timeout self.parser",
"Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) \\ AppleWebKit/537.36 (KHTML,",
"(KHTML, like Gecko) \\ Chrome/57.0.2987.133 Safari/537.36', ] parsed = urlparse.urlparse(self.url) headers = {",
"from a HTML content \"\"\" if self.soup is None: self.read_and_soup() if not self.success",
"URL in string, make a request, fetch its content, and parse using BeautifulSoup.",
"its content, and parse using BeautifulSoup. \"\"\" import time import requests import logging",
"and its affiliates. All Rights Reserved \"\"\" Given an URL in string, make",
"body of a HTML content \"\"\" if self.soup is None: self.read_and_soup() if not",
"parser self.proxies = proxies self.running_time = 0 def read_and_soup(self): \"\"\" Fetch content from",
"'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\",
"% len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\", } try: start_time = time.time() r =",
"self.parser) end_time = time.time() self.running_time = end_time - start_time self.soup = soup self.success",
"get_body(self): \"\"\" Get the body of a HTML content \"\"\" if self.soup is",
"import BeautifulSoup class URLContentFetcher(object): def __init__(self, url, timeout=3, parser='html5lib', proxies=None): self.url = url",
"class URLContentFetcher(object): def __init__(self, url, timeout=3, parser='html5lib', proxies=None): self.url = url self.soup =",
"+ \", url: {0}\".format(self.url)) self.success = False self.message = \"Modified URL error: \"",
"stream=True, proxies=self.proxies ) url_data = r.content.decode('utf-8', 'ignore') soup = BeautifulSoup(url_data, self.parser) end_time =",
"Gecko) \\ Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) \\ AppleWebKit/537.36 (KHTML,",
"AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"None: return \"\" return self.soup.body.getText() def get_title(self): \"\"\" Get the title from a",
"proxies self.running_time = 0 def read_and_soup(self): \"\"\" Fetch content from a url \"\"\"",
"error: \" + str(e) def get_body(self): \"\"\" Get the body of a HTML",
"= False self.message = \"Modified URL error: \" + str(e) def get_body(self): \"\"\"",
"(Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/57.0.2987.133 Safari/537.36',",
"def get_body(self): \"\"\" Get the body of a HTML content \"\"\" if self.soup",
"self.success = None self.message = None self.timeout = timeout self.parser = parser self.proxies",
"make a request, fetch its content, and parse using BeautifulSoup. \"\"\" import time",
"a url \"\"\" user_agent_list = [ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3)",
"logging import urllib.parse as urlparse from bs4 import BeautifulSoup class URLContentFetcher(object): def __init__(self,",
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved \"\"\" Given",
"- start_time self.soup = soup self.success = True except Exception as e: logging.error(repr(e)",
"logging.error(repr(e) + \", url: {0}\".format(self.url)) self.success = False self.message = \"Modified URL error:",
"\"\"\" Get the body of a HTML content \"\"\" if self.soup is None:",
"try: start_time = time.time() r = requests.get( self.url, headers=headers, timeout=self.timeout, stream=True, proxies=self.proxies )",
"\"\" return self.soup.body.getText() def get_title(self): \"\"\" Get the title from a HTML content",
"self.success = False self.message = \"Modified URL error: \" + str(e) def get_body(self):",
"Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/44.0.2403.157",
"Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko)",
"self.proxies = proxies self.running_time = 0 def read_and_soup(self): \"\"\" Fetch content from a",
"\"Modified URL error: \" + str(e) def get_body(self): \"\"\" Get the body of",
"\\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like",
"if self.soup is None: self.read_and_soup() if not self.success or self.soup.body is None: return",
"Mac OS X 10_9_3) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0",
"6.1; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11;",
"an URL in string, make a request, fetch its content, and parse using",
"(Windows NT 6.3; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36',",
"Exception as e: logging.error(repr(e) + \", url: {0}\".format(self.url)) self.success = False self.message =",
"url, timeout=3, parser='html5lib', proxies=None): self.url = url self.soup = None self.success = None",
"URL error: \" + str(e) def get_body(self): \"\"\" Get the body of a",
"url_data = r.content.decode('utf-8', 'ignore') soup = BeautifulSoup(url_data, self.parser) end_time = time.time() self.running_time =",
"from bs4 import BeautifulSoup class URLContentFetcher(object): def __init__(self, url, timeout=3, parser='html5lib', proxies=None): self.url",
"end_time = time.time() self.running_time = end_time - start_time self.soup = soup self.success =",
"self.soup is None: self.read_and_soup() if not self.success or self.soup.body is None: return \"\"",
"is None: self.read_and_soup() if not self.success or self.soup.title is None: return \"\" return",
"URLContentFetcher(object): def __init__(self, url, timeout=3, parser='html5lib', proxies=None): self.url = url self.soup = None",
"a HTML content \"\"\" if self.soup is None: self.read_and_soup() if not self.success or",
"{0}\".format(self.url)) self.success = False self.message = \"Modified URL error: \" + str(e) def",
"def read_and_soup(self): \"\"\" Fetch content from a url \"\"\" user_agent_list = [ 'Mozilla/5.0",
"Inc. and its affiliates. All Rights Reserved \"\"\" Given an URL in string,",
"Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11; Linux",
"proxies=self.proxies ) url_data = r.content.decode('utf-8', 'ignore') soup = BeautifulSoup(url_data, self.parser) end_time = time.time()",
"= proxies self.running_time = 0 def read_and_soup(self): \"\"\" Fetch content from a url",
"(KHTML, like Gecko) \\ Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\",
"r.content.decode('utf-8', 'ignore') soup = BeautifulSoup(url_data, self.parser) end_time = time.time() self.running_time = end_time -",
"if self.soup is None: self.read_and_soup() if not self.success or self.soup.title is None: return",
"AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64)",
"\\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64;",
"Given an URL in string, make a request, fetch its content, and parse",
"headers = { \"User-Agent\": user_agent_list[ hash(parsed.netloc + parsed.path) % len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\":",
"__init__(self, url, timeout=3, parser='html5lib', proxies=None): self.url = url self.soup = None self.success =",
"self.message = \"Modified URL error: \" + str(e) def get_body(self): \"\"\" Get the",
"AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)",
"parsed.path) % len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\", } try: start_time = time.time() r",
"url \"\"\" user_agent_list = [ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \\",
"like Gecko) \\ Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) \\ AppleWebKit/537.36",
"} try: start_time = time.time() r = requests.get( self.url, headers=headers, timeout=self.timeout, stream=True, proxies=self.proxies",
"= { \"User-Agent\": user_agent_list[ hash(parsed.netloc + parsed.path) % len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\",",
"= \"Modified URL error: \" + str(e) def get_body(self): \"\"\" Get the body",
"python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved \"\"\"",
"proxies=None): self.url = url self.soup = None self.success = None self.message = None",
"x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1;",
"\\ Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like",
"Gecko) \\ Chrome/57.0.2987.133 Safari/537.36', ] parsed = urlparse.urlparse(self.url) headers = { \"User-Agent\": user_agent_list[",
"\"\"\" Get the title from a HTML content \"\"\" if self.soup is None:",
"\\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64;",
"bs4 import BeautifulSoup class URLContentFetcher(object): def __init__(self, url, timeout=3, parser='html5lib', proxies=None): self.url =",
"(c) Facebook, Inc. and its affiliates. All Rights Reserved \"\"\" Given an URL",
"BeautifulSoup. \"\"\" import time import requests import logging import urllib.parse as urlparse from",
"import requests import logging import urllib.parse as urlparse from bs4 import BeautifulSoup class",
"Fetch content from a url \"\"\" user_agent_list = [ 'Mozilla/5.0 (Macintosh; Intel Mac",
"OS X 10_9_3) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0 (Windows",
"(KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\",
"\\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) \\",
"\"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\", } try: start_time = time.time() r = requests.get( self.url, headers=headers,",
"soup = BeautifulSoup(url_data, self.parser) end_time = time.time() self.running_time = end_time - start_time self.soup",
"read_and_soup(self): \"\"\" Fetch content from a url \"\"\" user_agent_list = [ 'Mozilla/5.0 (Macintosh;",
"\"User-Agent\": user_agent_list[ hash(parsed.netloc + parsed.path) % len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\", } try:",
"\"\"\" Fetch content from a url \"\"\" user_agent_list = [ 'Mozilla/5.0 (Macintosh; Intel",
"user_agent_list = [ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \\ AppleWebKit/537.36 (KHTML,",
"Intel Mac OS X 10_9_3) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/35.0.1916.47 Safari/537.36',",
"+ parsed.path) % len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\", } try: start_time = time.time()",
"+ str(e) def get_body(self): \"\"\" Get the body of a HTML content \"\"\"",
"Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko)",
"None: self.read_and_soup() if not self.success or self.soup.title is None: return \"\" return self.soup.title",
"True except Exception as e: logging.error(repr(e) + \", url: {0}\".format(self.url)) self.success = False",
"Get the title from a HTML content \"\"\" if self.soup is None: self.read_and_soup()",
"self.message = None self.timeout = timeout self.parser = parser self.proxies = proxies self.running_time",
"self.soup.body is None: return \"\" return self.soup.body.getText() def get_title(self): \"\"\" Get the title",
"title from a HTML content \"\"\" if self.soup is None: self.read_and_soup() if not",
"AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/57.0.2987.133 Safari/537.36', ] parsed = urlparse.urlparse(self.url) headers =",
"= r.content.decode('utf-8', 'ignore') soup = BeautifulSoup(url_data, self.parser) end_time = time.time() self.running_time = end_time",
"\", url: {0}\".format(self.url)) self.success = False self.message = \"Modified URL error: \" +",
"{ \"User-Agent\": user_agent_list[ hash(parsed.netloc + parsed.path) % len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\", \"Accept-Encoding\": \"gzip\", }",
"False self.message = \"Modified URL error: \" + str(e) def get_body(self): \"\"\" Get",
"the body of a HTML content \"\"\" if self.soup is None: self.read_and_soup() if",
"Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko)",
"its affiliates. All Rights Reserved \"\"\" Given an URL in string, make a",
"urllib.parse as urlparse from bs4 import BeautifulSoup class URLContentFetcher(object): def __init__(self, url, timeout=3,",
"self.url, headers=headers, timeout=self.timeout, stream=True, proxies=self.proxies ) url_data = r.content.decode('utf-8', 'ignore') soup = BeautifulSoup(url_data,",
"None: self.read_and_soup() if not self.success or self.soup.body is None: return \"\" return self.soup.body.getText()",
"\" + str(e) def get_body(self): \"\"\" Get the body of a HTML content",
"AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) \\ AppleWebKit/537.36",
"self.parser = parser self.proxies = proxies self.running_time = 0 def read_and_soup(self): \"\"\" Fetch",
"self.running_time = 0 def read_and_soup(self): \"\"\" Fetch content from a url \"\"\" user_agent_list",
"(KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) \\",
"= None self.message = None self.timeout = timeout self.parser = parser self.proxies =",
"Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/44.0.2403.157 Safari/537.36',",
"or self.soup.body is None: return \"\" return self.soup.body.getText() def get_title(self): \"\"\" Get the",
"= [ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \\ AppleWebKit/537.36 (KHTML, like",
"is None: return \"\" return self.soup.body.getText() def get_title(self): \"\"\" Get the title from",
"in string, make a request, fetch its content, and parse using BeautifulSoup. \"\"\"",
"\\ Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like",
"end_time - start_time self.soup = soup self.success = True except Exception as e:",
"Gecko) \\ Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) \\ AppleWebKit/537.36 (KHTML, like Gecko)",
"import logging import urllib.parse as urlparse from bs4 import BeautifulSoup class URLContentFetcher(object): def",
"except Exception as e: logging.error(repr(e) + \", url: {0}\".format(self.url)) self.success = False self.message",
"Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\",
"None self.success = None self.message = None self.timeout = timeout self.parser = parser",
"x86_64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3;",
"Linux x86_64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0 (Windows NT",
"self.soup is None: self.read_and_soup() if not self.success or self.soup.title is None: return \"\"",
"Reserved \"\"\" Given an URL in string, make a request, fetch its content,",
"def get_title(self): \"\"\" Get the title from a HTML content \"\"\" if self.soup",
"\"\"\" Given an URL in string, make a request, fetch its content, and",
"Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved \"\"\" Given an",
"from a url \"\"\" user_agent_list = [ 'Mozilla/5.0 (Macintosh; Intel Mac OS X",
"urlparse.urlparse(self.url) headers = { \"User-Agent\": user_agent_list[ hash(parsed.netloc + parsed.path) % len(user_agent_list)], \"X-Requested-With\": \"XMLHttpRequest\",",
"requests.get( self.url, headers=headers, timeout=self.timeout, stream=True, proxies=self.proxies ) url_data = r.content.decode('utf-8', 'ignore') soup =",
"like Gecko) \\ Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36",
"(KHTML, like Gecko) \\ Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) \\ AppleWebKit/537.36 (KHTML,",
"content \"\"\" if self.soup is None: self.read_and_soup() if not self.success or self.soup.body is",
"NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/60.0.3112.113 Safari/537.36', 'Mozilla/5.0",
"string, make a request, fetch its content, and parse using BeautifulSoup. \"\"\" import",
"parser='html5lib', proxies=None): self.url = url self.soup = None self.success = None self.message =",
"BeautifulSoup(url_data, self.parser) end_time = time.time() self.running_time = end_time - start_time self.soup = soup",
"\\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/35.0.1916.47 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64;",
"'Mozilla/5.0 (X11; Linux x86_64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/44.0.2403.157 Safari/537.36', 'Mozilla/5.0",
"time.time() r = requests.get( self.url, headers=headers, timeout=self.timeout, stream=True, proxies=self.proxies ) url_data = r.content.decode('utf-8',",
"using BeautifulSoup. \"\"\" import time import requests import logging import urllib.parse as urlparse",
"parsed = urlparse.urlparse(self.url) headers = { \"User-Agent\": user_agent_list[ hash(parsed.netloc + parsed.path) % len(user_agent_list)],",
"= time.time() r = requests.get( self.url, headers=headers, timeout=self.timeout, stream=True, proxies=self.proxies ) url_data =",
"the title from a HTML content \"\"\" if self.soup is None: self.read_and_soup() if",
"Get the body of a HTML content \"\"\" if self.soup is None: self.read_and_soup()",
"= 0 def read_and_soup(self): \"\"\" Fetch content from a url \"\"\" user_agent_list ="
] |
[
"setup(name='ttv', version='0.0.1', description='A command line tool and a python library for test, train,",
"library for test, train, validation set splitting', author='<NAME>', author_email='<EMAIL>', url='https://github.com/coopie/ttv', download_url='https://github.com/coopie/ttv/archive/master.zip', license='MIT', install_requires=['docopt',",
"tool and a python library for test, train, validation set splitting', author='<NAME>', author_email='<EMAIL>',",
"import setup setup(name='ttv', version='0.0.1', description='A command line tool and a python library for",
"setup setup(name='ttv', version='0.0.1', description='A command line tool and a python library for test,",
"version='0.0.1', description='A command line tool and a python library for test, train, validation",
"a python library for test, train, validation set splitting', author='<NAME>', author_email='<EMAIL>', url='https://github.com/coopie/ttv', download_url='https://github.com/coopie/ttv/archive/master.zip',",
"<filename>setup.py from setuptools import setup setup(name='ttv', version='0.0.1', description='A command line tool and a",
"setuptools import setup setup(name='ttv', version='0.0.1', description='A command line tool and a python library",
"for test, train, validation set splitting', author='<NAME>', author_email='<EMAIL>', url='https://github.com/coopie/ttv', download_url='https://github.com/coopie/ttv/archive/master.zip', license='MIT', install_requires=['docopt', 'pyyaml'],",
"line tool and a python library for test, train, validation set splitting', author='<NAME>',",
"python library for test, train, validation set splitting', author='<NAME>', author_email='<EMAIL>', url='https://github.com/coopie/ttv', download_url='https://github.com/coopie/ttv/archive/master.zip', license='MIT',",
"test, train, validation set splitting', author='<NAME>', author_email='<EMAIL>', url='https://github.com/coopie/ttv', download_url='https://github.com/coopie/ttv/archive/master.zip', license='MIT', install_requires=['docopt', 'pyyaml'], py_modules=['ttv']",
"description='A command line tool and a python library for test, train, validation set",
"train, validation set splitting', author='<NAME>', author_email='<EMAIL>', url='https://github.com/coopie/ttv', download_url='https://github.com/coopie/ttv/archive/master.zip', license='MIT', install_requires=['docopt', 'pyyaml'], py_modules=['ttv'] )",
"command line tool and a python library for test, train, validation set splitting',",
"from setuptools import setup setup(name='ttv', version='0.0.1', description='A command line tool and a python",
"and a python library for test, train, validation set splitting', author='<NAME>', author_email='<EMAIL>', url='https://github.com/coopie/ttv',"
] |
[
"neither general or expected n_exp_ = 0 n_gen_ = 0 n_err_ = 0",
"that are more general than the expected one (therefore they are still true)",
"#note that the general values are all the returned values that are more",
"compute the number of expected/general/erroneous values returned by the approach #note that the",
"they are still true) #note that the erronous values are values that are",
"truth_, ancestors_): #function that compute the number of expected/general/erroneous values returned by the",
"the general values are all the returned values that are more general than",
"#note that the erronous values are values that are neither general or expected",
"0 for d in sol_dict_: returned_value = sol_dict_[d] expected = truth_[d] if returned_value",
"are all the returned values that are more general than the expected one",
"number of expected/general/erroneous values returned by the approach #note that the general values",
"expected: n_exp_ += 1 else: if returned_value in ancestors_[expected]: n_gen_ += 1 else:",
"approach #note that the general values are all the returned values that are",
"d in sol_dict_: returned_value = sol_dict_[d] expected = truth_[d] if returned_value == expected:",
"values are values that are neither general or expected n_exp_ = 0 n_gen_",
"(therefore they are still true) #note that the erronous values are values that",
"returned by the approach #note that the general values are all the returned",
"returned_value in ancestors_[expected]: n_gen_ += 1 else: n_err_ += 1 return n_exp_, n_gen_,",
"expected/general/erroneous values returned by the approach #note that the general values are all",
"if returned_value == expected: n_exp_ += 1 else: if returned_value in ancestors_[expected]: n_gen_",
"values that are neither general or expected n_exp_ = 0 n_gen_ = 0",
"expected = truth_[d] if returned_value == expected: n_exp_ += 1 else: if returned_value",
"still true) #note that the erronous values are values that are neither general",
"that the erronous values are values that are neither general or expected n_exp_",
"values returned by the approach #note that the general values are all the",
"general than the expected one (therefore they are still true) #note that the",
"are neither general or expected n_exp_ = 0 n_gen_ = 0 n_err_ =",
"sol_dict_[d] expected = truth_[d] if returned_value == expected: n_exp_ += 1 else: if",
"general values are all the returned values that are more general than the",
"ancestors_): #function that compute the number of expected/general/erroneous values returned by the approach",
"returned_value = sol_dict_[d] expected = truth_[d] if returned_value == expected: n_exp_ += 1",
"general or expected n_exp_ = 0 n_gen_ = 0 n_err_ = 0 for",
"values that are more general than the expected one (therefore they are still",
"in ancestors_[expected]: n_gen_ += 1 else: n_err_ += 1 return n_exp_, n_gen_, n_err_",
"by the approach #note that the general values are all the returned values",
"that are neither general or expected n_exp_ = 0 n_gen_ = 0 n_err_",
"the erronous values are values that are neither general or expected n_exp_ =",
"+= 1 else: if returned_value in ancestors_[expected]: n_gen_ += 1 else: n_err_ +=",
"compute_precision_with_general(sol_dict_, truth_, ancestors_): #function that compute the number of expected/general/erroneous values returned by",
"that compute the number of expected/general/erroneous values returned by the approach #note that",
"one (therefore they are still true) #note that the erronous values are values",
"that the general values are all the returned values that are more general",
"the number of expected/general/erroneous values returned by the approach #note that the general",
"more general than the expected one (therefore they are still true) #note that",
"1 else: if returned_value in ancestors_[expected]: n_gen_ += 1 else: n_err_ += 1",
"= 0 n_err_ = 0 for d in sol_dict_: returned_value = sol_dict_[d] expected",
"== expected: n_exp_ += 1 else: if returned_value in ancestors_[expected]: n_gen_ += 1",
"true) #note that the erronous values are values that are neither general or",
"= 0 n_gen_ = 0 n_err_ = 0 for d in sol_dict_: returned_value",
"are still true) #note that the erronous values are values that are neither",
"values are all the returned values that are more general than the expected",
"returned values that are more general than the expected one (therefore they are",
"in sol_dict_: returned_value = sol_dict_[d] expected = truth_[d] if returned_value == expected: n_exp_",
"or expected n_exp_ = 0 n_gen_ = 0 n_err_ = 0 for d",
"expected one (therefore they are still true) #note that the erronous values are",
"the returned values that are more general than the expected one (therefore they",
"= 0 for d in sol_dict_: returned_value = sol_dict_[d] expected = truth_[d] if",
"#function that compute the number of expected/general/erroneous values returned by the approach #note",
"0 n_err_ = 0 for d in sol_dict_: returned_value = sol_dict_[d] expected =",
"all the returned values that are more general than the expected one (therefore",
"than the expected one (therefore they are still true) #note that the erronous",
"n_err_ = 0 for d in sol_dict_: returned_value = sol_dict_[d] expected = truth_[d]",
"for d in sol_dict_: returned_value = sol_dict_[d] expected = truth_[d] if returned_value ==",
"= sol_dict_[d] expected = truth_[d] if returned_value == expected: n_exp_ += 1 else:",
"def compute_precision_with_general(sol_dict_, truth_, ancestors_): #function that compute the number of expected/general/erroneous values returned",
"n_gen_ = 0 n_err_ = 0 for d in sol_dict_: returned_value = sol_dict_[d]",
"sol_dict_: returned_value = sol_dict_[d] expected = truth_[d] if returned_value == expected: n_exp_ +=",
"the approach #note that the general values are all the returned values that",
"returned_value == expected: n_exp_ += 1 else: if returned_value in ancestors_[expected]: n_gen_ +=",
"0 n_gen_ = 0 n_err_ = 0 for d in sol_dict_: returned_value =",
"= truth_[d] if returned_value == expected: n_exp_ += 1 else: if returned_value in",
"expected n_exp_ = 0 n_gen_ = 0 n_err_ = 0 for d in",
"of expected/general/erroneous values returned by the approach #note that the general values are",
"if returned_value in ancestors_[expected]: n_gen_ += 1 else: n_err_ += 1 return n_exp_,",
"erronous values are values that are neither general or expected n_exp_ = 0",
"else: if returned_value in ancestors_[expected]: n_gen_ += 1 else: n_err_ += 1 return",
"n_exp_ = 0 n_gen_ = 0 n_err_ = 0 for d in sol_dict_:",
"are values that are neither general or expected n_exp_ = 0 n_gen_ =",
"truth_[d] if returned_value == expected: n_exp_ += 1 else: if returned_value in ancestors_[expected]:",
"are more general than the expected one (therefore they are still true) #note",
"the expected one (therefore they are still true) #note that the erronous values",
"<reponame>lgi2p/TDSelection<filename>TDO/utils_tdo/utils_evaluation.py def compute_precision_with_general(sol_dict_, truth_, ancestors_): #function that compute the number of expected/general/erroneous values",
"n_exp_ += 1 else: if returned_value in ancestors_[expected]: n_gen_ += 1 else: n_err_"
] |
[
"and the following disclaimer in the documentation # and/or other materials provided with",
"# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #",
"EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES",
"AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL",
"OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE",
"without # modification, are permitted provided that the following conditions are met: #",
"in binary form must reproduce the above copyright notice, # this list of",
"All rights reserved. # # Redistribution and use in source and binary forms,",
"software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY",
"# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE",
"IRIS-HEP # All rights reserved. # # Redistribution and use in source and",
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT",
"PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS",
"# this software without specific prior written permission. # # THIS SOFTWARE IS",
"uproot print(sys.path) file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events = file[\"Events\"] arrays = events.arrays([\"nElectron\", \"Electron_pt\",",
"physics_objects[\"Electron\"] = { \"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets,",
"OF THE POSSIBILITY OF SUCH DAMAGE. import os import awkward import pyarrow as",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #",
"\"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[",
"pa_table = awkward.toarrow(t) batches = pa_table.to_batches() batch = batches[0] sink = pa.BufferOutputStream() writer",
"2019, IRIS-HEP # All rights reserved. # # Redistribution and use in source",
"awkward.toarrow(t) batches = pa_table.to_batches() batch = batches[0] sink = pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(sink,",
"code must retain the above copyright notice, this # list of conditions and",
"and the following disclaimer. # # * Redistributions in binary form must reproduce",
"= {} offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] = { \"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content),",
"offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] = { \"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets,",
"# # * Redistributions in binary form must reproduce the above copyright notice,",
"# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING,",
"LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR",
"* Redistributions in binary form must reproduce the above copyright notice, # this",
"this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED",
"# * Neither the name of the copyright holder nor the names of",
"CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT",
"file[\"Events\"] arrays = events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\", \"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects",
"with or without # modification, are permitted provided that the following conditions are",
"events = file[\"Events\"] arrays = events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\", \"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"],",
"awkward import pyarrow as pa import sys import uproot print(sys.path) file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\",",
"endorse or promote products derived from # this software without specific prior written",
"# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF",
"= uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events = file[\"Events\"] arrays = events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\", \"Electron_phi\", \"Electron_mass\",",
"LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND",
"and/or other materials provided with the distribution. # # * Neither the name",
"Copyright (c) 2019, IRIS-HEP # All rights reserved. # # Redistribution and use",
"# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,",
"Redistributions of source code must retain the above copyright notice, this # list",
"USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY",
"NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
"WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF",
"= awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] = { \"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content),",
"print(sys.path) file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events = file[\"Events\"] arrays = events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\",",
"rights reserved. # # Redistribution and use in source and binary forms, with",
"\"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content),",
"conditions and the following disclaimer. # # * Redistributions in binary form must",
"electrons = physics_objects[\"Electron\"] t = awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t) pa_table = awkward.toarrow(t) batches =",
"permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS",
"the following conditions are met: # # * Redistributions of source code must",
"copyright holder nor the names of its # contributors may be used to",
"\"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content) } electrons = physics_objects[\"Electron\"] t = awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t)",
"OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE,",
"THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF",
"that the following conditions are met: # # * Redistributions of source code",
"reproduce the above copyright notice, # this list of conditions and the following",
"batches = pa_table.to_batches() batch = batches[0] sink = pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(sink, batch.schema)",
"HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,",
"the documentation # and/or other materials provided with the distribution. # # *",
"GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)",
"TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE",
"= events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\", \"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects = {}",
"IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY",
"THE POSSIBILITY OF SUCH DAMAGE. import os import awkward import pyarrow as pa",
"awkward.toparquet(\"tmp.parquet\", t) pa_table = awkward.toarrow(t) batches = pa_table.to_batches() batch = batches[0] sink =",
"or without # modification, are permitted provided that the following conditions are met:",
"CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY",
"without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE",
"\"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets,",
"copyright notice, # this list of conditions and the following disclaimer in the",
"BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL #",
"THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
"(c) 2019, IRIS-HEP # All rights reserved. # # Redistribution and use in",
"notice, this # list of conditions and the following disclaimer. # # *",
"INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,",
"documentation # and/or other materials provided with the distribution. # # * Neither",
"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS",
"this list of conditions and the following disclaimer in the documentation # and/or",
"of conditions and the following disclaimer in the documentation # and/or other materials",
"are permitted provided that the following conditions are met: # # * Redistributions",
"\"Electron_pt\", \"Electron_eta\", \"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects = {} offsets =",
"list of conditions and the following disclaimer. # # * Redistributions in binary",
"OF SUCH DAMAGE. import os import awkward import pyarrow as pa import sys",
"DAMAGE. import os import awkward import pyarrow as pa import sys import uproot",
"awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t) pa_table = awkward.toarrow(t) batches = pa_table.to_batches() batch = batches[0] sink",
"list of conditions and the following disclaimer in the documentation # and/or other",
"arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content),",
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF",
"name of the copyright holder nor the names of its # contributors may",
"NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF",
"and use in source and binary forms, with or without # modification, are",
"entrystop=1000) physics_objects = {} offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] = { \"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content),",
"FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
"batches[0] sink = pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch) writer.close() buf = sink.getvalue()",
"the distribution. # # * Neither the name of the copyright holder nor",
"# this list of conditions and the following disclaimer in the documentation #",
"provided that the following conditions are met: # # * Redistributions of source",
"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED",
"# Copyright (c) 2019, IRIS-HEP # All rights reserved. # # Redistribution and",
"IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import awkward import",
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import",
"ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import awkward import pyarrow",
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE #",
"# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE",
"arrays[ b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content) } electrons = physics_objects[\"Electron\"]",
"of its # contributors may be used to endorse or promote products derived",
"its # contributors may be used to endorse or promote products derived from",
"= file[\"Events\"] arrays = events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\", \"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000)",
"OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER",
"WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING",
"OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE",
"uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events = file[\"Events\"] arrays = events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\", \"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\",",
"as pa import sys import uproot print(sys.path) file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events =",
"OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS",
"IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR",
"contributors may be used to endorse or promote products derived from # this",
"= pa.ipc.open_stream(buf) batches2 = [b for b in reader] arrays = awkward.fromarrow(batches2[0]) print(arrays)",
"NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY",
"POSSIBILITY OF SUCH DAMAGE. import os import awkward import pyarrow as pa import",
"Redistribution and use in source and binary forms, with or without # modification,",
"source and binary forms, with or without # modification, are permitted provided that",
"BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR",
"the name of the copyright holder nor the names of its # contributors",
"FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE",
"writer.close() buf = sink.getvalue() reader = pa.ipc.open_stream(buf) batches2 = [b for b in",
"of conditions and the following disclaimer. # # * Redistributions in binary form",
"CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, #",
"batch.schema) writer.write_batch(batch) writer.close() buf = sink.getvalue() reader = pa.ipc.open_stream(buf) batches2 = [b for",
"above copyright notice, this # list of conditions and the following disclaimer. #",
"the following disclaimer. # # * Redistributions in binary form must reproduce the",
"pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch) writer.close() buf = sink.getvalue() reader = pa.ipc.open_stream(buf)",
"derived from # this software without specific prior written permission. # # THIS",
"HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT",
"t) pa_table = awkward.toarrow(t) batches = pa_table.to_batches() batch = batches[0] sink = pa.BufferOutputStream()",
"ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING",
"# # * Neither the name of the copyright holder nor the names",
"awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] = { \"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\":",
"# contributors may be used to endorse or promote products derived from #",
"permitted provided that the following conditions are met: # # * Redistributions of",
"= pa_table.to_batches() batch = batches[0] sink = pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch)",
"HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,",
"other materials provided with the distribution. # # * Neither the name of",
"COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES,",
"= physics_objects[\"Electron\"] t = awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t) pa_table = awkward.toarrow(t) batches = pa_table.to_batches()",
"SUCH DAMAGE. import os import awkward import pyarrow as pa import sys import",
"import awkward import pyarrow as pa import sys import uproot print(sys.path) file =",
"= { \"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content),",
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO",
"{} offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] = { \"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\":",
"forms, with or without # modification, are permitted provided that the following conditions",
"# # * Redistributions of source code must retain the above copyright notice,",
"with the distribution. # # * Neither the name of the copyright holder",
"above copyright notice, # this list of conditions and the following disclaimer in",
"physics_objects[\"Electron\"] t = awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t) pa_table = awkward.toarrow(t) batches = pa_table.to_batches() batch",
"in source and binary forms, with or without # modification, are permitted provided",
"arrays[ b\"Electron_pfRelIso03_all\"].content) } electrons = physics_objects[\"Electron\"] t = awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t) pa_table =",
"IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF",
"b\"Electron_pfRelIso03_all\"].content) } electrons = physics_objects[\"Electron\"] t = awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t) pa_table = awkward.toarrow(t)",
"the following disclaimer in the documentation # and/or other materials provided with the",
"PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY,",
"# # Redistribution and use in source and binary forms, with or without",
"arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content) }",
"pa import sys import uproot print(sys.path) file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events = file[\"Events\"]",
"the above copyright notice, this # list of conditions and the following disclaimer.",
"TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE",
"used to endorse or promote products derived from # this software without specific",
"\"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects = {} offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] = {",
"promote products derived from # this software without specific prior written permission. #",
"prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS",
"writer.write_batch(batch) writer.close() buf = sink.getvalue() reader = pa.ipc.open_stream(buf) batches2 = [b for b",
"awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content) } electrons =",
"pa_table.to_batches() batch = batches[0] sink = pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch) writer.close()",
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #",
"= pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch) writer.close() buf = sink.getvalue() reader = pa.ipc.open_stream(buf) batches2 =",
"events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\", \"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects = {} offsets",
"\"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content) } electrons",
"use in source and binary forms, with or without # modification, are permitted",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED.",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" #",
"= pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch) writer.close() buf = sink.getvalue() reader =",
"<reponame>ssl-hep/ServiceX_datastream # Copyright (c) 2019, IRIS-HEP # All rights reserved. # # Redistribution",
"OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR",
"must reproduce the above copyright notice, # this list of conditions and the",
"batch = batches[0] sink = pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch) writer.close() buf",
"this # list of conditions and the following disclaimer. # # * Redistributions",
"# All rights reserved. # # Redistribution and use in source and binary",
"following conditions are met: # # * Redistributions of source code must retain",
"# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #",
"sys import uproot print(sys.path) file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events = file[\"Events\"] arrays =",
"disclaimer in the documentation # and/or other materials provided with the distribution. #",
"to endorse or promote products derived from # this software without specific prior",
"os import awkward import pyarrow as pa import sys import uproot print(sys.path) file",
"OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER",
"INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO,",
"\"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects = {} offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] = { \"pt\": awkward.JaggedArray.fromoffsets(offsets,",
"EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT,",
"LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)",
"\"Electron_eta\", \"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects = {} offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron'])",
"distribution. # # * Neither the name of the copyright holder nor the",
"in the documentation # and/or other materials provided with the distribution. # #",
"TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR",
"awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content) } electrons = physics_objects[\"Electron\"] t = awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t) pa_table",
"AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT",
"# and/or other materials provided with the distribution. # # * Neither the",
"products derived from # this software without specific prior written permission. # #",
"SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS",
"the above copyright notice, # this list of conditions and the following disclaimer",
"from # this software without specific prior written permission. # # THIS SOFTWARE",
"awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\":",
"be used to endorse or promote products derived from # this software without",
"OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF",
"IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,",
"* Neither the name of the copyright holder nor the names of its",
"OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON",
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY",
"BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN",
"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT",
"USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH",
"materials provided with the distribution. # # * Neither the name of the",
"EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE",
"arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets,",
"PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR",
"= sink.getvalue() reader = pa.ipc.open_stream(buf) batches2 = [b for b in reader] arrays",
"pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch) writer.close() buf = sink.getvalue() reader = pa.ipc.open_stream(buf) batches2 = [b",
"IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN",
"and binary forms, with or without # modification, are permitted provided that the",
"conditions and the following disclaimer in the documentation # and/or other materials provided",
"sink.getvalue() reader = pa.ipc.open_stream(buf) batches2 = [b for b in reader] arrays =",
"names of its # contributors may be used to endorse or promote products",
"buf = sink.getvalue() reader = pa.ipc.open_stream(buf) batches2 = [b for b in reader]",
"copyright notice, this # list of conditions and the following disclaimer. # #",
"SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND",
"disclaimer. # # * Redistributions in binary form must reproduce the above copyright",
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED",
"WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND",
"provided with the distribution. # # * Neither the name of the copyright",
"A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER",
"modification, are permitted provided that the following conditions are met: # # *",
"import sys import uproot print(sys.path) file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events = file[\"Events\"] arrays",
"must retain the above copyright notice, this # list of conditions and the",
"are met: # # * Redistributions of source code must retain the above",
"CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR",
"arrays = events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\", \"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects =",
"OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS",
"awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[",
"ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED",
"= awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t) pa_table = awkward.toarrow(t) batches = pa_table.to_batches() batch = batches[0]",
"the copyright holder nor the names of its # contributors may be used",
"ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN",
"physics_objects = {} offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] = { \"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets,",
"PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS;",
"COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,",
"SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT,",
"# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #",
"= awkward.toarrow(t) batches = pa_table.to_batches() batch = batches[0] sink = pa.BufferOutputStream() writer =",
"reader = pa.ipc.open_stream(buf) batches2 = [b for b in reader] arrays = awkward.fromarrow(batches2[0])",
"\"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content) } electrons = physics_objects[\"Electron\"] t =",
"met: # # * Redistributions of source code must retain the above copyright",
"{ \"pt\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pt\"].content), \"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\":",
"\"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events = file[\"Events\"] arrays = events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\", \"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\",",
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY",
"file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events = file[\"Events\"] arrays = events.arrays([\"nElectron\", \"Electron_pt\", \"Electron_eta\", \"Electron_phi\",",
"import os import awkward import pyarrow as pa import sys import uproot print(sys.path)",
"import uproot print(sys.path) file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events = file[\"Events\"] arrays = events.arrays([\"nElectron\",",
"import pyarrow as pa import sys import uproot print(sys.path) file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\"))",
"Redistributions in binary form must reproduce the above copyright notice, # this list",
"ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE",
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT",
"CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL",
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA,",
"LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT",
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import",
"of the copyright holder nor the names of its # contributors may be",
"# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"",
"of source code must retain the above copyright notice, this # list of",
"ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT",
"writer = pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch) writer.close() buf = sink.getvalue() reader = pa.ipc.open_stream(buf) batches2",
"\"eta\":awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_eta\"].content), \"phi\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content), \"pdgId\":",
"notice, # this list of conditions and the following disclaimer in the documentation",
"THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE",
"MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT",
"sink = pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch) writer.close() buf = sink.getvalue() reader",
"THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR IMPLIED",
"the names of its # contributors may be used to endorse or promote",
"\"Electron_phi\", \"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects = {} offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"]",
"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES;",
"} electrons = physics_objects[\"Electron\"] t = awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t) pa_table = awkward.toarrow(t) batches",
"reserved. # # Redistribution and use in source and binary forms, with or",
"\"AS IS\" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED",
"# Redistribution and use in source and binary forms, with or without #",
"INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS",
"pyarrow as pa import sys import uproot print(sys.path) file = uproot.open(os.path.join(\"/Users\",\"bengal1\",\"dev\",\"IRIS-HEP\",\"data\", \"DYJetsToLL_M-50_HT-100to200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root\")) events",
"nor the names of its # contributors may be used to endorse or",
"source code must retain the above copyright notice, this # list of conditions",
"conditions are met: # # * Redistributions of source code must retain the",
"retain the above copyright notice, this # list of conditions and the following",
"holder nor the names of its # contributors may be used to endorse",
"BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" # AND ANY EXPRESS OR",
"BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF",
"awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content)",
"arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content) } electrons = physics_objects[\"Electron\"] t = awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\",",
"STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY",
"EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import awkward",
"binary forms, with or without # modification, are permitted provided that the following",
"\"Electron_mass\", \"Electron_cutBased\", \"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects = {} offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] =",
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os",
"may be used to endorse or promote products derived from # this software",
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE",
"\"Electron_pdgId\", \"Electron_pfRelIso03_all\"], entrystop=1000) physics_objects = {} offsets = awkward.JaggedArray.counts2offsets(arrays[b'nElectron']) physics_objects[\"Electron\"] = { \"pt\":",
"# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS",
"= batches[0] sink = pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(sink, batch.schema) writer.write_batch(batch) writer.close() buf =",
"binary form must reproduce the above copyright notice, # this list of conditions",
"following disclaimer in the documentation # and/or other materials provided with the distribution.",
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE,",
"form must reproduce the above copyright notice, # this list of conditions and",
"LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES",
"# list of conditions and the following disclaimer. # # * Redistributions in",
"Neither the name of the copyright holder nor the names of its #",
"PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS",
"arrays[b\"Electron_phi\"].content), \"mass\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_mass\"].content), \"cutBased\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets,",
"OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY",
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN",
"t = awkward.Table(electrons) awkward.toparquet(\"tmp.parquet\", t) pa_table = awkward.toarrow(t) batches = pa_table.to_batches() batch =",
"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED",
"OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR",
"OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR",
"# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
"# * Redistributions of source code must retain the above copyright notice, this",
"# modification, are permitted provided that the following conditions are met: # #",
"written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND",
"# * Redistributions in binary form must reproduce the above copyright notice, #",
"AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR",
"b\"Electron_cutBased\"].content), \"pdgId\": awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content) } electrons = physics_objects[\"Electron\"] t",
"awkward.JaggedArray.fromoffsets(offsets, arrays[b\"Electron_pdgId\"].content), \"pfRelIso03_all\": awkward.JaggedArray.fromoffsets(offsets, arrays[ b\"Electron_pfRelIso03_all\"].content) } electrons = physics_objects[\"Electron\"] t = awkward.Table(electrons)",
"OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF",
"or promote products derived from # this software without specific prior written permission.",
"specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT",
"* Redistributions of source code must retain the above copyright notice, this #",
"following disclaimer. # # * Redistributions in binary form must reproduce the above"
] |
[
"with this environment.\\n\" b\"Removing context1 ... Done !\\n\" b\"Removing buildx ... Done !\\n\"",
"= ( b\"Warning: No docker-compose file is provided with this environment.\\n\" b\"Removing context1",
"\"flag\": \"flag_value\", \"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\": \"testpkrbuilder\", } def test_docker_driver_values(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard()",
"/ \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"context1\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir /",
"\"pkr\" pkr_folder = \"docker_driver\" kard_env = \"dev\" kard_driver = \"buildx_compose\" kard_extra = {",
"self.src_path self.generate_kard(env=\"contexts\") self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\" self.assertTrue((out_dir / \"buildx\"",
"\"context1\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"buildx\" / \"file1.dockerfile\").exists()) self.assertTrue((out_dir / \"context1\"",
"is provided with this environment.\\n\" b\"Removing context1 ... Done !\\n\" b\"Removing buildx ...",
"p in path.iterdir(): if p.is_dir(): yield from walk(p) continue yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected)",
"\"{} image build -s container1 -c\".format(self.PKR) prc = self._run_cmd(cmd) stdout = prc.stdout.read() stderr",
"stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout, expected, stdout) self.assertRegex( stderr.decode(\"utf-8\"), r\"docker buildx build --progress plain --builder",
"\"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"context1\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"buildx\"",
"pkrTestCase class TestBuildxDriver(pkrTestCase): PKR = \"pkr\" pkr_folder = \"docker_driver\" kard_env = \"dev\" kard_driver",
"python < 3.6\\n\" ) return expected = ( b\"Warning: No docker-compose file is",
"flag_value\" in stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout, expected, stdout) self.assertRegex( stderr.decode(\"utf-8\"), r\"docker buildx build --progress",
"stderr = prc.stderr.read() # Python 3.6 if sys.version_info < (3, 7): self.assertEqual(stdout, b\"\",",
"supported for python < 3.6\\n\" ) return expected = ( b\"Warning: No docker-compose",
"expected, stdout) self.assertRegex( stderr.decode(\"utf-8\"), r\"docker buildx build --progress plain --builder testpkrbuilder --load \"",
"(Exception) buildx is not supported for python < 3.6\\n\" ) return expected =",
"b\"Removing context1 ... Done !\\n\" b\"Removing buildx ... Done !\\n\" b\"Start buildx builder",
"yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected) def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard(env=\"contexts\") self.make_kard() out_dir =",
"kard_env = \"dev\" kard_driver = \"buildx_compose\" kard_extra = { \"tag\": \"123\", \"flag\": \"flag_value\",",
"/ \"file2\", out_dir / \"buildx\" / \"file1.dockerfile\", out_dir / \"meta.yml\", ] ) def",
"out_dir = self.pkr_path / \"kard\" / \"test\" self.assertTrue((out_dir / \"buildx\" / \"folder2_dst\" /",
"< 3.6\\n\" ) return expected = ( b\"Warning: No docker-compose file is provided",
"\"file1.dockerfile\").exists()) self.assertTrue((out_dir / \"context1\" / \"file1.dockerfile\").exists()) cmd = \"{} image build -s container1",
"kard_extra = { \"tag\": \"123\", \"flag\": \"flag_value\", \"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\": \"testpkrbuilder\", } def",
"\"copy\").exists()) self.assertTrue((out_dir / \"context1\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"buildx\" / \"file1.dockerfile\").exists())",
"stderr, b\"ERROR: (Exception) buildx is not supported for python < 3.6\\n\" ) return",
"/ \"buildx\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"context1\" / \"folder2_dst\" / \"copy\").exists())",
"(3, 7): self.assertEqual(stdout, b\"\", stdout) self.assertEqual( stderr, b\"ERROR: (Exception) buildx is not supported",
"self.assertRegex( stderr.decode(\"utf-8\"), r\"docker buildx build --progress plain --builder testpkrbuilder --load \" r\"--file /tmp/.*/file1.dockerfile",
"stdout) self.assertEqual( stderr, b\"ERROR: (Exception) buildx is not supported for python < 3.6\\n\"",
"b\"\", stdout) self.assertEqual( stderr, b\"ERROR: (Exception) buildx is not supported for python <",
"if p.is_dir(): yield from walk(p) continue yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected) def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"]",
"/ \"copy\").exists()) self.assertTrue((out_dir / \"context1\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"buildx\" /",
"/ \"buildx\" / \"file1\" / \"file2\", out_dir / \"buildx\" / \"file1.dockerfile\", out_dir /",
"/ \"test\" expected = sorted( [ out_dir / \"buildx\" / \"folder2_dst\" / \"copy\",",
"sys from .utils import pkrTestCase class TestBuildxDriver(pkrTestCase): PKR = \"pkr\" pkr_folder = \"docker_driver\"",
"/ \"context1\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"buildx\" / \"file1.dockerfile\").exists()) self.assertTrue((out_dir /",
"prc.stdout.read() stderr = prc.stderr.read() # Python 3.6 if sys.version_info < (3, 7): self.assertEqual(stdout,",
"\"buildx\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"context1\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir",
"3.6 if sys.version_info < (3, 7): self.assertEqual(stdout, b\"\", stdout) self.assertEqual( stderr, b\"ERROR: (Exception)",
"Done !\\n\" b\"Removing buildx ... Done !\\n\" b\"Start buildx builder testpkrbuilder\\n\" b\"Building docker",
"file is provided with this environment.\\n\" b\"Removing context1 ... Done !\\n\" b\"Removing buildx",
") def walk(path): for p in path.iterdir(): if p.is_dir(): yield from walk(p) continue",
"builder testpkrbuilder\\n\" b\"Building docker images...\\n\\n\" b\"Building container1:123 image...\\n\\n\" ) self.assertTrue(\"unknown instruction: flag_value\" in",
"def test_docker_driver_values(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard() self.make_kard() out_dir = self.pkr_path / \"kard\" /",
"sorted( [ out_dir / \"buildx\" / \"folder2_dst\" / \"copy\", out_dir / \"buildx\" /",
"self._run_cmd(cmd) stdout = prc.stdout.read() stderr = prc.stderr.read() # Python 3.6 if sys.version_info <",
"= sorted( [ out_dir / \"buildx\" / \"folder2_dst\" / \"copy\", out_dir / \"buildx\"",
"docker-compose file is provided with this environment.\\n\" b\"Removing context1 ... Done !\\n\" b\"Removing",
"kard_driver = \"buildx_compose\" kard_extra = { \"tag\": \"123\", \"flag\": \"flag_value\", \"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\":",
"b\"Building docker images...\\n\\n\" b\"Building container1:123 image...\\n\\n\" ) self.assertTrue(\"unknown instruction: flag_value\" in stderr.decode(\"utf-8\"), stderr)",
"self.assertTrue((out_dir / \"context1\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"buildx\" / \"file1.dockerfile\").exists()) self.assertTrue((out_dir",
"TestBuildxDriver(pkrTestCase): PKR = \"pkr\" pkr_folder = \"docker_driver\" kard_env = \"dev\" kard_driver = \"buildx_compose\"",
"/ \"file1.dockerfile\", out_dir / \"meta.yml\", ] ) def walk(path): for p in path.iterdir():",
"for p in path.iterdir(): if p.is_dir(): yield from walk(p) continue yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))),",
"\"dummy\", \"buildx.builder_name\": \"testpkrbuilder\", } def test_docker_driver_values(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard() self.make_kard() out_dir =",
"stdout = prc.stdout.read() stderr = prc.stderr.read() # Python 3.6 if sys.version_info < (3,",
"container1 -c\".format(self.PKR) prc = self._run_cmd(cmd) stdout = prc.stdout.read() stderr = prc.stderr.read() # Python",
"testpkrbuilder\\n\" b\"Building docker images...\\n\\n\" b\"Building container1:123 image...\\n\\n\" ) self.assertTrue(\"unknown instruction: flag_value\" in stderr.decode(\"utf-8\"),",
"= prc.stdout.read() stderr = prc.stderr.read() # Python 3.6 if sys.version_info < (3, 7):",
"out_dir / \"buildx\" / \"file1.dockerfile\", out_dir / \"meta.yml\", ] ) def walk(path): for",
"= self.pkr_path / \"kard\" / \"test\" self.assertTrue((out_dir / \"buildx\" / \"folder2_dst\" / \"copy\").exists())",
"/ \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"buildx\" / \"file1.dockerfile\").exists()) self.assertTrue((out_dir / \"context1\" /",
"return expected = ( b\"Warning: No docker-compose file is provided with this environment.\\n\"",
"test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard(env=\"contexts\") self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\"",
"from walk(p) continue yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected) def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard(env=\"contexts\")",
"from .utils import pkrTestCase class TestBuildxDriver(pkrTestCase): PKR = \"pkr\" pkr_folder = \"docker_driver\" kard_env",
"provided with this environment.\\n\" b\"Removing context1 ... Done !\\n\" b\"Removing buildx ... Done",
"} def test_docker_driver_values(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard() self.make_kard() out_dir = self.pkr_path / \"kard\"",
"b\"Start buildx builder testpkrbuilder\\n\" b\"Building docker images...\\n\\n\" b\"Building container1:123 image...\\n\\n\" ) self.assertTrue(\"unknown instruction:",
"p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected) def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard(env=\"contexts\") self.make_kard() out_dir = self.pkr_path",
"test_docker_driver_values(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard() self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\"",
"\"test\" self.assertTrue((out_dir / \"buildx\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"context1\" / \"folder2_dst\"",
"= \"docker_driver\" kard_env = \"dev\" kard_driver = \"buildx_compose\" kard_extra = { \"tag\": \"123\",",
"stderr.decode(\"utf-8\"), r\"docker buildx build --progress plain --builder testpkrbuilder --load \" r\"--file /tmp/.*/file1.dockerfile --cache-from",
"\"testpkrbuilder\", } def test_docker_driver_values(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard() self.make_kard() out_dir = self.pkr_path /",
"/ \"buildx\" / \"folder2_dst\" / \"copy\", out_dir / \"buildx\" / \"file1\" / \"file2\",",
"... Done !\\n\" b\"Removing buildx ... Done !\\n\" b\"Start buildx builder testpkrbuilder\\n\" b\"Building",
"build --progress plain --builder testpkrbuilder --load \" r\"--file /tmp/.*/file1.dockerfile --cache-from type=registry,ref=dummy/cache \" r\"--cache-to",
"\"buildx.builder_name\": \"testpkrbuilder\", } def test_docker_driver_values(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard() self.make_kard() out_dir = self.pkr_path",
"/ \"buildx\" / \"file1.dockerfile\").exists()) self.assertTrue((out_dir / \"context1\" / \"file1.dockerfile\").exists()) cmd = \"{} image",
"self.kard_extra[\"src_path\"] = self.src_path self.generate_kard() self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\" expected",
"in path.iterdir(): if p.is_dir(): yield from walk(p) continue yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected) def",
"= \"buildx_compose\" kard_extra = { \"tag\": \"123\", \"flag\": \"flag_value\", \"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\": \"testpkrbuilder\",",
"self.generate_kard(env=\"contexts\") self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\" self.assertTrue((out_dir / \"buildx\" /",
"/ \"buildx\" / \"file1.dockerfile\", out_dir / \"meta.yml\", ] ) def walk(path): for p",
"= \"dev\" kard_driver = \"buildx_compose\" kard_extra = { \"tag\": \"123\", \"flag\": \"flag_value\", \"buildx.cache_registry\":",
"= self.src_path self.generate_kard() self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\" expected =",
"\"123\", \"flag\": \"flag_value\", \"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\": \"testpkrbuilder\", } def test_docker_driver_values(self): self.kard_extra[\"src_path\"] = self.src_path",
"/ \"kard\" / \"test\" self.assertTrue((out_dir / \"buildx\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir /",
"in stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout, expected, stdout) self.assertRegex( stderr.decode(\"utf-8\"), r\"docker buildx build --progress plain",
"\"docker_driver\" kard_env = \"dev\" kard_driver = \"buildx_compose\" kard_extra = { \"tag\": \"123\", \"flag\":",
"b\"Warning: No docker-compose file is provided with this environment.\\n\" b\"Removing context1 ... Done",
"expected = sorted( [ out_dir / \"buildx\" / \"folder2_dst\" / \"copy\", out_dir /",
"--builder testpkrbuilder --load \" r\"--file /tmp/.*/file1.dockerfile --cache-from type=registry,ref=dummy/cache \" r\"--cache-to type=registry,mode=max,ref=dummy/cache --tag container1:123",
"out_dir = self.pkr_path / \"kard\" / \"test\" expected = sorted( [ out_dir /",
"3.6\\n\" ) return expected = ( b\"Warning: No docker-compose file is provided with",
"\"tag\": \"123\", \"flag\": \"flag_value\", \"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\": \"testpkrbuilder\", } def test_docker_driver_values(self): self.kard_extra[\"src_path\"] =",
"self.src_path self.generate_kard() self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\" expected = sorted(",
"not supported for python < 3.6\\n\" ) return expected = ( b\"Warning: No",
"if sys.version_info < (3, 7): self.assertEqual(stdout, b\"\", stdout) self.assertEqual( stderr, b\"ERROR: (Exception) buildx",
"!\\n\" b\"Removing buildx ... Done !\\n\" b\"Start buildx builder testpkrbuilder\\n\" b\"Building docker images...\\n\\n\"",
"... Done !\\n\" b\"Start buildx builder testpkrbuilder\\n\" b\"Building docker images...\\n\\n\" b\"Building container1:123 image...\\n\\n\"",
"plain --builder testpkrbuilder --load \" r\"--file /tmp/.*/file1.dockerfile --cache-from type=registry,ref=dummy/cache \" r\"--cache-to type=registry,mode=max,ref=dummy/cache --tag",
"def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard(env=\"contexts\") self.make_kard() out_dir = self.pkr_path / \"kard\" /",
"( b\"Warning: No docker-compose file is provided with this environment.\\n\" b\"Removing context1 ...",
"self.assertEqual(stdout, expected, stdout) self.assertRegex( stderr.decode(\"utf-8\"), r\"docker buildx build --progress plain --builder testpkrbuilder --load",
"out_dir / \"meta.yml\", ] ) def walk(path): for p in path.iterdir(): if p.is_dir():",
"] ) def walk(path): for p in path.iterdir(): if p.is_dir(): yield from walk(p)",
"/ \"file1.dockerfile\").exists()) cmd = \"{} image build -s container1 -c\".format(self.PKR) prc = self._run_cmd(cmd)",
"\"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\": \"testpkrbuilder\", } def test_docker_driver_values(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard() self.make_kard() out_dir",
"pkr_folder = \"docker_driver\" kard_env = \"dev\" kard_driver = \"buildx_compose\" kard_extra = { \"tag\":",
"walk(p) continue yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected) def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard(env=\"contexts\") self.make_kard()",
"\"buildx\" / \"folder2_dst\" / \"copy\", out_dir / \"buildx\" / \"file1\" / \"file2\", out_dir",
"No docker-compose file is provided with this environment.\\n\" b\"Removing context1 ... Done !\\n\"",
"\"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"buildx\" / \"file1.dockerfile\").exists()) self.assertTrue((out_dir / \"context1\" / \"file1.dockerfile\").exists())",
") self.assertTrue(\"unknown instruction: flag_value\" in stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout, expected, stdout) self.assertRegex( stderr.decode(\"utf-8\"), r\"docker",
"path.iterdir(): if p.is_dir(): yield from walk(p) continue yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected) def test_docker_multiple_contexts(self):",
"self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\" expected = sorted( [ out_dir",
"prc.stderr.read() # Python 3.6 if sys.version_info < (3, 7): self.assertEqual(stdout, b\"\", stdout) self.assertEqual(",
") return expected = ( b\"Warning: No docker-compose file is provided with this",
"/ \"kard\" / \"test\" expected = sorted( [ out_dir / \"buildx\" / \"folder2_dst\"",
"\"buildx\" / \"file1.dockerfile\", out_dir / \"meta.yml\", ] ) def walk(path): for p in",
"\"copy\").exists()) self.assertTrue((out_dir / \"buildx\" / \"file1.dockerfile\").exists()) self.assertTrue((out_dir / \"context1\" / \"file1.dockerfile\").exists()) cmd =",
"/ \"file1\" / \"file2\", out_dir / \"buildx\" / \"file1.dockerfile\", out_dir / \"meta.yml\", ]",
"\"copy\", out_dir / \"buildx\" / \"file1\" / \"file2\", out_dir / \"buildx\" / \"file1.dockerfile\",",
"walk(path): for p in path.iterdir(): if p.is_dir(): yield from walk(p) continue yield p.resolve()",
"= { \"tag\": \"123\", \"flag\": \"flag_value\", \"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\": \"testpkrbuilder\", } def test_docker_driver_values(self):",
"\"meta.yml\", ] ) def walk(path): for p in path.iterdir(): if p.is_dir(): yield from",
"self.assertTrue((out_dir / \"buildx\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"context1\" / \"folder2_dst\" /",
"self.kard_extra[\"src_path\"] = self.src_path self.generate_kard(env=\"contexts\") self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\" self.assertTrue((out_dir",
"\"file1.dockerfile\", out_dir / \"meta.yml\", ] ) def walk(path): for p in path.iterdir(): if",
"\"flag_value\", \"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\": \"testpkrbuilder\", } def test_docker_driver_values(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard() self.make_kard()",
"/ \"folder2_dst\" / \"copy\", out_dir / \"buildx\" / \"file1\" / \"file2\", out_dir /",
"\"dev\" kard_driver = \"buildx_compose\" kard_extra = { \"tag\": \"123\", \"flag\": \"flag_value\", \"buildx.cache_registry\": \"dummy\",",
"= self._run_cmd(cmd) stdout = prc.stdout.read() stderr = prc.stderr.read() # Python 3.6 if sys.version_info",
"out_dir / \"buildx\" / \"file1\" / \"file2\", out_dir / \"buildx\" / \"file1.dockerfile\", out_dir",
"sys.version_info < (3, 7): self.assertEqual(stdout, b\"\", stdout) self.assertEqual( stderr, b\"ERROR: (Exception) buildx is",
"= self.src_path self.generate_kard(env=\"contexts\") self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\" self.assertTrue((out_dir /",
"/ \"test\" self.assertTrue((out_dir / \"buildx\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"context1\" /",
"= \"{} image build -s container1 -c\".format(self.PKR) prc = self._run_cmd(cmd) stdout = prc.stdout.read()",
"-c\".format(self.PKR) prc = self._run_cmd(cmd) stdout = prc.stdout.read() stderr = prc.stderr.read() # Python 3.6",
"\"kard\" / \"test\" self.assertTrue((out_dir / \"buildx\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir / \"context1\"",
"self.pkr_path / \"kard\" / \"test\" expected = sorted( [ out_dir / \"buildx\" /",
"\"file1\" / \"file2\", out_dir / \"buildx\" / \"file1.dockerfile\", out_dir / \"meta.yml\", ] )",
"self.assertEqual(stdout, b\"\", stdout) self.assertEqual( stderr, b\"ERROR: (Exception) buildx is not supported for python",
"stdout) self.assertRegex( stderr.decode(\"utf-8\"), r\"docker buildx build --progress plain --builder testpkrbuilder --load \" r\"--file",
"self.generate_kard() self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\" expected = sorted( [",
"image...\\n\\n\" ) self.assertTrue(\"unknown instruction: flag_value\" in stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout, expected, stdout) self.assertRegex( stderr.decode(\"utf-8\"),",
"self.make_kard() out_dir = self.pkr_path / \"kard\" / \"test\" self.assertTrue((out_dir / \"buildx\" / \"folder2_dst\"",
"image build -s container1 -c\".format(self.PKR) prc = self._run_cmd(cmd) stdout = prc.stdout.read() stderr =",
"self.assertEqual( stderr, b\"ERROR: (Exception) buildx is not supported for python < 3.6\\n\" )",
"is not supported for python < 3.6\\n\" ) return expected = ( b\"Warning:",
"p.is_dir(): yield from walk(p) continue yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected) def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] =",
"\"buildx\" / \"file1.dockerfile\").exists()) self.assertTrue((out_dir / \"context1\" / \"file1.dockerfile\").exists()) cmd = \"{} image build",
"\"file1.dockerfile\").exists()) cmd = \"{} image build -s container1 -c\".format(self.PKR) prc = self._run_cmd(cmd) stdout",
"expected) def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard(env=\"contexts\") self.make_kard() out_dir = self.pkr_path / \"kard\"",
"/ \"file1.dockerfile\").exists()) self.assertTrue((out_dir / \"context1\" / \"file1.dockerfile\").exists()) cmd = \"{} image build -s",
"build -s container1 -c\".format(self.PKR) prc = self._run_cmd(cmd) stdout = prc.stdout.read() stderr = prc.stderr.read()",
"b\"Building container1:123 image...\\n\\n\" ) self.assertTrue(\"unknown instruction: flag_value\" in stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout, expected, stdout)",
"yield from walk(p) continue yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected) def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] = self.src_path",
"\" r\"--file /tmp/.*/file1.dockerfile --cache-from type=registry,ref=dummy/cache \" r\"--cache-to type=registry,mode=max,ref=dummy/cache --tag container1:123 \" r\"/tmp/.*/context1\", )",
"docker images...\\n\\n\" b\"Building container1:123 image...\\n\\n\" ) self.assertTrue(\"unknown instruction: flag_value\" in stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout,",
"= prc.stderr.read() # Python 3.6 if sys.version_info < (3, 7): self.assertEqual(stdout, b\"\", stdout)",
".utils import pkrTestCase class TestBuildxDriver(pkrTestCase): PKR = \"pkr\" pkr_folder = \"docker_driver\" kard_env =",
"\"buildx\" / \"file1\" / \"file2\", out_dir / \"buildx\" / \"file1.dockerfile\", out_dir / \"meta.yml\",",
"this environment.\\n\" b\"Removing context1 ... Done !\\n\" b\"Removing buildx ... Done !\\n\" b\"Start",
"self.assertTrue((out_dir / \"context1\" / \"file1.dockerfile\").exists()) cmd = \"{} image build -s container1 -c\".format(self.PKR)",
"buildx is not supported for python < 3.6\\n\" ) return expected = (",
"/ \"copy\", out_dir / \"buildx\" / \"file1\" / \"file2\", out_dir / \"buildx\" /",
"\"context1\" / \"file1.dockerfile\").exists()) cmd = \"{} image build -s container1 -c\".format(self.PKR) prc =",
"Done !\\n\" b\"Start buildx builder testpkrbuilder\\n\" b\"Building docker images...\\n\\n\" b\"Building container1:123 image...\\n\\n\" )",
"stderr) self.assertEqual(stdout, expected, stdout) self.assertRegex( stderr.decode(\"utf-8\"), r\"docker buildx build --progress plain --builder testpkrbuilder",
"# Python 3.6 if sys.version_info < (3, 7): self.assertEqual(stdout, b\"\", stdout) self.assertEqual( stderr,",
"\"test\" expected = sorted( [ out_dir / \"buildx\" / \"folder2_dst\" / \"copy\", out_dir",
"buildx build --progress plain --builder testpkrbuilder --load \" r\"--file /tmp/.*/file1.dockerfile --cache-from type=registry,ref=dummy/cache \"",
"buildx ... Done !\\n\" b\"Start buildx builder testpkrbuilder\\n\" b\"Building docker images...\\n\\n\" b\"Building container1:123",
"testpkrbuilder --load \" r\"--file /tmp/.*/file1.dockerfile --cache-from type=registry,ref=dummy/cache \" r\"--cache-to type=registry,mode=max,ref=dummy/cache --tag container1:123 \"",
"prc = self._run_cmd(cmd) stdout = prc.stdout.read() stderr = prc.stderr.read() # Python 3.6 if",
"expected = ( b\"Warning: No docker-compose file is provided with this environment.\\n\" b\"Removing",
"environment.\\n\" b\"Removing context1 ... Done !\\n\" b\"Removing buildx ... Done !\\n\" b\"Start buildx",
"--progress plain --builder testpkrbuilder --load \" r\"--file /tmp/.*/file1.dockerfile --cache-from type=registry,ref=dummy/cache \" r\"--cache-to type=registry,mode=max,ref=dummy/cache",
"for python < 3.6\\n\" ) return expected = ( b\"Warning: No docker-compose file",
"/ \"copy\").exists()) self.assertTrue((out_dir / \"buildx\" / \"file1.dockerfile\").exists()) self.assertTrue((out_dir / \"context1\" / \"file1.dockerfile\").exists()) cmd",
"container1:123 image...\\n\\n\" ) self.assertTrue(\"unknown instruction: flag_value\" in stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout, expected, stdout) self.assertRegex(",
"7): self.assertEqual(stdout, b\"\", stdout) self.assertEqual( stderr, b\"ERROR: (Exception) buildx is not supported for",
"!\\n\" b\"Start buildx builder testpkrbuilder\\n\" b\"Building docker images...\\n\\n\" b\"Building container1:123 image...\\n\\n\" ) self.assertTrue(\"unknown",
"import pkrTestCase class TestBuildxDriver(pkrTestCase): PKR = \"pkr\" pkr_folder = \"docker_driver\" kard_env = \"dev\"",
"PKR = \"pkr\" pkr_folder = \"docker_driver\" kard_env = \"dev\" kard_driver = \"buildx_compose\" kard_extra",
"[ out_dir / \"buildx\" / \"folder2_dst\" / \"copy\", out_dir / \"buildx\" / \"file1\"",
"\"buildx_compose\" kard_extra = { \"tag\": \"123\", \"flag\": \"flag_value\", \"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\": \"testpkrbuilder\", }",
"b\"Removing buildx ... Done !\\n\" b\"Start buildx builder testpkrbuilder\\n\" b\"Building docker images...\\n\\n\" b\"Building",
"\"folder2_dst\" / \"copy\", out_dir / \"buildx\" / \"file1\" / \"file2\", out_dir / \"buildx\"",
"context1 ... Done !\\n\" b\"Removing buildx ... Done !\\n\" b\"Start buildx builder testpkrbuilder\\n\"",
"-s container1 -c\".format(self.PKR) prc = self._run_cmd(cmd) stdout = prc.stdout.read() stderr = prc.stderr.read() #",
"= \"pkr\" pkr_folder = \"docker_driver\" kard_env = \"dev\" kard_driver = \"buildx_compose\" kard_extra =",
"buildx builder testpkrbuilder\\n\" b\"Building docker images...\\n\\n\" b\"Building container1:123 image...\\n\\n\" ) self.assertTrue(\"unknown instruction: flag_value\"",
"out_dir / \"buildx\" / \"folder2_dst\" / \"copy\", out_dir / \"buildx\" / \"file1\" /",
"images...\\n\\n\" b\"Building container1:123 image...\\n\\n\" ) self.assertTrue(\"unknown instruction: flag_value\" in stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout, expected,",
"self.assertEqual(sorted(list(walk(out_dir))), expected) def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard(env=\"contexts\") self.make_kard() out_dir = self.pkr_path /",
"--load \" r\"--file /tmp/.*/file1.dockerfile --cache-from type=registry,ref=dummy/cache \" r\"--cache-to type=registry,mode=max,ref=dummy/cache --tag container1:123 \" r\"/tmp/.*/context1\",",
"class TestBuildxDriver(pkrTestCase): PKR = \"pkr\" pkr_folder = \"docker_driver\" kard_env = \"dev\" kard_driver =",
"\"file2\", out_dir / \"buildx\" / \"file1.dockerfile\", out_dir / \"meta.yml\", ] ) def walk(path):",
"= self.pkr_path / \"kard\" / \"test\" expected = sorted( [ out_dir / \"buildx\"",
"/ \"meta.yml\", ] ) def walk(path): for p in path.iterdir(): if p.is_dir(): yield",
"def walk(path): for p in path.iterdir(): if p.is_dir(): yield from walk(p) continue yield",
"self.pkr_path / \"kard\" / \"test\" self.assertTrue((out_dir / \"buildx\" / \"folder2_dst\" / \"copy\").exists()) self.assertTrue((out_dir",
"/ \"context1\" / \"file1.dockerfile\").exists()) cmd = \"{} image build -s container1 -c\".format(self.PKR) prc",
"< (3, 7): self.assertEqual(stdout, b\"\", stdout) self.assertEqual( stderr, b\"ERROR: (Exception) buildx is not",
"cmd = \"{} image build -s container1 -c\".format(self.PKR) prc = self._run_cmd(cmd) stdout =",
"{ \"tag\": \"123\", \"flag\": \"flag_value\", \"buildx.cache_registry\": \"dummy\", \"buildx.builder_name\": \"testpkrbuilder\", } def test_docker_driver_values(self): self.kard_extra[\"src_path\"]",
"b\"ERROR: (Exception) buildx is not supported for python < 3.6\\n\" ) return expected",
"Python 3.6 if sys.version_info < (3, 7): self.assertEqual(stdout, b\"\", stdout) self.assertEqual( stderr, b\"ERROR:",
"r\"docker buildx build --progress plain --builder testpkrbuilder --load \" r\"--file /tmp/.*/file1.dockerfile --cache-from type=registry,ref=dummy/cache",
"self.assertTrue(\"unknown instruction: flag_value\" in stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout, expected, stdout) self.assertRegex( stderr.decode(\"utf-8\"), r\"docker buildx",
"import sys from .utils import pkrTestCase class TestBuildxDriver(pkrTestCase): PKR = \"pkr\" pkr_folder =",
"instruction: flag_value\" in stderr.decode(\"utf-8\"), stderr) self.assertEqual(stdout, expected, stdout) self.assertRegex( stderr.decode(\"utf-8\"), r\"docker buildx build",
"self.assertTrue((out_dir / \"buildx\" / \"file1.dockerfile\").exists()) self.assertTrue((out_dir / \"context1\" / \"file1.dockerfile\").exists()) cmd = \"{}",
"continue yield p.resolve() self.assertEqual(sorted(list(walk(out_dir))), expected) def test_docker_multiple_contexts(self): self.kard_extra[\"src_path\"] = self.src_path self.generate_kard(env=\"contexts\") self.make_kard() out_dir",
"\"kard\" / \"test\" expected = sorted( [ out_dir / \"buildx\" / \"folder2_dst\" /"
] |
[
"<1> sentence = sentence.split(' ') for word in sentence: # <2> if len(word)",
"= sentence.split(' ') for word in sentence: # <2> if len(word) > 10:",
"') for word in sentence: # <2> if len(word) > 10: # <3>",
"sentence: # <2> if len(word) > 10: # <3> return True return False",
"in sentence: # <2> if len(word) > 10: # <3> return True return",
"if isinstance(sentence, str): # <1> sentence = sentence.split(' ') for word in sentence:",
"# <2> if len(word) > 10: # <3> return True return False #",
"<2> if len(word) > 10: # <3> return True return False # <4>",
"sentence.split(' ') for word in sentence: # <2> if len(word) > 10: #",
"word in sentence: # <2> if len(word) > 10: # <3> return True",
"isinstance(sentence, str): # <1> sentence = sentence.split(' ') for word in sentence: #",
"for word in sentence: # <2> if len(word) > 10: # <3> return",
"sentence = sentence.split(' ') for word in sentence: # <2> if len(word) >",
"def has_long_words(sentence): if isinstance(sentence, str): # <1> sentence = sentence.split(' ') for word",
"str): # <1> sentence = sentence.split(' ') for word in sentence: # <2>",
"# <1> sentence = sentence.split(' ') for word in sentence: # <2> if",
"has_long_words(sentence): if isinstance(sentence, str): # <1> sentence = sentence.split(' ') for word in"
] |
[
"<filename>src/wready/__init__.py from .sig_handler import SignalInterruptHandler from .wready_client import TaskContext, WReadyClient from .wready_server import",
"import SignalInterruptHandler from .wready_client import TaskContext, WReadyClient from .wready_server import InitTask, WReadyServer, WReadyServerObserver",
"from .sig_handler import SignalInterruptHandler from .wready_client import TaskContext, WReadyClient from .wready_server import InitTask,",
".sig_handler import SignalInterruptHandler from .wready_client import TaskContext, WReadyClient from .wready_server import InitTask, WReadyServer,"
] |
[
"product.pear, product.melon], create_price=[340, 490], create_time_sec=1800, manpower=108 ) # Iron Age IronForger = base.ManufactureBuilding(",
"create_time_sec=1800, manpower=108 ) # Iron Age IronForger = base.ManufactureBuilding( name=\"🥩🏠 Мясник\", products=[product.meat, product.chicken],",
"Плантация\", products=[product.grape, product.pear, product.melon], create_price=[340, 490], create_time_sec=1800, manpower=108 ) # Iron Age IronForger",
"490], create_time_sec=1800, manpower=108 ) BronzePlantation = base.ManufactureBuilding( name=\"🍇🏠 Плантация\", products=[product.grape, product.pear, product.melon], create_price=[340,",
"create_price=[340, 490], create_time_sec=1800, manpower=108 ) # Iron Age IronForger = base.ManufactureBuilding( name=\"🥩🏠 Мясник\",",
"490], create_time_sec=1800, manpower=108 ) # Iron Age IronForger = base.ManufactureBuilding( name=\"🥩🏠 Мясник\", products=[product.meat,",
"= base.ManufactureBuilding( name=\"🥩🏠 Мясник\", products=[product.meat, product.chicken], create_price=[1500, 2400], create_time_sec=5400, manpower=230 ) IronButcher =",
") # Iron Age IronForger = base.ManufactureBuilding( name=\"🥩🏠 Мясник\", products=[product.meat, product.chicken], create_price=[1500, 2400],",
"base, product # # Bronze Age # BronzePottery = base.ManufactureBuilding( name=\"🏺🏠 Гончарня\", products=[product.dish,",
"base.ManufactureBuilding( name=\"🍇🏠 Плантация\", products=[product.grape, product.pear, product.melon], create_price=[340, 490], create_time_sec=1800, manpower=108 ) # Iron",
"# Bronze Age # BronzePottery = base.ManufactureBuilding( name=\"🏺🏠 Гончарня\", products=[product.dish, product.jug, product.amphora], create_price=[340,",
"IronForger = base.ManufactureBuilding( name=\"🥩🏠 Мясник\", products=[product.meat, product.chicken], create_price=[1500, 2400], create_time_sec=5400, manpower=230 ) IronButcher",
"name=\"🥩🏠 Мясник\", products=[product.meat, product.chicken], create_price=[1500, 2400], create_time_sec=5400, manpower=230 ) IronButcher = base.ManufactureBuilding( name=\"🧵🏠",
"create_time_sec=1800, manpower=108 ) BronzePlantation = base.ManufactureBuilding( name=\"🍇🏠 Плантация\", products=[product.grape, product.pear, product.melon], create_price=[340, 490],",
"BronzePlantation = base.ManufactureBuilding( name=\"🍇🏠 Плантация\", products=[product.grape, product.pear, product.melon], create_price=[340, 490], create_time_sec=1800, manpower=108 )",
"# BronzePottery = base.ManufactureBuilding( name=\"🏺🏠 Гончарня\", products=[product.dish, product.jug, product.amphora], create_price=[340, 490], create_time_sec=1800, manpower=108",
"from utils.models import base, product # # Bronze Age # BronzePottery = base.ManufactureBuilding(",
") BronzePlantation = base.ManufactureBuilding( name=\"🍇🏠 Плантация\", products=[product.grape, product.pear, product.melon], create_price=[340, 490], create_time_sec=1800, manpower=108",
"base.ManufactureBuilding( name=\"🏺🏠 Гончарня\", products=[product.dish, product.jug, product.amphora], create_price=[340, 490], create_time_sec=1800, manpower=108 ) BronzePlantation =",
"product.melon], create_price=[340, 490], create_time_sec=1800, manpower=108 ) # Iron Age IronForger = base.ManufactureBuilding( name=\"🥩🏠",
"manpower=108 ) BronzePlantation = base.ManufactureBuilding( name=\"🍇🏠 Плантация\", products=[product.grape, product.pear, product.melon], create_price=[340, 490], create_time_sec=1800,",
"utils.models import base, product # # Bronze Age # BronzePottery = base.ManufactureBuilding( name=\"🏺🏠",
"name=\"🍇🏠 Плантация\", products=[product.grape, product.pear, product.melon], create_price=[340, 490], create_time_sec=1800, manpower=108 ) # Iron Age",
"import base, product # # Bronze Age # BronzePottery = base.ManufactureBuilding( name=\"🏺🏠 Гончарня\",",
"products=[product.grape, product.pear, product.melon], create_price=[340, 490], create_time_sec=1800, manpower=108 ) # Iron Age IronForger =",
"Bronze Age # BronzePottery = base.ManufactureBuilding( name=\"🏺🏠 Гончарня\", products=[product.dish, product.jug, product.amphora], create_price=[340, 490],",
"# # Bronze Age # BronzePottery = base.ManufactureBuilding( name=\"🏺🏠 Гончарня\", products=[product.dish, product.jug, product.amphora],",
"products=[product.meat, product.chicken], create_price=[1500, 2400], create_time_sec=5400, manpower=230 ) IronButcher = base.ManufactureBuilding( name=\"🧵🏠 Портной\", products=[product.threads,",
"create_time_sec=5400, manpower=230 ) IronButcher = base.ManufactureBuilding( name=\"🧵🏠 Портной\", products=[product.threads, product.socks], create_price=[1500, 2400], create_time_sec=5400,",
"products=[product.dish, product.jug, product.amphora], create_price=[340, 490], create_time_sec=1800, manpower=108 ) BronzePlantation = base.ManufactureBuilding( name=\"🍇🏠 Плантация\",",
"Гончарня\", products=[product.dish, product.jug, product.amphora], create_price=[340, 490], create_time_sec=1800, manpower=108 ) BronzePlantation = base.ManufactureBuilding( name=\"🍇🏠",
"manpower=108 ) # Iron Age IronForger = base.ManufactureBuilding( name=\"🥩🏠 Мясник\", products=[product.meat, product.chicken], create_price=[1500,",
"name=\"🏺🏠 Гончарня\", products=[product.dish, product.jug, product.amphora], create_price=[340, 490], create_time_sec=1800, manpower=108 ) BronzePlantation = base.ManufactureBuilding(",
"product.jug, product.amphora], create_price=[340, 490], create_time_sec=1800, manpower=108 ) BronzePlantation = base.ManufactureBuilding( name=\"🍇🏠 Плантация\", products=[product.grape,",
"create_price=[1500, 2400], create_time_sec=5400, manpower=230 ) IronButcher = base.ManufactureBuilding( name=\"🧵🏠 Портной\", products=[product.threads, product.socks], create_price=[1500,",
") IronButcher = base.ManufactureBuilding( name=\"🧵🏠 Портной\", products=[product.threads, product.socks], create_price=[1500, 2400], create_time_sec=5400, manpower=230 )",
"2400], create_time_sec=5400, manpower=230 ) IronButcher = base.ManufactureBuilding( name=\"🧵🏠 Портной\", products=[product.threads, product.socks], create_price=[1500, 2400],",
"product.chicken], create_price=[1500, 2400], create_time_sec=5400, manpower=230 ) IronButcher = base.ManufactureBuilding( name=\"🧵🏠 Портной\", products=[product.threads, product.socks],",
"= base.ManufactureBuilding( name=\"🍇🏠 Плантация\", products=[product.grape, product.pear, product.melon], create_price=[340, 490], create_time_sec=1800, manpower=108 ) #",
"BronzePottery = base.ManufactureBuilding( name=\"🏺🏠 Гончарня\", products=[product.dish, product.jug, product.amphora], create_price=[340, 490], create_time_sec=1800, manpower=108 )",
"base.ManufactureBuilding( name=\"🥩🏠 Мясник\", products=[product.meat, product.chicken], create_price=[1500, 2400], create_time_sec=5400, manpower=230 ) IronButcher = base.ManufactureBuilding(",
"Мясник\", products=[product.meat, product.chicken], create_price=[1500, 2400], create_time_sec=5400, manpower=230 ) IronButcher = base.ManufactureBuilding( name=\"🧵🏠 Портной\",",
"# Iron Age IronForger = base.ManufactureBuilding( name=\"🥩🏠 Мясник\", products=[product.meat, product.chicken], create_price=[1500, 2400], create_time_sec=5400,",
"Age IronForger = base.ManufactureBuilding( name=\"🥩🏠 Мясник\", products=[product.meat, product.chicken], create_price=[1500, 2400], create_time_sec=5400, manpower=230 )",
"Age # BronzePottery = base.ManufactureBuilding( name=\"🏺🏠 Гончарня\", products=[product.dish, product.jug, product.amphora], create_price=[340, 490], create_time_sec=1800,",
"product.amphora], create_price=[340, 490], create_time_sec=1800, manpower=108 ) BronzePlantation = base.ManufactureBuilding( name=\"🍇🏠 Плантация\", products=[product.grape, product.pear,",
"= base.ManufactureBuilding( name=\"🏺🏠 Гончарня\", products=[product.dish, product.jug, product.amphora], create_price=[340, 490], create_time_sec=1800, manpower=108 ) BronzePlantation",
"manpower=230 ) IronButcher = base.ManufactureBuilding( name=\"🧵🏠 Портной\", products=[product.threads, product.socks], create_price=[1500, 2400], create_time_sec=5400, manpower=230",
"Iron Age IronForger = base.ManufactureBuilding( name=\"🥩🏠 Мясник\", products=[product.meat, product.chicken], create_price=[1500, 2400], create_time_sec=5400, manpower=230",
"create_price=[340, 490], create_time_sec=1800, manpower=108 ) BronzePlantation = base.ManufactureBuilding( name=\"🍇🏠 Плантация\", products=[product.grape, product.pear, product.melon],",
"product # # Bronze Age # BronzePottery = base.ManufactureBuilding( name=\"🏺🏠 Гончарня\", products=[product.dish, product.jug,"
] |
[
"The Floor's Revenge - Project Euler # https://projecteuler.net/problem=546 # # Code by <NAME>",
"# #546 The Floor's Revenge - Project Euler # https://projecteuler.net/problem=546 # # Code",
"# # #546 The Floor's Revenge - Project Euler # https://projecteuler.net/problem=546 # #",
"Revenge - Project Euler # https://projecteuler.net/problem=546 # # Code by <NAME> # ###########################",
"#546 The Floor's Revenge - Project Euler # https://projecteuler.net/problem=546 # # Code by",
"########################### # # #546 The Floor's Revenge - Project Euler # https://projecteuler.net/problem=546 #",
"Floor's Revenge - Project Euler # https://projecteuler.net/problem=546 # # Code by <NAME> #"
] |
[
"field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='end_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='worker', name='qualification', field=models.IntegerField(default=0), ), ]",
"model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='end_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='worker', name='qualification', field=models.IntegerField(default=0),",
"Generated by Django 2.1.3 on 2018-11-09 00:49 from django.db import migrations, models class",
"dependencies = [ ('workertasks', '0002_auto_20181109_0046'), ] operations = [ migrations.AlterField( model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True),",
"by Django 2.1.3 on 2018-11-09 00:49 from django.db import migrations, models class Migration(migrations.Migration):",
"= [ migrations.AlterField( model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True), ), migrations.AlterField(",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workertasks', '0002_auto_20181109_0046'), ]",
"field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='end_hit', field=models.DateTimeField(null=True), ), migrations.AlterField(",
"00:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workertasks', '0002_auto_20181109_0046'),",
"), migrations.AlterField( model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='end_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='worker',",
"migrations.AlterField( model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='end_hit',",
"('workertasks', '0002_auto_20181109_0046'), ] operations = [ migrations.AlterField( model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment',",
"# Generated by Django 2.1.3 on 2018-11-09 00:49 from django.db import migrations, models",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('workertasks', '0002_auto_20181109_0046'), ] operations = [",
"migrations.AlterField( model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='end_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='worker', name='qualification',",
"[ migrations.AlterField( model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment',",
"name='begin_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='end_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='worker', name='qualification', field=models.IntegerField(default=0), ),",
"operations = [ migrations.AlterField( model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True), ),",
"name='begin_exp', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='end_hit', field=models.DateTimeField(null=True), ),",
"Django 2.1.3 on 2018-11-09 00:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"Migration(migrations.Migration): dependencies = [ ('workertasks', '0002_auto_20181109_0046'), ] operations = [ migrations.AlterField( model_name='assignment', name='begin_exp',",
"class Migration(migrations.Migration): dependencies = [ ('workertasks', '0002_auto_20181109_0046'), ] operations = [ migrations.AlterField( model_name='assignment',",
"= [ ('workertasks', '0002_auto_20181109_0046'), ] operations = [ migrations.AlterField( model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True), ),",
"on 2018-11-09 00:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"'0002_auto_20181109_0046'), ] operations = [ migrations.AlterField( model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='begin_hit',",
"2018-11-09 00:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workertasks',",
"model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='end_hit', field=models.DateTimeField(null=True),",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workertasks', '0002_auto_20181109_0046'), ] operations",
"models class Migration(migrations.Migration): dependencies = [ ('workertasks', '0002_auto_20181109_0046'), ] operations = [ migrations.AlterField(",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('workertasks', '0002_auto_20181109_0046'), ] operations =",
"] operations = [ migrations.AlterField( model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True), ), migrations.AlterField( model_name='assignment', name='begin_hit', field=models.DateTimeField(null=True),",
"2.1.3 on 2018-11-09 00:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"[ ('workertasks', '0002_auto_20181109_0046'), ] operations = [ migrations.AlterField( model_name='assignment', name='begin_exp', field=models.DateTimeField(null=True), ), migrations.AlterField("
] |
[
"fox', '4 b1' ] \"\"\" newmols = Multiset() for mol in mollist: mol",
"educts.split('+') prlist = products.split('+') edmset = ReactionParser.parse_molecules( self, edlist ) prmset = ReactionParser.parse_molecules(",
"ValueError: print >> sys.stderr, \"syntax error on line=\", line exit(-1) if (edmset.empty() and",
"ValueError k = float(kvar) (educts, products) = reactstr.split('-->', 2) edlist = educts.split('+') prlist",
"PURPOSE. See the # GNU General Public License for more details. # #",
"class ReactionParser(): def parse_molecules( self, mollist ): \"\"\" parse educt or product multiset",
"2) edlist = educts.split('+') prlist = products.split('+') edmset = ReactionParser.parse_molecules( self, edlist )",
"published by the Free Software Foundation. # # PyCellChemistry is distributed in the",
"prlist = products.split('+') edmset = ReactionParser.parse_molecules( self, edlist ) prmset = ReactionParser.parse_molecules( self,",
"return self.parse_input(sys.stdin) def parse_file( self, fname ): \"\"\" open and parse input file",
"GNU General Public License # along with PyCellChemistry, see file COPYING. If not,",
"# ReactionParser.py: parser for chemical reactions in text format, such as: # #",
"line = line.strip() if (line != '' and line[0] != '#'): reaction =",
"0 and name != '': newmols.inject(name, n) return newmols def parse_line( self, line",
"# - - - - - - - - - - - -",
"(reactstr, kstr) = line.split(',', 2) reactstr = reactstr.strip() (kstr, kvar) = kstr.split('=', 2)",
"a copy of the GNU General Public License # along with PyCellChemistry, see",
"and prmset.empty()): return newreaction = Reaction(edmset, prmset, k) return newreaction def parse_input( self,",
"GNU General Public License # version 3, as published by the Free Software",
"- - - - - - # # Copyright (C) 2015 <NAME> #",
"parser for chemical reactions in text format, such as: # # A +",
"= products.split('+') edmset = ReactionParser.parse_molecules( self, edlist ) prmset = ReactionParser.parse_molecules( self, prlist",
"parse input file fname \"\"\" reactions = None try: infd = open(fname, 'r')",
"is part of PyCellChemistry. # # PyCellChemistry is free software: you can redistribute",
"line.find(',') < 0: reactstr = line k = 1.0 else: (reactstr, kstr) =",
"self, line ): \"\"\" parse string containing chemical reaction \"\"\" line2 = line.split('#')",
"!= '' and line[0] != '#'): reaction = self.parse_line(line) reactions.add(reaction) return reactions def",
"should have received a copy of the GNU General Public License # along",
"2) name = name.strip() n = int(num) if n > 0 and name",
"(num, name) = mol.split(' ', 2) name = name.strip() n = int(num) if",
"= int(num) if n > 0 and name != '': newmols.inject(name, n) return",
"self, infile ): \"\"\" parse input file containing multiple chemical reactions, one per",
"without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"): \"\"\" parse input file containing multiple chemical reactions, one per line. 'infile'",
"def parse_input( self, infile ): \"\"\" parse input file containing multiple chemical reactions,",
"http://www.gnu.org/licenses/ # import sys from Multiset import * from Reaction import * class",
"sys from Multiset import * from Reaction import * class ReactionParser(): def parse_molecules(",
"- - - - - - - # # Copyright (C) 2015 <NAME>",
"- - - - - - - - - - - # #",
"format, such as: # # A + 2 B --> 3 C ,",
"along with PyCellChemistry, see file COPYING. If not, see # http://www.gnu.org/licenses/ # import",
"product multiset given as a list of strings containing the molecule name and",
"'4 b1' ] \"\"\" newmols = Multiset() for mol in mollist: mol =",
"see # http://www.gnu.org/licenses/ # import sys from Multiset import * from Reaction import",
"You should have received a copy of the GNU General Public License #",
"of the GNU General Public License # along with PyCellChemistry, see file COPYING.",
"by <NAME>, Univ. Basel, Switzerland, January 2010 # June 2013: adapted to the",
"import * class ReactionParser(): def parse_molecules( self, mollist ): \"\"\" parse educt or",
"line.strip() if (line != '' and line[0] != '#'): reaction = self.parse_line(line) reactions.add(reaction)",
"0: reactstr = line k = 1.0 else: (reactstr, kstr) = line.split(',', 2)",
"if (kstr.strip() != 'k'): raise ValueError k = float(kvar) (educts, products) = reactstr.split('-->',",
"details. # # You should have received a copy of the GNU General",
"WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A",
"line k = 1.0 else: (reactstr, kstr) = line.split(',', 2) reactstr = reactstr.strip()",
"') < 0: name = mol n = 1 else: (num, name) =",
"to the PyCellChemistry package # # - - - - - - -",
"self.parse_input(sys.stdin) def parse_file( self, fname ): \"\"\" open and parse input file fname",
"that it will be useful, # but WITHOUT ANY WARRANTY; without even the",
"sys.stderr, \"syntax error on line=\", line exit(-1) if (edmset.empty() and prmset.empty()): return newreaction",
"return newreaction def parse_input( self, infile ): \"\"\" parse input file containing multiple",
"k = 1.0 else: (reactstr, kstr) = line.split(',', 2) reactstr = reactstr.strip() (kstr,",
"input (stdin) \"\"\" return self.parse_input(sys.stdin) def parse_file( self, fname ): \"\"\" open and",
"except ValueError: print >> sys.stderr, \"syntax error on line=\", line exit(-1) if (edmset.empty()",
"mol.find(' ') < 0: name = mol n = 1 else: (num, name)",
"self ): \"\"\" parse standard input (stdin) \"\"\" return self.parse_input(sys.stdin) def parse_file( self,",
"Reaction import * class ReactionParser(): def parse_molecules( self, mollist ): \"\"\" parse educt",
"parse_molecules( self, mollist ): \"\"\" parse educt or product multiset given as a",
"# Copyright (C) 2015 <NAME> # Contact: http://www.artificial-chemistries.org/ # # This file is",
"of strings containing the molecule name and an optional stoichiometric coefficient, e.g. [",
"line=\", line exit(-1) if (edmset.empty() and prmset.empty()): return newreaction = Reaction(edmset, prmset, k)",
"implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"educt or product multiset given as a list of strings containing the molecule",
">> sys.stderr, \"syntax error on line=\", line exit(-1) if (edmset.empty() and prmset.empty()): return",
"and parse input file fname \"\"\" reactions = None try: infd = open(fname,",
"it and/or # modify it under the terms of the GNU General Public",
"!= 'k'): raise ValueError k = float(kvar) (educts, products) = reactstr.split('-->', 2) edlist",
"kstr) = line.split(',', 2) reactstr = reactstr.strip() (kstr, kvar) = kstr.split('=', 2) if",
"(edmset.empty() and prmset.empty()): return newreaction = Reaction(edmset, prmset, k) return newreaction def parse_input(",
"the hope that it will be useful, # but WITHOUT ANY WARRANTY; without",
"'#'): reaction = self.parse_line(line) reactions.add(reaction) return reactions def parse_stdin( self ): \"\"\" parse",
"containing chemical reaction \"\"\" line2 = line.split('#') # skip comments line = line2[0]",
"!= '#'): reaction = self.parse_line(line) reactions.add(reaction) return reactions def parse_stdin( self ): \"\"\"",
"'': newmols.inject(name, n) return newmols def parse_line( self, line ): \"\"\" parse string",
"newmols def parse_line( self, line ): \"\"\" parse string containing chemical reaction \"\"\"",
"> 0 and name != '': newmols.inject(name, n) return newmols def parse_line( self,",
"General Public License # version 3, as published by the Free Software Foundation.",
"line ): \"\"\" parse string containing chemical reaction \"\"\" line2 = line.split('#') #",
"): \"\"\" open and parse input file fname \"\"\" reactions = None try:",
"the Free Software Foundation. # # PyCellChemistry is distributed in the hope that",
"# You should have received a copy of the GNU General Public License",
"line.split(',', 2) reactstr = reactstr.strip() (kstr, kvar) = kstr.split('=', 2) if (kstr.strip() !=",
"= mol n = 1 else: (num, name) = mol.split(' ', 2) name",
"\"\"\" parse string containing chemical reaction \"\"\" line2 = line.split('#') # skip comments",
"line.split('#') # skip comments line = line2[0] try: if line.find(',') < 0: reactstr",
"Reaction(edmset, prmset, k) return newreaction def parse_input( self, infile ): \"\"\" parse input",
"- - - # # Copyright (C) 2015 <NAME> # Contact: http://www.artificial-chemistries.org/ #",
"multiset given as a list of strings containing the molecule name and an",
"# # PyCellChemistry is distributed in the hope that it will be useful,",
"reactstr = reactstr.strip() (kstr, kvar) = kstr.split('=', 2) if (kstr.strip() != 'k'): raise",
"\"syntax error on line=\", line exit(-1) if (edmset.empty() and prmset.empty()): return newreaction =",
"= 1.0 else: (reactstr, kstr) = line.split(',', 2) reactstr = reactstr.strip() (kstr, kvar)",
"- - - - - - - - - - # # Copyright",
"# A + 2 B --> 3 C , k=2.49 # # by",
"A PARTICULAR PURPOSE. See the # GNU General Public License for more details.",
"1.0 else: (reactstr, kstr) = line.split(',', 2) reactstr = reactstr.strip() (kstr, kvar) =",
"= float(kvar) (educts, products) = reactstr.split('-->', 2) edlist = educts.split('+') prlist = products.split('+')",
"parse_file( self, fname ): \"\"\" open and parse input file fname \"\"\" reactions",
"one per line. 'infile' is the file descriptor for the open input file",
"open input file \"\"\" reactions = ReactionQueue() for line in infile.readlines(): line =",
"file containing multiple chemical reactions, one per line. 'infile' is the file descriptor",
"- - - - - # # Copyright (C) 2015 <NAME> # Contact:",
"try: infd = open(fname, 'r') reactions = self.parse_input(infd) infd.close() except IOError: print >>",
"<NAME>, Univ. Basel, Switzerland, January 2010 # June 2013: adapted to the PyCellChemistry",
"skip comments line = line2[0] try: if line.find(',') < 0: reactstr = line",
"exit(-1) if (edmset.empty() and prmset.empty()): return newreaction = Reaction(edmset, prmset, k) return newreaction",
"# GNU General Public License for more details. # # You should have",
"line exit(-1) if (edmset.empty() and prmset.empty()): return newreaction = Reaction(edmset, prmset, k) return",
"fname ): \"\"\" open and parse input file fname \"\"\" reactions = None",
"fname \"\"\" reactions = None try: infd = open(fname, 'r') reactions = self.parse_input(infd)",
"- - - - - - - - - - - - #",
"list of strings containing the molecule name and an optional stoichiometric coefficient, e.g.",
"for mol in mollist: mol = mol.strip() if mol.find(' ') < 0: name",
"ReactionParser(): def parse_molecules( self, mollist ): \"\"\" parse educt or product multiset given",
"'a', '2 fox', '4 b1' ] \"\"\" newmols = Multiset() for mol in",
"part of PyCellChemistry. # # PyCellChemistry is free software: you can redistribute it",
"file \"\"\" reactions = ReactionQueue() for line in infile.readlines(): line = line.strip() if",
"# modify it under the terms of the GNU General Public License #",
"received a copy of the GNU General Public License # along with PyCellChemistry,",
"file fname \"\"\" reactions = None try: infd = open(fname, 'r') reactions =",
"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General",
"): \"\"\" parse educt or product multiset given as a list of strings",
"reaction = self.parse_line(line) reactions.add(reaction) return reactions def parse_stdin( self ): \"\"\" parse standard",
"= 1 else: (num, name) = mol.split(' ', 2) name = name.strip() n",
"file COPYING. If not, see # http://www.gnu.org/licenses/ # import sys from Multiset import",
"reactions.add(reaction) return reactions def parse_stdin( self ): \"\"\" parse standard input (stdin) \"\"\"",
"self.parse_line(line) reactions.add(reaction) return reactions def parse_stdin( self ): \"\"\" parse standard input (stdin)",
"of PyCellChemistry. # # PyCellChemistry is free software: you can redistribute it and/or",
"(C) 2015 <NAME> # Contact: http://www.artificial-chemistries.org/ # # This file is part of",
"parse_line( self, line ): \"\"\" parse string containing chemical reaction \"\"\" line2 =",
"Public License # version 3, as published by the Free Software Foundation. #",
"containing the molecule name and an optional stoichiometric coefficient, e.g. [ 'a', '2",
"<NAME> # Contact: http://www.artificial-chemistries.org/ # # This file is part of PyCellChemistry. #",
"and/or # modify it under the terms of the GNU General Public License",
"ReactionParser.parse_molecules( self, edlist ) prmset = ReactionParser.parse_molecules( self, prlist ) except ValueError: print",
"input file containing multiple chemical reactions, one per line. 'infile' is the file",
"If not, see # http://www.gnu.org/licenses/ # import sys from Multiset import * from",
"= ReactionParser.parse_molecules( self, prlist ) except ValueError: print >> sys.stderr, \"syntax error on",
"reactions in text format, such as: # # A + 2 B -->",
"\"\"\" reactions = ReactionQueue() for line in infile.readlines(): line = line.strip() if (line",
"--> 3 C , k=2.49 # # by <NAME>, Univ. Basel, Switzerland, January",
"of the GNU General Public License # version 3, as published by the",
"descriptor for the open input file \"\"\" reactions = ReactionQueue() for line in",
"None try: infd = open(fname, 'r') reactions = self.parse_input(infd) infd.close() except IOError: print",
"warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #",
"if line.find(',') < 0: reactstr = line k = 1.0 else: (reactstr, kstr)",
"= line.split('#') # skip comments line = line2[0] try: if line.find(',') < 0:",
"# http://www.gnu.org/licenses/ # import sys from Multiset import * from Reaction import *",
"chemical reaction \"\"\" line2 = line.split('#') # skip comments line = line2[0] try:",
"name = mol n = 1 else: (num, name) = mol.split(' ', 2)",
"PyCellChemistry. # # PyCellChemistry is free software: you can redistribute it and/or #",
"(stdin) \"\"\" return self.parse_input(sys.stdin) def parse_file( self, fname ): \"\"\" open and parse",
"< 0: name = mol n = 1 else: (num, name) = mol.split('",
"parse string containing chemical reaction \"\"\" line2 = line.split('#') # skip comments line",
"+ 2 B --> 3 C , k=2.49 # # by <NAME>, Univ.",
"2013: adapted to the PyCellChemistry package # # - - - - -",
"- - - - - - - - - - - - -",
"is the file descriptor for the open input file \"\"\" reactions = ReactionQueue()",
"on line=\", line exit(-1) if (edmset.empty() and prmset.empty()): return newreaction = Reaction(edmset, prmset,",
"it will be useful, # but WITHOUT ANY WARRANTY; without even the implied",
"Contact: http://www.artificial-chemistries.org/ # # This file is part of PyCellChemistry. # # PyCellChemistry",
"= name.strip() n = int(num) if n > 0 and name != '':",
"prmset, k) return newreaction def parse_input( self, infile ): \"\"\" parse input file",
"'' and line[0] != '#'): reaction = self.parse_line(line) reactions.add(reaction) return reactions def parse_stdin(",
"\"\"\" parse input file containing multiple chemical reactions, one per line. 'infile' is",
"- - - - - - - - - # # Copyright (C)",
"for chemical reactions in text format, such as: # # A + 2",
"General Public License for more details. # # You should have received a",
"try: if line.find(',') < 0: reactstr = line k = 1.0 else: (reactstr,",
"if (line != '' and line[0] != '#'): reaction = self.parse_line(line) reactions.add(reaction) return",
"the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"= ReactionQueue() for line in infile.readlines(): line = line.strip() if (line != ''",
"file is part of PyCellChemistry. # # PyCellChemistry is free software: you can",
"[ 'a', '2 fox', '4 b1' ] \"\"\" newmols = Multiset() for mol",
"reactstr.split('-->', 2) edlist = educts.split('+') prlist = products.split('+') edmset = ReactionParser.parse_molecules( self, edlist",
"line2 = line.split('#') # skip comments line = line2[0] try: if line.find(',') <",
"# by <NAME>, Univ. Basel, Switzerland, January 2010 # June 2013: adapted to",
"http://www.artificial-chemistries.org/ # # This file is part of PyCellChemistry. # # PyCellChemistry is",
"float(kvar) (educts, products) = reactstr.split('-->', 2) edlist = educts.split('+') prlist = products.split('+') edmset",
"June 2013: adapted to the PyCellChemistry package # # - - - -",
"import sys from Multiset import * from Reaction import * class ReactionParser(): def",
"the # GNU General Public License for more details. # # You should",
"!= '': newmols.inject(name, n) return newmols def parse_line( self, line ): \"\"\" parse",
"n) return newmols def parse_line( self, line ): \"\"\" parse string containing chemical",
"# along with PyCellChemistry, see file COPYING. If not, see # http://www.gnu.org/licenses/ #",
"or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License",
"\"\"\" return self.parse_input(sys.stdin) def parse_file( self, fname ): \"\"\" open and parse input",
"for more details. # # You should have received a copy of the",
"the PyCellChemistry package # # - - - - - - - -",
"input file fname \"\"\" reactions = None try: infd = open(fname, 'r') reactions",
"multiple chemical reactions, one per line. 'infile' is the file descriptor for the",
"def parse_stdin( self ): \"\"\" parse standard input (stdin) \"\"\" return self.parse_input(sys.stdin) def",
"the open input file \"\"\" reactions = ReactionQueue() for line in infile.readlines(): line",
"reactions = None try: infd = open(fname, 'r') reactions = self.parse_input(infd) infd.close() except",
"License # along with PyCellChemistry, see file COPYING. If not, see # http://www.gnu.org/licenses/",
", k=2.49 # # by <NAME>, Univ. Basel, Switzerland, January 2010 # June",
"is free software: you can redistribute it and/or # modify it under the",
"(kstr, kvar) = kstr.split('=', 2) if (kstr.strip() != 'k'): raise ValueError k =",
"more details. # # You should have received a copy of the GNU",
"else: (reactstr, kstr) = line.split(',', 2) reactstr = reactstr.strip() (kstr, kvar) = kstr.split('=',",
"of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU",
"open and parse input file fname \"\"\" reactions = None try: infd =",
"GNU General Public License for more details. # # You should have received",
"line[0] != '#'): reaction = self.parse_line(line) reactions.add(reaction) return reactions def parse_stdin( self ):",
"\"\"\" parse standard input (stdin) \"\"\" return self.parse_input(sys.stdin) def parse_file( self, fname ):",
"e.g. [ 'a', '2 fox', '4 b1' ] \"\"\" newmols = Multiset() for",
"input file \"\"\" reactions = ReactionQueue() for line in infile.readlines(): line = line.strip()",
"= line.strip() if (line != '' and line[0] != '#'): reaction = self.parse_line(line)",
"- # # Copyright (C) 2015 <NAME> # Contact: http://www.artificial-chemistries.org/ # # This",
"Basel, Switzerland, January 2010 # June 2013: adapted to the PyCellChemistry package #",
"2015 <NAME> # Contact: http://www.artificial-chemistries.org/ # # This file is part of PyCellChemistry.",
"distributed in the hope that it will be useful, # but WITHOUT ANY",
"'2 fox', '4 b1' ] \"\"\" newmols = Multiset() for mol in mollist:",
"the GNU General Public License # along with PyCellChemistry, see file COPYING. If",
"', 2) name = name.strip() n = int(num) if n > 0 and",
"(line != '' and line[0] != '#'): reaction = self.parse_line(line) reactions.add(reaction) return reactions",
"mol = mol.strip() if mol.find(' ') < 0: name = mol n =",
"given as a list of strings containing the molecule name and an optional",
"line. 'infile' is the file descriptor for the open input file \"\"\" reactions",
"reactions = ReactionQueue() for line in infile.readlines(): line = line.strip() if (line !=",
"= Reaction(edmset, prmset, k) return newreaction def parse_input( self, infile ): \"\"\" parse",
"mol.split(' ', 2) name = name.strip() n = int(num) if n > 0",
"name) = mol.split(' ', 2) name = name.strip() n = int(num) if n",
"in mollist: mol = mol.strip() if mol.find(' ') < 0: name = mol",
"from Multiset import * from Reaction import * class ReactionParser(): def parse_molecules( self,",
"k) return newreaction def parse_input( self, infile ): \"\"\" parse input file containing",
"for the open input file \"\"\" reactions = ReactionQueue() for line in infile.readlines():",
"free software: you can redistribute it and/or # modify it under the terms",
"PARTICULAR PURPOSE. See the # GNU General Public License for more details. #",
"self, mollist ): \"\"\" parse educt or product multiset given as a list",
"terms of the GNU General Public License # version 3, as published by",
"# # ReactionParser.py: parser for chemical reactions in text format, such as: #",
"Foundation. # # PyCellChemistry is distributed in the hope that it will be",
"hope that it will be useful, # but WITHOUT ANY WARRANTY; without even",
"1 else: (num, name) = mol.split(' ', 2) name = name.strip() n =",
"k = float(kvar) (educts, products) = reactstr.split('-->', 2) edlist = educts.split('+') prlist =",
"b1' ] \"\"\" newmols = Multiset() for mol in mollist: mol = mol.strip()",
"# skip comments line = line2[0] try: if line.find(',') < 0: reactstr =",
"January 2010 # June 2013: adapted to the PyCellChemistry package # # -",
"'r') reactions = self.parse_input(infd) infd.close() except IOError: print >> sys.stderr, \"Error opening file\",",
"as published by the Free Software Foundation. # # PyCellChemistry is distributed in",
"2010 # June 2013: adapted to the PyCellChemistry package # # - -",
"(kstr.strip() != 'k'): raise ValueError k = float(kvar) (educts, products) = reactstr.split('-->', 2)",
"= reactstr.split('-->', 2) edlist = educts.split('+') prlist = products.split('+') edmset = ReactionParser.parse_molecules( self,",
"# # This file is part of PyCellChemistry. # # PyCellChemistry is free",
"This file is part of PyCellChemistry. # # PyCellChemistry is free software: you",
"useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #",
"name and an optional stoichiometric coefficient, e.g. [ 'a', '2 fox', '4 b1'",
"# This file is part of PyCellChemistry. # # PyCellChemistry is free software:",
"reactions = self.parse_input(infd) infd.close() except IOError: print >> sys.stderr, \"Error opening file\", fname",
"as a list of strings containing the molecule name and an optional stoichiometric",
"prlist ) except ValueError: print >> sys.stderr, \"syntax error on line=\", line exit(-1)",
"by the Free Software Foundation. # # PyCellChemistry is distributed in the hope",
"infile ): \"\"\" parse input file containing multiple chemical reactions, one per line.",
"\"\"\" parse educt or product multiset given as a list of strings containing",
"even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"= None try: infd = open(fname, 'r') reactions = self.parse_input(infd) infd.close() except IOError:",
"C , k=2.49 # # by <NAME>, Univ. Basel, Switzerland, January 2010 #",
"= line2[0] try: if line.find(',') < 0: reactstr = line k = 1.0",
"(educts, products) = reactstr.split('-->', 2) edlist = educts.split('+') prlist = products.split('+') edmset =",
"text format, such as: # # A + 2 B --> 3 C",
"# # A + 2 B --> 3 C , k=2.49 # #",
"products) = reactstr.split('-->', 2) edlist = educts.split('+') prlist = products.split('+') edmset = ReactionParser.parse_molecules(",
"Copyright (C) 2015 <NAME> # Contact: http://www.artificial-chemistries.org/ # # This file is part",
"COPYING. If not, see # http://www.gnu.org/licenses/ # import sys from Multiset import *",
"kvar) = kstr.split('=', 2) if (kstr.strip() != 'k'): raise ValueError k = float(kvar)",
"the terms of the GNU General Public License # version 3, as published",
"be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of",
"return reactions def parse_stdin( self ): \"\"\" parse standard input (stdin) \"\"\" return",
"n = 1 else: (num, name) = mol.split(' ', 2) name = name.strip()",
"can redistribute it and/or # modify it under the terms of the GNU",
"or product multiset given as a list of strings containing the molecule name",
"newmols = Multiset() for mol in mollist: mol = mol.strip() if mol.find(' ')",
"line = line2[0] try: if line.find(',') < 0: reactstr = line k =",
"reactstr.strip() (kstr, kvar) = kstr.split('=', 2) if (kstr.strip() != 'k'): raise ValueError k",
"prmset.empty()): return newreaction = Reaction(edmset, prmset, k) return newreaction def parse_input( self, infile",
"is distributed in the hope that it will be useful, # but WITHOUT",
"mol n = 1 else: (num, name) = mol.split(' ', 2) name =",
"n = int(num) if n > 0 and name != '': newmols.inject(name, n)",
"per line. 'infile' is the file descriptor for the open input file \"\"\"",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public",
"if (edmset.empty() and prmset.empty()): return newreaction = Reaction(edmset, prmset, k) return newreaction def",
"infile.readlines(): line = line.strip() if (line != '' and line[0] != '#'): reaction",
"not, see # http://www.gnu.org/licenses/ # import sys from Multiset import * from Reaction",
"line in infile.readlines(): line = line.strip() if (line != '' and line[0] !=",
"in the hope that it will be useful, # but WITHOUT ANY WARRANTY;",
"infd.close() except IOError: print >> sys.stderr, \"Error opening file\", fname exit(-1) return reactions",
"def parse_molecules( self, mollist ): \"\"\" parse educt or product multiset given as",
"int(num) if n > 0 and name != '': newmols.inject(name, n) return newmols",
"error on line=\", line exit(-1) if (edmset.empty() and prmset.empty()): return newreaction = Reaction(edmset,",
"FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for",
"\"\"\" line2 = line.split('#') # skip comments line = line2[0] try: if line.find(',')",
"from Reaction import * class ReactionParser(): def parse_molecules( self, mollist ): \"\"\" parse",
"parse input file containing multiple chemical reactions, one per line. 'infile' is the",
"Switzerland, January 2010 # June 2013: adapted to the PyCellChemistry package # #",
"infd = open(fname, 'r') reactions = self.parse_input(infd) infd.close() except IOError: print >> sys.stderr,",
"copy of the GNU General Public License # along with PyCellChemistry, see file",
"= line k = 1.0 else: (reactstr, kstr) = line.split(',', 2) reactstr =",
"parse educt or product multiset given as a list of strings containing the",
"newreaction def parse_input( self, infile ): \"\"\" parse input file containing multiple chemical",
"software: you can redistribute it and/or # modify it under the terms of",
"molecule name and an optional stoichiometric coefficient, e.g. [ 'a', '2 fox', '4",
"\"\"\" reactions = None try: infd = open(fname, 'r') reactions = self.parse_input(infd) infd.close()",
"optional stoichiometric coefficient, e.g. [ 'a', '2 fox', '4 b1' ] \"\"\" newmols",
"# PyCellChemistry is distributed in the hope that it will be useful, #",
"version 3, as published by the Free Software Foundation. # # PyCellChemistry is",
"# # by <NAME>, Univ. Basel, Switzerland, January 2010 # June 2013: adapted",
"PyCellChemistry package # # - - - - - - - - -",
"): \"\"\" parse string containing chemical reaction \"\"\" line2 = line.split('#') # skip",
"newreaction = Reaction(edmset, prmset, k) return newreaction def parse_input( self, infile ): \"\"\"",
"print >> sys.stderr, \"syntax error on line=\", line exit(-1) if (edmset.empty() and prmset.empty()):",
"License # version 3, as published by the Free Software Foundation. # #",
"an optional stoichiometric coefficient, e.g. [ 'a', '2 fox', '4 b1' ] \"\"\"",
"0: name = mol n = 1 else: (num, name) = mol.split(' ',",
"B --> 3 C , k=2.49 # # by <NAME>, Univ. Basel, Switzerland,",
"# import sys from Multiset import * from Reaction import * class ReactionParser():",
"Multiset import * from Reaction import * class ReactionParser(): def parse_molecules( self, mollist",
"stoichiometric coefficient, e.g. [ 'a', '2 fox', '4 b1' ] \"\"\" newmols =",
"redistribute it and/or # modify it under the terms of the GNU General",
"#--------------------------------------------------------------------------- # # ReactionParser.py: parser for chemical reactions in text format, such as:",
"but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or",
"edmset = ReactionParser.parse_molecules( self, edlist ) prmset = ReactionParser.parse_molecules( self, prlist ) except",
"coefficient, e.g. [ 'a', '2 fox', '4 b1' ] \"\"\" newmols = Multiset()",
"Multiset() for mol in mollist: mol = mol.strip() if mol.find(' ') < 0:",
"* from Reaction import * class ReactionParser(): def parse_molecules( self, mollist ): \"\"\"",
"open(fname, 'r') reactions = self.parse_input(infd) infd.close() except IOError: print >> sys.stderr, \"Error opening",
"string containing chemical reaction \"\"\" line2 = line.split('#') # skip comments line =",
"- - # # Copyright (C) 2015 <NAME> # Contact: http://www.artificial-chemistries.org/ # #",
"reactstr = line k = 1.0 else: (reactstr, kstr) = line.split(',', 2) reactstr",
"kstr.split('=', 2) if (kstr.strip() != 'k'): raise ValueError k = float(kvar) (educts, products)",
"mollist ): \"\"\" parse educt or product multiset given as a list of",
"in text format, such as: # # A + 2 B --> 3",
"< 0: reactstr = line k = 1.0 else: (reactstr, kstr) = line.split(',',",
"PyCellChemistry, see file COPYING. If not, see # http://www.gnu.org/licenses/ # import sys from",
"# version 3, as published by the Free Software Foundation. # # PyCellChemistry",
"such as: # # A + 2 B --> 3 C , k=2.49",
"n > 0 and name != '': newmols.inject(name, n) return newmols def parse_line(",
"edlist ) prmset = ReactionParser.parse_molecules( self, prlist ) except ValueError: print >> sys.stderr,",
"General Public License # along with PyCellChemistry, see file COPYING. If not, see",
"PyCellChemistry is distributed in the hope that it will be useful, # but",
"chemical reactions in text format, such as: # # A + 2 B",
"License for more details. # # You should have received a copy of",
"# PyCellChemistry is free software: you can redistribute it and/or # modify it",
"mol in mollist: mol = mol.strip() if mol.find(' ') < 0: name =",
"and name != '': newmols.inject(name, n) return newmols def parse_line( self, line ):",
"# # Copyright (C) 2015 <NAME> # Contact: http://www.artificial-chemistries.org/ # # This file",
"return newreaction = Reaction(edmset, prmset, k) return newreaction def parse_input( self, infile ):",
"mol.strip() if mol.find(' ') < 0: name = mol n = 1 else:",
"and line[0] != '#'): reaction = self.parse_line(line) reactions.add(reaction) return reactions def parse_stdin( self",
"line2[0] try: if line.find(',') < 0: reactstr = line k = 1.0 else:",
"\"\"\" newmols = Multiset() for mol in mollist: mol = mol.strip() if mol.find('",
"# Contact: http://www.artificial-chemistries.org/ # # This file is part of PyCellChemistry. # #",
"): \"\"\" parse standard input (stdin) \"\"\" return self.parse_input(sys.stdin) def parse_file( self, fname",
"if mol.find(' ') < 0: name = mol n = 1 else: (num,",
"def parse_line( self, line ): \"\"\" parse string containing chemical reaction \"\"\" line2",
") prmset = ReactionParser.parse_molecules( self, prlist ) except ValueError: print >> sys.stderr, \"syntax",
"# June 2013: adapted to the PyCellChemistry package # # - - -",
"in infile.readlines(): line = line.strip() if (line != '' and line[0] != '#'):",
"ReactionParser.py: parser for chemical reactions in text format, such as: # # A",
"= kstr.split('=', 2) if (kstr.strip() != 'k'): raise ValueError k = float(kvar) (educts,",
"mollist: mol = mol.strip() if mol.find(' ') < 0: name = mol n",
"ReactionParser.parse_molecules( self, prlist ) except ValueError: print >> sys.stderr, \"syntax error on line=\",",
"2) reactstr = reactstr.strip() (kstr, kvar) = kstr.split('=', 2) if (kstr.strip() != 'k'):",
"See the # GNU General Public License for more details. # # You",
"else: (num, name) = mol.split(' ', 2) name = name.strip() n = int(num)",
"= educts.split('+') prlist = products.split('+') edmset = ReactionParser.parse_molecules( self, edlist ) prmset =",
"import * from Reaction import * class ReactionParser(): def parse_molecules( self, mollist ):",
"products.split('+') edmset = ReactionParser.parse_molecules( self, edlist ) prmset = ReactionParser.parse_molecules( self, prlist )",
"and an optional stoichiometric coefficient, e.g. [ 'a', '2 fox', '4 b1' ]",
"the file descriptor for the open input file \"\"\" reactions = ReactionQueue() for",
"see file COPYING. If not, see # http://www.gnu.org/licenses/ # import sys from Multiset",
"# # PyCellChemistry is free software: you can redistribute it and/or # modify",
"3 C , k=2.49 # # by <NAME>, Univ. Basel, Switzerland, January 2010",
"newmols.inject(name, n) return newmols def parse_line( self, line ): \"\"\" parse string containing",
"containing multiple chemical reactions, one per line. 'infile' is the file descriptor for",
"return newmols def parse_line( self, line ): \"\"\" parse string containing chemical reaction",
"package # # - - - - - - - - - -",
"name.strip() n = int(num) if n > 0 and name != '': newmols.inject(name,",
"a list of strings containing the molecule name and an optional stoichiometric coefficient,",
"under the terms of the GNU General Public License # version 3, as",
"self, fname ): \"\"\" open and parse input file fname \"\"\" reactions =",
"for line in infile.readlines(): line = line.strip() if (line != '' and line[0]",
"PyCellChemistry is free software: you can redistribute it and/or # modify it under",
"reaction \"\"\" line2 = line.split('#') # skip comments line = line2[0] try: if",
"\"\"\" open and parse input file fname \"\"\" reactions = None try: infd",
"comments line = line2[0] try: if line.find(',') < 0: reactstr = line k",
"it under the terms of the GNU General Public License # version 3,",
"= self.parse_input(infd) infd.close() except IOError: print >> sys.stderr, \"Error opening file\", fname exit(-1)",
"strings containing the molecule name and an optional stoichiometric coefficient, e.g. [ 'a',",
"raise ValueError k = float(kvar) (educts, products) = reactstr.split('-->', 2) edlist = educts.split('+')",
"ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR",
"you can redistribute it and/or # modify it under the terms of the",
"* class ReactionParser(): def parse_molecules( self, mollist ): \"\"\" parse educt or product",
"= mol.split(' ', 2) name = name.strip() n = int(num) if n >",
"parse standard input (stdin) \"\"\" return self.parse_input(sys.stdin) def parse_file( self, fname ): \"\"\"",
"adapted to the PyCellChemistry package # # - - - - - -",
"A + 2 B --> 3 C , k=2.49 # # by <NAME>,",
"# # - - - - - - - - - - -",
"as: # # A + 2 B --> 3 C , k=2.49 #",
"chemical reactions, one per line. 'infile' is the file descriptor for the open",
"WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS",
"2) if (kstr.strip() != 'k'): raise ValueError k = float(kvar) (educts, products) =",
"# # You should have received a copy of the GNU General Public",
"Public License # along with PyCellChemistry, see file COPYING. If not, see #",
"standard input (stdin) \"\"\" return self.parse_input(sys.stdin) def parse_file( self, fname ): \"\"\" open",
"Univ. Basel, Switzerland, January 2010 # June 2013: adapted to the PyCellChemistry package",
"FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more",
"= open(fname, 'r') reactions = self.parse_input(infd) infd.close() except IOError: print >> sys.stderr, \"Error",
"have received a copy of the GNU General Public License # along with",
"parse_input( self, infile ): \"\"\" parse input file containing multiple chemical reactions, one",
"Public License for more details. # # You should have received a copy",
"- - - - # # Copyright (C) 2015 <NAME> # Contact: http://www.artificial-chemistries.org/",
"Free Software Foundation. # # PyCellChemistry is distributed in the hope that it",
"the GNU General Public License # version 3, as published by the Free",
"= ReactionParser.parse_molecules( self, edlist ) prmset = ReactionParser.parse_molecules( self, prlist ) except ValueError:",
"2 B --> 3 C , k=2.49 # # by <NAME>, Univ. Basel,",
"file descriptor for the open input file \"\"\" reactions = ReactionQueue() for line",
"modify it under the terms of the GNU General Public License # version",
"parse_stdin( self ): \"\"\" parse standard input (stdin) \"\"\" return self.parse_input(sys.stdin) def parse_file(",
"= mol.strip() if mol.find(' ') < 0: name = mol n = 1",
"ReactionQueue() for line in infile.readlines(): line = line.strip() if (line != '' and",
"] \"\"\" newmols = Multiset() for mol in mollist: mol = mol.strip() if",
"3, as published by the Free Software Foundation. # # PyCellChemistry is distributed",
"k=2.49 # # by <NAME>, Univ. Basel, Switzerland, January 2010 # June 2013:",
"edlist = educts.split('+') prlist = products.split('+') edmset = ReactionParser.parse_molecules( self, edlist ) prmset",
"with PyCellChemistry, see file COPYING. If not, see # http://www.gnu.org/licenses/ # import sys",
") except ValueError: print >> sys.stderr, \"syntax error on line=\", line exit(-1) if",
"reactions def parse_stdin( self ): \"\"\" parse standard input (stdin) \"\"\" return self.parse_input(sys.stdin)",
"Software Foundation. # # PyCellChemistry is distributed in the hope that it will",
"will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty",
"- - - - - - - - # # Copyright (C) 2015",
"name = name.strip() n = int(num) if n > 0 and name !=",
"the molecule name and an optional stoichiometric coefficient, e.g. [ 'a', '2 fox',",
"= line.split(',', 2) reactstr = reactstr.strip() (kstr, kvar) = kstr.split('=', 2) if (kstr.strip()",
"= reactstr.strip() (kstr, kvar) = kstr.split('=', 2) if (kstr.strip() != 'k'): raise ValueError",
"self.parse_input(infd) infd.close() except IOError: print >> sys.stderr, \"Error opening file\", fname exit(-1) return",
"name != '': newmols.inject(name, n) return newmols def parse_line( self, line ): \"\"\"",
"prmset = ReactionParser.parse_molecules( self, prlist ) except ValueError: print >> sys.stderr, \"syntax error",
"def parse_file( self, fname ): \"\"\" open and parse input file fname \"\"\"",
"= Multiset() for mol in mollist: mol = mol.strip() if mol.find(' ') <",
"= self.parse_line(line) reactions.add(reaction) return reactions def parse_stdin( self ): \"\"\" parse standard input",
"# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY",
"'k'): raise ValueError k = float(kvar) (educts, products) = reactstr.split('-->', 2) edlist =",
"self, edlist ) prmset = ReactionParser.parse_molecules( self, prlist ) except ValueError: print >>",
"reactions, one per line. 'infile' is the file descriptor for the open input",
"self, prlist ) except ValueError: print >> sys.stderr, \"syntax error on line=\", line",
"if n > 0 and name != '': newmols.inject(name, n) return newmols def",
"'infile' is the file descriptor for the open input file \"\"\" reactions ="
] |
[
"sum([word not in word2id for word in vocab]) invalid_num = sum([word not in",
"3, 0, 0], # second post: <go> hello <eos> <pad> <pad> ]), \"resp_allvocabs\":",
"a dict, its value must be a list(or tuple) of lists(or tuples).') elif",
"text and returns the next label(integer). Note that it may raise StopIteration. Args:{DataField.GET_NEXT_ARG}",
"%s.txt contains different numbers of fields\" % key) vocab = chain_allvocab(origin_data[key], data_fields[key]) vocab_num",
"used if a word is not valid. Size: ``[batch_size, max(sent_length)]`` * **post_allvocabs** (:class:`numpy.ndarray`):",
"\\ self._min_vocab_times, self._max_sent_length, None, self._invalid_vocab_times) def _general_load_data(self, file_path, data_fields, min_vocab_times, max_sent_length, max_turn_length, invalid_vocab_times):",
"``[batch_size, max(sent_length)]`` Examples: >>> # all_vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\",",
"# different runs vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab =",
"sent_num else: max_turn_length_before_cut = 1 cut_sentence_rate = 0 print((\"%s set. invalid rate: %f,",
"first response: <go> i am fine <eos> [2, 7, 3, 0, 0], #",
"set only contains sessions. min_vocab_times (int): A cut-off threshold of valid tokens. All",
"valid_vocab_len = len(vocab_list) valid_vocab_set = set(vocab_list) for key in self.key_name: if key ==",
"numpy.array([5, 3]), # length of posts \"resp_length\": numpy.array([5, 3]), # length of responses",
"= set(vocab_list) for key in self.key_name: if key == 'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key]))",
">= min_vocab_times] vocab_list = self.ext_vocab + list(left_vocab) valid_vocab_len = len(vocab_list) valid_vocab_set = set(vocab_list)",
"label2, ...]} If it's a dict, different datasets may have different formats.(If `data_fields`",
"self.ext_vocab):valid_vocab_len]) self.__hash_value = hash_value return vocab_list, valid_vocab_len, data, data_size def get_batch(self, key, indexes):",
"in enumerate(vocab_list)} data = {} data_size = {} for key in self.key_name: data[key]",
"raise TypeError('If `data_field` is a dict, its value must be a list(or tuple)",
"not valid. Size: ``[batch_size, max(sent_length)]`` * **post_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing",
"response: <go> hello <eos> <pad> <pad> ]), \"post_length\": numpy.array([5, 3]), # length of",
"An element of a dataset. convert_ids_to_tokens: It's useless. This argument exists, just to",
"max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital ): super().__init__(file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer,",
"formats.(If `data_fields` is a list or a tuple, different datasets have the same",
"will be regarded as valid vocabs, while ``vocab_list[valid_vocab_len:]`` regarded as invalid vocabs. *",
"(:class:`numpy.ndarray`): A 1-d array, the length of post in each batch. Size: ``[batch_size]``",
"the same as self.key_name('train', 'test', 'dev', etc.). Each value is # a list(tuple)",
"special_tokens = set(self.ext_vocab) origin_data = {} for key in self.key_name: origin_data[key] = {data_key:",
"res = {} batch_size = len(indexes) res[\"post_length\"] = np.array(list(map(lambda i: len(self.data[key]['post'][i]), indexes)), dtype=int)",
"test set only contains sessions. min_vocab_times (int): A cut-off threshold of valid tokens.",
"\"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", >>> # \"hello\", \"i\", \"am\", \"fine\"] >>>",
"# vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", \"hello\", \"i\"] >>>",
"rate: %f\\n\\tmax turn length before cut: %d, cut sentence rate: %f\") % \\",
"sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab = [x[0] for x in vocab",
"no data fields for dataset(%s) ' % ', '.join(no_field_keys)) try: data_fields = {key:",
">= self.valid_vocab_len] = self.unk_id if key=='train': res['score']=np.array([self.data[key]['score'][i] for i in indexes]) return res",
"DataField(in this case, its instance will be used, assuming its constructor accepts no",
"numpy.array([ [2, 5, 6, 10, 3], # first post: <go> are you fine",
"session2, ...], 'key2': [label1, label2, ...]} If it's a dict, different datasets may",
"origin_data[key][data_key]] if key not in data_size: data_size[key] = len(data[key][data_key]) elif data_size[key] != len(data[key][data_key]):",
"tokens. All tokens appear not less than `min_vocab_times` in **training set** will be",
"**post_length** (:class:`numpy.ndarray`): A 1-d array, the length of post in each batch. Size:",
"session_keys)))) max_turn_length_before_cut = max(turn_length) sent_num = sum(turn_length) cut_sentence_rate = np.sum(np.maximum(np.array(turn_length) - max_turn_length, 0))",
"key not in data_fields] if no_field_keys: raise ValueError('There is no data fields for",
"= sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab = [x[0] for x in",
"'dev': [['post', 'Sentence'], ['resp', 'Sentence']], 'test': [['post', 'Sentence'], ['resp', 'Sentence']], } return self._general_load_data(self._file_path,",
"form in posts. Provide both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` *",
"enumerate(indexes): post = self.data[key]['post'][j] resp = self.data[key]['resp'][j] res_post[i, :len(post)] = post res_resp[i, :len(resp)]",
"for token in field.iter_tokens(element): if token in special_tokens: raise RuntimeError( 'The dataset contains",
"in session_keys)))) max_turn_length_before_cut = max(turn_length) sent_num = sum(turn_length) cut_sentence_rate = np.sum(np.maximum(np.array(turn_length) - max_turn_length,",
"file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital ): super().__init__(file_id, min_vocab_times, \\ max_sent_length,",
"for key in self.key_name} except AssertionError: raise TypeError('If `data_field` is a dict, its",
"valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` Examples: >>> # all_vocab_list = [\"<pad>\",",
"array containing words of id form in posts. Provide both valid and invalid",
"lines* is a session, *followed by an empty line*, and the next line",
"def get_next(self, dataset): r\"\"\"read text and returns the next label(integer). Note that it",
"= res[\"resp\"] = np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int) for i, j in enumerate(indexes): post =",
"the element itself. Args: element: An element of a dataset. convert_ids_to_tokens: It's useless.",
"len(vocab_list)) word2id = {w: i for i, w in enumerate(vocab_list)} data = {}",
"sentences longer than ``max_sent_length`` will be shortened to first ``max_sent_length`` tokens. max_turn_length (int):",
"'dev', etc.). Each value is # a list(tuple) of lists(tuples), which means (data_key(str),",
"padded array containing words of id form in posts. Only provide valid words.",
"same format). Its keys are the same as `self.key_name` that indicate the datasets,",
"unknown rate: %f, max sentence length before cut: %d, \" + \\ \"cut",
"train set contains sessions and labels, but the test set only contains sessions.",
"\"how\", \"are\", \"you\", >>> # \"hello\", \"i\", \"am\", \"fine\"] >>> # vocab_size =",
"least contains: * **post_length** (:class:`numpy.ndarray`): A 1-d array, the length of post in",
"<eos> <pad> <pad> ]), \"resp\": numpy.array([ [2, 8, 1, 1, 3], # first",
"# second response: <go> hello <eos> <pad> <pad> ]), \"resp\": numpy.array([ [2, 8,",
"self.__hash_value = hash_value return vocab_list, valid_vocab_len, data, data_size def get_batch(self, key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS}",
"max_turn_length_before_cut = 1 cut_sentence_rate = 0 print((\"%s set. invalid rate: %f, unknown rate:",
"cut: %d, cut sentence rate: %f\") % \\ (key, invalid_num / vocab_num, oov_num",
"max_turn_length, 0)) / sent_num else: max_turn_length_before_cut = 1 cut_sentence_rate = 0 print((\"%s set.",
"self.data[key]['post'][j] resp = self.data[key]['resp'][j] res_post[i, :len(post)] = post res_resp[i, :len(resp)] = resp res[\"post_allvocabs\"]",
"word in vocab]) - oov_num sent_length = [] for data_key, field in data_fields[key]:",
"in the raw file, the first *several lines* is a session, *followed by",
"valid_vocab_len, data, data_size def get_batch(self, key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict): A dict at",
"the path of dataset. data_fields (dict, list, tuple): If it's a list(tuple), it",
"chain_allvocab(origin_data['train'], data_fields['train']) # Important: Sort the words preventing the index changes between #",
"<eos> [2, 7, 3, 0, 0], # second response: <go> hello <eos> <pad>",
"in special_tokens: raise RuntimeError( 'The dataset contains special token \"%s\". This is not",
"in fields] if isinstance(data_fields, dict): no_field_keys = [key for key in self.key_name if",
"max_turn_length=max_turn_length) for element in origin_data[key][data_key]] if key not in data_size: data_size[key] = len(data[key][data_key])",
"post: <go> hello <eos> <pad> <pad> ]), \"resp_allvocabs\": numpy.array([ [2, 8, 9, 10,",
"len(vocab_list) valid_vocab_set = set(vocab_list) for key in self.key_name: if key == 'train': continue",
"vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value = hash_value return vocab_list, valid_vocab_len, data, data_size def get_batch(self, key,",
"field.get_next(dataset) 1 >>> field.get_next(dataset) 0 \"\"\" score = next(dataset) return float(score.strip()) def _map_fun(self,",
"j in enumerate(indexes): post = self.data[key]['post'][j] resp = self.data[key]['resp'][j] res_post[i, :len(post)] = post",
"# Note, different dataset may have different fields. special_tokens = set(self.ext_vocab) origin_data =",
"length of posts \"resp_length\": numpy.array([5, 3]), # length of responses } ''' if",
"not in word2id for word in vocab]) invalid_num = sum([word not in valid_vocab_set",
"TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def __init__(self, file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital ):",
"if key not in self.key_name: raise ValueError(\"No set named %s.\" % key) res",
"StopIteration. Args:{DataField.GET_NEXT_ARG} Examples: >>> dataset = iter([\"1\\n\", \"0\\n\"]) >>> field = Label() >>>",
"valid vocab. ``vocab_list[:valid_vocab_len]`` will be regarded as valid vocabs, while ``vocab_list[valid_vocab_len:]`` regarded as",
"vocab list length = %d\" % valid_vocab_len) print(\"vocab list length = %d\" %",
"length of responses } ''' if key not in self.key_name: raise ValueError(\"No set",
"the values are lists as mentioned above. For example, data_fields = {'train': [['sess',",
"map(len, chain.from_iterable((origin_data[key][sess_key] for sess_key in session_keys)))) max_turn_length_before_cut = max(turn_length) sent_num = sum(turn_length) cut_sentence_rate",
"{'key1': [session1, session2, ...], 'key2': [label1, label2, ...]} If it's a dict, different",
"[len(sent) for element in origin_data[key][data_key] for sent in field.iter_sentence(element)]) cut_word_num = np.sum(np.maximum(np.array(sent_length) -",
"['label', Label()]]}. # Note, different dataset may have different fields. special_tokens = set(self.ext_vocab)",
"[2, 8, 1, 1, 3], # first response: <go> i <unk> <unk> <eos>",
"if isinstance(data_fields, dict): no_field_keys = [key for key in self.key_name if key not",
"# second response: <go> hello <eos> <pad> <pad> ]), \"post_length\": numpy.array([5, 3]), #",
"Size: ``[batch_size]`` * **resp** (:class:`numpy.ndarray`): A 2-d padded array containing words of id",
"= resp res[\"post_allvocabs\"] = res_post.copy() res[\"resp_allvocabs\"] = res_resp.copy() res_post[res_post >= self.valid_vocab_len] = self.unk_id",
"<unk> <eos> [2, 7, 3, 0, 0], # second response: <go> hello <eos>",
"in indexes]) return res def main(): max_sent_length = 50 loader = TranslationWithScore('./data/iwslt14_raml', 10,",
"responses. Only provide valid vocabs. ``unk_id`` will be used if a word is",
"ignored. invalid_vocab_times (int): A cut-off threshold of invalid tokens. All tokens appear not",
"if token in special_tokens: raise RuntimeError( 'The dataset contains special token \"%s\". This",
"= [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", \"hello\", \"i\"] >>> dataloader.get_batch('train', [0,",
"for element in origin_data[key][data_key]] data[key][data_key] = [ field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length) for element in",
"isinstance(data_fields, dict): no_field_keys = [key for key in self.key_name if key not in",
"[x[0] for x in vocab if x[1] >= invalid_vocab_times and x[0] not in",
"element in origin_data[key][data_key] for sent in field.iter_sentence(element)]) cut_word_num = np.sum(np.maximum(np.array(sent_length) - max_sent_length, 0))",
"if a word is not valid. Size: ``[batch_size, max(sent_length)]`` * **resp_allvocabs** (:class:`numpy.ndarray`): A",
"first *several lines* is a session, *followed by an empty line*, and the",
"as self.key_name('train', 'test', 'dev', etc.). Each value is # a list(tuple) of lists(tuples),",
"origin_data[key] = {data_key: [] for data_key, _ in data_fields[key]} with open(\"%s/%s.txt\" % (file_path,",
">= self.valid_vocab_len] = self.unk_id res_resp[res_resp >= self.valid_vocab_len] = self.unk_id if key=='train': res['score']=np.array([self.data[key]['score'][i] for",
"the same as that of super class. \"\"\" return element class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader",
"less than `min_vocab_times` in **training set** will be marked as valid words. max_sent_length",
"valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid vocab list length = %d\" % valid_vocab_len) print(\"vocab list length",
"pairs. Field must be a DataField instance, or a subclass of DataField(in this",
"% key) vocab = chain_allvocab(origin_data[key], data_fields[key]) vocab_num = len(vocab) oov_num = sum([word not",
"fine <eos> [2, 7, 3, 0, 0], # second post: <go> hello <eos>",
"token in field.iter_tokens(element): if token in special_tokens: raise RuntimeError( 'The dataset contains special",
"rate: %f\") % \\ (key, invalid_num / vocab_num, oov_num / vocab_num, max(sent_length), \\",
"data. ''' def get_fields(fields): assert isinstance(fields, list) or isinstance(fields, tuple) return [(data_key, DataField.get_field(field))",
"now data_fields is a dict. Keys are the same as self.key_name('train', 'test', 'dev',",
"not less than ``invalid_vocab_times`` in the **whole dataset** (except valid words) will be",
"[field.convert_to_ids(element, word2id, self) for element in origin_data[key][data_key]] data[key][data_key] = [ field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length)",
"max_turn_length, invalid_vocab_times): r'''This function implements a general loading process. Arguments: file_path (str): A",
"and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` Examples: >>> # all_vocab_list = [\"<pad>\", \"<unk>\",",
"All sessions, whose turn length is longer than ``max_turn_length`` will be shorten to",
"element = field.convert_to_tokens(field.get_next(f_file), self.tokenize) for token in field.iter_tokens(element): if token in special_tokens: raise",
"- max_turn_length, 0)) / sent_num else: max_turn_length_before_cut = 1 cut_sentence_rate = 0 print((\"%s",
"['score', Score]], 'dev': [['post', 'Sentence'], ['resp', 'Sentence']], 'test': [['post', 'Sentence'], ['resp', 'Sentence']], }",
"cut_sentence_rate = np.sum(np.maximum(np.array(turn_length) - max_turn_length, 0)) / sent_num else: max_turn_length_before_cut = 1 cut_sentence_rate",
"# calculate hash value hash_value = DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len])",
"A 1-d array, the length of response in each batch. Size: ``[batch_size]`` *",
"element: An element of a dataset. convert_ids_to_tokens: It's useless. This argument exists, just",
">>> dataloader.get_batch('train', [0, 1]) { \"post_allvocabs\": numpy.array([ [2, 5, 6, 10, 3], #",
"class, whose __name__ is field, will be used). For example, data_fields=[['post', 'Sentence'], ['label',",
"self.ext_vocab + list(left_vocab) valid_vocab_len = len(vocab_list) valid_vocab_set = set(vocab_list) for key in self.key_name:",
"get_batch(self, key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict): A dict at least contains: * **post_length**",
"a string(in this case, the instance of the class, whose __name__ is field,",
"max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital) def _load_data(self): data_fields = { 'train': [['post', 'Sentence'],",
"dataset contains special token \"%s\". This is not allowed.' % token) origin_data[key][data_key].append(element) except",
"_load_data(self): data_fields = { 'train': [['post', 'Sentence'], ['resp', 'Sentence'], ['score', Score]], 'dev': [['post',",
"3, 0, 0], # second response: <go> hello <eos> <pad> <pad> ]), \"post_length\":",
"for data_key, field in data_fields[key]: origin_data[key][data_key] = [field.convert_to_ids(element, word2id, self) for element in",
"for word in vocab]) invalid_num = sum([word not in valid_vocab_set for word in",
"else: raise TypeError('`data_fields` must be a dict, or a list, or a tuple.')",
"i, j in enumerate(indexes): post = self.data[key]['post'][j] resp = self.data[key]['resp'][j] res_post[i, :len(post)] =",
"elif data_size[key] != len(data[key][data_key]): raise RuntimeError( \"The data of input %s.txt contains different",
"before cut: %d, cut sentence rate: %f\") % \\ (key, invalid_num / vocab_num,",
"[data_key for data_key, field in data_fields[key] if field.__class__ == Session] if session_keys: turn_length",
"Label]] means that, in the raw file, the first line is a sentence",
"resp res[\"post_allvocabs\"] = res_post.copy() res[\"resp_allvocabs\"] = res_resp.copy() res_post[res_post >= self.valid_vocab_len] = self.unk_id res_resp[res_resp",
"length = %d\" % len(vocab_list)) word2id = {w: i for i, w in",
"array, the length of post in each batch. Size: ``[batch_size]`` * **post** (:class:`numpy.ndarray`):",
"= hash_value return vocab_list, valid_vocab_len, data, data_size def get_batch(self, key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns:",
"rate: %f, max sentence length before cut: %d, \" + \\ \"cut word",
"means (data_key(str), data_field(DataField)) pairs. # For example, # data_fields == {'train': [['sent', Sentence()],",
"numpy.array([ [2, 8, 9, 10, 3], # first response: <go> i am fine",
"['resp', 'Sentence']], 'test': [['post', 'Sentence'], ['resp', 'Sentence']], } return self._general_load_data(self._file_path, data_fields, \\ self._min_vocab_times,",
"for model or metrics. Returns: (tuple): containing: * **all_vocab_list** (list): vocabulary list of",
"length before cut: %d, cut sentence rate: %f\") % \\ (key, invalid_num /",
"max(sent_length)]`` * **post_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form",
"dict): no_field_keys = [key for key in self.key_name if key not in data_fields]",
"0, 0], # second response: <go> hello <eos> <pad> <pad> ]), \"post_length\": numpy.array([5,",
"class Score(DataField): def get_next(self, dataset): r\"\"\"read text and returns the next label(integer). Note",
"line*, and the next line is a label. dataset = {'key1': [session1, session2,",
"the datasets, and the values are lists as mentioned above. For example, data_fields",
"_ in data_fields[key]} with open(\"%s/%s.txt\" % (file_path, key), encoding='utf-8') as f_file: while True:",
"regarded as invalid vocabs. * **data** (dict): a dict contains data. * **data_size**",
"valid. Size: ``[batch_size, max(sent_length)]`` * **resp_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words",
"data_fields = { 'train': [['post', 'Sentence'], ['resp', 'Sentence'], ['score', Score]], 'dev': [['post', 'Sentence'],",
"a dict contains size of each item in data. ''' def get_fields(fields): assert",
"{} for key in self.key_name: origin_data[key] = {data_key: [] for data_key, _ in",
"data_fields is a dict. Keys are the same as self.key_name('train', 'test', 'dev', etc.).",
"'''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict): A dict at least contains: * **post_length** (:class:`numpy.ndarray`): A 1-d",
"%d\" % len(vocab_list)) word2id = {w: i for i, w in enumerate(vocab_list)} data",
"For example, # data_fields == {'train': [['sent', Sentence()], ['label', Label()]], # 'test': [['sent',",
"except AssertionError: raise TypeError('If `data_field` is a dict, its value must be a",
"than ``invalid_vocab_times`` in the **whole dataset** (except valid words) will be marked as",
"tuple) return [(data_key, DataField.get_field(field)) for data_key, field in fields] if isinstance(data_fields, dict): no_field_keys",
"\" + \\ \"cut word rate: %f\\n\\tmax turn length before cut: %d, cut",
"* **post** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form in",
"`data_fields` is a list or a tuple, different datasets have the same format).",
"data_key, field in data_fields[key]: sent_length.extend( [len(sent) for element in origin_data[key][data_key] for sent in",
"np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int) res_resp = res[\"resp\"] = np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int) for i, j",
"# first response: <go> i am fine <eos> [2, 7, 3, 0, 0],",
"if session_keys: turn_length = list( map(len, chain.from_iterable((origin_data[key][sess_key] for sess_key in session_keys)))) max_turn_length_before_cut =",
"chain class Score(DataField): def get_next(self, dataset): r\"\"\"read text and returns the next label(integer).",
"[['post', 'Sentence'], ['resp', 'Sentence']], } return self._general_load_data(self._file_path, data_fields, \\ self._min_vocab_times, self._max_sent_length, None, self._invalid_vocab_times)",
"instance, or a subclass of DataField(in this case, its instance will be used,",
"} return self._general_load_data(self._file_path, data_fields, \\ self._min_vocab_times, self._max_sent_length, None, self._invalid_vocab_times) def _general_load_data(self, file_path, data_fields,",
"first line is a sentence and the second line is a label. They",
"= {w: i for i, w in enumerate(vocab_list)} data = {} data_size =",
"sum([word not in valid_vocab_set for word in vocab]) - oov_num sent_length = []",
"<go> are you fine <eos> [2, 7, 3, 0, 0], # second post:",
"<pad> ]), \"post_length\": numpy.array([5, 3]), # length of posts \"resp_length\": numpy.array([5, 3]), #",
"of id form in responses. Only provide valid vocabs. ``unk_id`` will be used",
"(:class:`numpy.ndarray`): A 2-d padded array containing words of id form in posts. Provide",
"= self.data[key]['post'][j] resp = self.data[key]['resp'][j] res_post[i, :len(post)] = post res_resp[i, :len(resp)] = resp",
"A 2-d padded array containing words of id form in responses. Only provide",
"that, in the raw file, the first line is a sentence and the",
"= np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int) for i, j in enumerate(indexes): post = self.data[key]['post'][j] resp",
"fields] if isinstance(data_fields, dict): no_field_keys = [key for key in self.key_name if key",
":len(resp)] = resp res[\"post_allvocabs\"] = res_post.copy() res[\"resp_allvocabs\"] = res_resp.copy() res_post[res_post >= self.valid_vocab_len] =",
"as valid vocabs, while ``vocab_list[valid_vocab_len:]`` regarded as invalid vocabs. * **data** (dict): a",
"\"<eos>\", \"how\", \"are\", \"you\", >>> # \"hello\", \"i\", \"am\", \"fine\"] >>> # vocab_size",
"for key in self.key_name: origin_data[key] = {data_key: [] for data_key, _ in data_fields[key]}",
"Provide both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` * **resp_length** (:class:`numpy.ndarray`): A",
"\\ \"cut word rate: %f\\n\\tmax turn length before cut: %d, cut sentence rate:",
"element class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def __init__(self, file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer,",
"[0, 1]) { \"post_allvocabs\": numpy.array([ [2, 5, 6, 10, 3], # first post:",
"of each item in data. ''' def get_fields(fields): assert isinstance(fields, list) or isinstance(fields,",
"runs vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab = [x[0] for",
"as f_file: while True: try: for data_key, field in data_fields[key]: element = field.convert_to_tokens(field.get_next(f_file),",
"Label()]]}. # Note, different dataset may have different fields. special_tokens = set(self.ext_vocab) origin_data",
"path of dataset. data_fields (dict, list, tuple): If it's a list(tuple), it must",
"0], # second post: <go> hello <eos> <pad> <pad> ]), \"resp_allvocabs\": numpy.array([ [2,",
"]), \"post_length\": numpy.array([5, 3]), # length of posts \"resp_length\": numpy.array([5, 3]), # length",
"by an empty line*, and the next line is a label. dataset =",
"data fields for dataset(%s) ' % ', '.join(no_field_keys)) try: data_fields = {key: get_fields(data_fields[key])",
"(dict): a dict contains data. * **data_size** (dict): a dict contains size of",
"It's useless. This argument exists, just to keep the signature the same as",
"__name__ is field, will be used). For example, data_fields=[['post', 'Sentence'], ['label', Label]] means",
"get_next(self, dataset): r\"\"\"read text and returns the next label(integer). Note that it may",
"it's a list(tuple), it must be a list of (key, field) pairs. Field",
"origin_data[key][data_key]] data[key][data_key] = [ field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length) for element in origin_data[key][data_key]] if key",
"a general loading process. Arguments: file_path (str): A string indicating the path of",
"data_fields = get_fields(data_fields) data_fields = {key: data_fields for key in self.key_name} else: raise",
"in self.key_name if key not in data_fields] if no_field_keys: raise ValueError('There is no",
"``max_turn_length`` sentences. If the dataset don't contains sessions, this parameter will be ignored.",
"return vocabs raw_vocab_list = chain_allvocab(origin_data['train'], data_fields['train']) # Important: Sort the words preventing the",
"* **post_length** (:class:`numpy.ndarray`): A 1-d array, the length of post in each batch.",
"= self.data[key]['resp'][j] res_post[i, :len(post)] = post res_resp[i, :len(resp)] = resp res[\"post_allvocabs\"] = res_post.copy()",
"`min_vocab_times` in **training set** will be marked as valid words. max_sent_length (int): All",
"array containing words of id form in posts. Only provide valid words. ``unk_id``",
"fields: for element in dic[data_key]: vocabs.extend(field.iter_tokens(element)) return vocabs raw_vocab_list = chain_allvocab(origin_data['train'], data_fields['train']) #",
"= res_resp.copy() res_post[res_post >= self.valid_vocab_len] = self.unk_id res_resp[res_resp >= self.valid_vocab_len] = self.unk_id if",
"0 \"\"\" score = next(dataset) return float(score.strip()) def _map_fun(self, element, convert_ids_to_tokens=None): \"\"\" Returns",
"no arguments), or a string(in this case, the instance of the class, whose",
"= {'key1': [session1, session2, ...], 'key2': [label1, label2, ...]} If it's a dict,",
"Label() >>> field.get_next(dataset) 1 >>> field.get_next(dataset) 0 \"\"\" score = next(dataset) return float(score.strip())",
"Examples: >>> # all_vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", >>>",
"mentioned above. For example, data_fields = {'train': [['sess', 'Session'], ['label', 'Label']], 'test': [['sess',",
"self.key_name: origin_data[key] = {data_key: [] for data_key, _ in data_fields[key]} with open(\"%s/%s.txt\" %",
"the first line is a sentence and the second line is a label.",
"constructor accepts no arguments), or a string(in this case, the instance of the",
"sentences. If the dataset don't contains sessions, this parameter will be ignored. invalid_vocab_times",
"a word is not valid. Size: ``[batch_size, max(sent_length)]`` * **post_allvocabs** (:class:`numpy.ndarray`): A 2-d",
"collections import Counter import numpy as np from itertools import chain class Score(DataField):",
"key in self.key_name} else: raise TypeError('`data_fields` must be a dict, or a list,",
"post: <go> are you <unk> <eos> [2, 7, 3, 0, 0], # second",
"% \\ (key, invalid_num / vocab_num, oov_num / vocab_num, max(sent_length), \\ cut_word_num /",
"whose turn length is longer than ``max_turn_length`` will be shorten to first ``max_turn_length``",
"of the class, whose __name__ is field, will be used). For example, data_fields=[['post',",
"the second line is a label. They are saved in a dict. dataset",
"contains size of each item in data. ''' def get_fields(fields): assert isinstance(fields, list)",
"= sum([word not in valid_vocab_set for word in vocab]) - oov_num sent_length =",
"in a dict. dataset = {'post': [line1, line3, line5, ...], 'label': [line2, line4,",
"the test set only contains sessions. min_vocab_times (int): A cut-off threshold of valid",
"batch_size = len(indexes) res[\"post_length\"] = np.array(list(map(lambda i: len(self.data[key]['post'][i]), indexes)), dtype=int) res[\"resp_length\"] = np.array(list(map(lambda",
"are you fine <eos> [2, 7, 3, 0, 0], # second post: <go>",
"sessions, whose turn length is longer than ``max_turn_length`` will be shorten to first",
"ValueError('There is no data fields for dataset(%s) ' % ', '.join(no_field_keys)) try: data_fields",
"tokens. max_turn_length (int): All sessions, whose turn length is longer than ``max_turn_length`` will",
"is longer than ``max_turn_length`` will be shorten to first ``max_turn_length`` sentences. If the",
"including valid and invalid vocabs. * **valid_vocab_len** (int): the number of valid vocab.",
"1-d array, the length of response in each batch. Size: ``[batch_size]`` * **resp**",
"%f\") % \\ (key, invalid_num / vocab_num, oov_num / vocab_num, max(sent_length), \\ cut_word_num",
"contains sessions and labels, but the test set only contains sessions. min_vocab_times (int):",
"len(data[key][data_key]): raise RuntimeError( \"The data of input %s.txt contains different numbers of fields\"",
"- oov_num sent_length = [] for data_key, field in data_fields[key]: sent_length.extend( [len(sent) for",
"2-d padded array containing words of id form in posts. Only provide valid",
"longer than ``max_sent_length`` will be shortened to first ``max_sent_length`` tokens. max_turn_length (int): All",
"x in vocab if x[1] >= min_vocab_times] vocab_list = self.ext_vocab + list(left_vocab) valid_vocab_len",
"1, 3], # first post: <go> are you <unk> <eos> [2, 7, 3,",
"\\ cut_word_num / vocab_num, max_turn_length_before_cut, cut_sentence_rate)) # calculate hash value hash_value = DataloaderHash(ignore_tokens=(self.go_id,",
"(-pair[1], pair[0])) left_vocab = [x[0] for x in vocab if x[1] >= min_vocab_times]",
"same as self.key_name('train', 'test', 'dev', etc.). Each value is # a list(tuple) of",
"Provide both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` Examples: >>> # all_vocab_list",
"[key for key in self.key_name if key not in data_fields] if no_field_keys: raise",
"* **valid_vocab_len** (int): the number of valid vocab. ``vocab_list[:valid_vocab_len]`` will be regarded as",
"self.key_name} else: raise TypeError('`data_fields` must be a dict, or a list, or a",
"= {data_key: [] for data_key, _ in data_fields[key]} with open(\"%s/%s.txt\" % (file_path, key),",
"will be used). For example, data_fields=[['post', 'Sentence'], ['label', Label]] means that, in the",
"if field.__class__ == Session] if session_keys: turn_length = list( map(len, chain.from_iterable((origin_data[key][sess_key] for sess_key",
"np from itertools import chain class Score(DataField): def get_next(self, dataset): r\"\"\"read text and",
"set. invalid rate: %f, unknown rate: %f, max sentence length before cut: %d,",
"for key in self.key_name: data[key] = {} for data_key, field in data_fields[key]: origin_data[key][data_key]",
"ValueError(\"No set named %s.\" % key) res = {} batch_size = len(indexes) res[\"post_length\"]",
"3], # first post: <go> are you <unk> <eos> [2, 7, 3, 0,",
"[(data_key, DataField.get_field(field)) for data_key, field in fields] if isinstance(data_fields, dict): no_field_keys = [key",
"a dict. Keys are the same as self.key_name('train', 'test', 'dev', etc.). Each value",
"for word in vocab]) - oov_num sent_length = [] for data_key, field in",
"just to keep the signature the same as that of super class. \"\"\"",
"in the **whole dataset** (except valid words) will be marked as invalid words.",
"word is not valid. Size: ``[batch_size, max(sent_length)]`` * **resp_allvocabs** (:class:`numpy.ndarray`): A 2-d padded",
"for sess_key in session_keys)))) max_turn_length_before_cut = max(turn_length) sent_num = sum(turn_length) cut_sentence_rate = np.sum(np.maximum(np.array(turn_length)",
"'Sentence']], } return self._general_load_data(self._file_path, data_fields, \\ self._min_vocab_times, self._max_sent_length, None, self._invalid_vocab_times) def _general_load_data(self, file_path,",
"means that the train set contains sessions and labels, but the test set",
"Size: ``[batch_size, max(sent_length)]`` * **resp_length** (:class:`numpy.ndarray`): A 1-d array, the length of response",
"Args:{DataField.GET_NEXT_ARG} Examples: >>> dataset = iter([\"1\\n\", \"0\\n\"]) >>> field = Label() >>> field.get_next(dataset)",
"set** will be marked as valid words. max_sent_length (int): All sentences longer than",
"[line2, line4, line6, ...]} data_fields=[['key1', 'Session'], ['key2', Label()]], means that, in the raw",
"invalid_vocab_times and x[0] not in valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid vocab list length = %d\"",
"%d, \" + \\ \"cut word rate: %f\\n\\tmax turn length before cut: %d,",
"the signature the same as that of super class. \"\"\" return element class",
"% key) res = {} batch_size = len(indexes) res[\"post_length\"] = np.array(list(map(lambda i: len(self.data[key]['post'][i]),",
"tuple, different datasets have the same format). Its keys are the same as",
"' % ', '.join(no_field_keys)) try: data_fields = {key: get_fields(data_fields[key]) for key in self.key_name}",
"get_fields(data_fields) data_fields = {key: data_fields for key in self.key_name} else: raise TypeError('`data_fields` must",
"dict contains size of each item in data. ''' def get_fields(fields): assert isinstance(fields,",
"% token) origin_data[key][data_key].append(element) except StopIteration: break def chain_allvocab(dic, fields): vocabs = [] for",
"0], # second post: <go> hello <eos> <pad> <pad> ]), \"post\": numpy.array([ [2,",
"instance of the class, whose __name__ is field, will be used). For example,",
"cut_sentence_rate)) # calculate hash value hash_value = DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len(",
"may have different fields. special_tokens = set(self.ext_vocab) origin_data = {} for key in",
"word rate: %f\\n\\tmax turn length before cut: %d, cut sentence rate: %f\") %",
"= np.sum(np.maximum(np.array(sent_length) - max_sent_length, 0)) session_keys = [data_key for data_key, field in data_fields[key]",
"_map_fun(self, element, convert_ids_to_tokens=None): \"\"\" Returns the element itself. Args: element: An element of",
"len(data[key][data_key]) elif data_size[key] != len(data[key][data_key]): raise RuntimeError( \"The data of input %s.txt contains",
"hash value hash_value = DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value =",
"file, the first line is a sentence and the second line is a",
">>> # vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", \"hello\", \"i\"]",
"data_size def get_batch(self, key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict): A dict at least contains:",
"isinstance(fields, tuple) return [(data_key, DataField.get_field(field)) for data_key, field in fields] if isinstance(data_fields, dict):",
"less than ``invalid_vocab_times`` in the **whole dataset** (except valid words) will be marked",
"(tuple): containing: * **all_vocab_list** (list): vocabulary list of the datasets, including valid and",
"['label', 'Label']], 'test': [['sess', 'session']]}, means that the train set contains sessions and",
"cotk._utils.file_utils import get_resource_file_path from cotk.dataloader.dataloader import * from collections import Counter import numpy",
"{} for data_key, field in data_fields[key]: origin_data[key][data_key] = [field.convert_to_ids(element, word2id, self) for element",
"res_post[i, :len(post)] = post res_resp[i, :len(resp)] = resp res[\"post_allvocabs\"] = res_post.copy() res[\"resp_allvocabs\"] =",
"will be marked as invalid words. Otherwise, they are unknown words, which are",
"len(self.data[key]['post'][i]), indexes)), dtype=int) res[\"resp_length\"] = np.array(list(map(lambda i: len(self.data[key]['resp'][i]), indexes)), dtype=int) res_post = res[\"post\"]",
"response in each batch. Size: ``[batch_size]`` * **resp** (:class:`numpy.ndarray`): A 2-d padded array",
"general loading process. Arguments: file_path (str): A string indicating the path of dataset.",
"'Session'], ['key2', Label()]], means that, in the raw file, the first *several lines*",
"will be marked as valid words. max_sent_length (int): All sentences longer than ``max_sent_length``",
"first ``max_turn_length`` sentences. If the dataset don't contains sessions, this parameter will be",
"dtype=int) res_post = res[\"post\"] = np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int) res_resp = res[\"resp\"] = np.zeros((batch_size,",
"containing words of id form in responses. Only provide valid vocabs. ``unk_id`` will",
"signature the same as that of super class. \"\"\" return element class TranslationWithScore(cotk.dataloader.SingleTurnDialog):",
"words of id form in responses. Only provide valid vocabs. ``unk_id`` will be",
"%d\" % valid_vocab_len) print(\"vocab list length = %d\" % len(vocab_list)) word2id = {w:",
"while ``vocab_list[valid_vocab_len:]`` regarded as invalid vocabs. * **data** (dict): a dict contains data.",
"a tuple, different datasets have the same format). Its keys are the same",
"be used). For example, data_fields=[['post', 'Sentence'], ['label', Label]] means that, in the raw",
"(dict, list, tuple): If it's a list(tuple), it must be a list of",
"3], # first response: <go> i am fine <eos> [2, 7, 3, 0,",
"self.valid_vocab_len] = self.unk_id if key=='train': res['score']=np.array([self.data[key]['score'][i] for i in indexes]) return res def",
"must be a dict, or a list, or a tuple.') # now data_fields",
"element of a dataset. convert_ids_to_tokens: It's useless. This argument exists, just to keep",
"tokens. All tokens appear not less than ``invalid_vocab_times`` in the **whole dataset** (except",
"list) or isinstance(data_fields, tuple): data_fields = get_fields(data_fields) data_fields = {key: data_fields for key",
"in data_fields[key]: origin_data[key][data_key] = [field.convert_to_ids(element, word2id, self) for element in origin_data[key][data_key]] data[key][data_key] =",
"data_size[key] != len(data[key][data_key]): raise RuntimeError( \"The data of input %s.txt contains different numbers",
"= TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length, 0, 'nltk', False) loader.restart(\"train\",batch_size=2,shuffle=True) q=loader.get_next_batch(\"train\") print(len(q['score'])) print(q) if __name__",
"second post: <go> hello <eos> <pad> <pad> ]), \"post\": numpy.array([ [2, 5, 6,",
"data_key, field in data_fields[key] if field.__class__ == Session] if session_keys: turn_length = list(",
"string indicating the path of dataset. data_fields (dict, list, tuple): If it's a",
"chain_allvocab(origin_data[key], data_fields[key]) vocab_num = len(vocab) oov_num = sum([word not in word2id for word",
"# a list(tuple) of lists(tuples), which means (data_key(str), data_field(DataField)) pairs. # For example,",
"is # a list(tuple) of lists(tuples), which means (data_key(str), data_field(DataField)) pairs. # For",
"vocab_list.extend(left_vocab) print(\"valid vocab list length = %d\" % valid_vocab_len) print(\"vocab list length =",
"(:class:`numpy.ndarray`): A 2-d padded array containing words of id form in responses. Only",
"for data_key, field in data_fields[key]: sent_length.extend( [len(sent) for element in origin_data[key][data_key] for sent",
"# Important: Sort the words preventing the index changes between # different runs",
"self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value = hash_value return vocab_list, valid_vocab_len, data, data_size",
"import Counter import numpy as np from itertools import chain class Score(DataField): def",
"in posts. Provide both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` * **resp_length**",
"second response: <go> hello <eos> <pad> <pad> ]), \"resp\": numpy.array([ [2, 8, 1,",
"len(indexes) res[\"post_length\"] = np.array(list(map(lambda i: len(self.data[key]['post'][i]), indexes)), dtype=int) res[\"resp_length\"] = np.array(list(map(lambda i: len(self.data[key]['resp'][i]),",
"you fine <eos> [2, 7, 3, 0, 0], # second post: <go> hello",
"self.unk_id res_resp[res_resp >= self.valid_vocab_len] = self.unk_id if key=='train': res['score']=np.array([self.data[key]['score'][i] for i in indexes])",
"are unknown words, which are ignored both for model or metrics. Returns: (tuple):",
"post: <go> are you fine <eos> [2, 7, 3, 0, 0], # second",
"data_fields['train']) # Important: Sort the words preventing the index changes between # different",
"lists(tuples), which means (data_key(str), data_field(DataField)) pairs. # For example, # data_fields == {'train':",
"Sort the words preventing the index changes between # different runs vocab =",
"in enumerate(indexes): post = self.data[key]['post'][j] resp = self.data[key]['resp'][j] res_post[i, :len(post)] = post res_resp[i,",
"format). Its keys are the same as `self.key_name` that indicate the datasets, and",
"% valid_vocab_len) print(\"vocab list length = %d\" % len(vocab_list)) word2id = {w: i",
"a list(tuple), it must be a list of (key, field) pairs. Field must",
"= max(turn_length) sent_num = sum(turn_length) cut_sentence_rate = np.sum(np.maximum(np.array(turn_length) - max_turn_length, 0)) / sent_num",
"named %s.\" % key) res = {} batch_size = len(indexes) res[\"post_length\"] = np.array(list(map(lambda",
"datasets may have different formats.(If `data_fields` is a list or a tuple, different",
"file_path (str): A string indicating the path of dataset. data_fields (dict, list, tuple):",
"in origin_data[key][data_key]] data[key][data_key] = [ field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length) for element in origin_data[key][data_key]] if",
">>> # all_vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", >>> #",
"and returns the next label(integer). Note that it may raise StopIteration. Args:{DataField.GET_NEXT_ARG} Examples:",
"id form in posts. Provide both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]``",
"of id form in responses. Provide both valid and invalid vocabs. Size: ``[batch_size,",
"data_key, field in fields: for element in dic[data_key]: vocabs.extend(field.iter_tokens(element)) return vocabs raw_vocab_list =",
"item in data. ''' def get_fields(fields): assert isinstance(fields, list) or isinstance(fields, tuple) return",
"if key not in data_size: data_size[key] = len(data[key][data_key]) elif data_size[key] != len(data[key][data_key]): raise",
"Only provide valid vocabs. ``unk_id`` will be used if a word is not",
"data of input %s.txt contains different numbers of fields\" % key) vocab =",
"\"post_length\": numpy.array([5, 3]), # length of posts \"resp_length\": numpy.array([5, 3]), # length of",
"key not in data_size: data_size[key] = len(data[key][data_key]) elif data_size[key] != len(data[key][data_key]): raise RuntimeError(",
">>> field.get_next(dataset) 0 \"\"\" score = next(dataset) return float(score.strip()) def _map_fun(self, element, convert_ids_to_tokens=None):",
"= len(vocab) oov_num = sum([word not in word2id for word in vocab]) invalid_num",
"dataset = {'key1': [session1, session2, ...], 'key2': [label1, label2, ...]} If it's a",
"1 >>> field.get_next(dataset) 0 \"\"\" score = next(dataset) return float(score.strip()) def _map_fun(self, element,",
"This argument exists, just to keep the signature the same as that of",
"that the train set contains sessions and labels, but the test set only",
"hash_value = DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value = hash_value return",
"in responses. Only provide valid vocabs. ``unk_id`` will be used if a word",
"\"resp_allvocabs\": numpy.array([ [2, 8, 9, 10, 3], # first response: <go> i am",
"for x in vocab if x[1] >= invalid_vocab_times and x[0] not in valid_vocab_set]",
"<pad> <pad> ]), \"post_length\": numpy.array([5, 3]), # length of posts \"resp_length\": numpy.array([5, 3]),",
"valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` * **resp_length** (:class:`numpy.ndarray`): A 1-d array,",
"than ``max_sent_length`` will be shortened to first ``max_sent_length`` tokens. max_turn_length (int): All sessions,",
"[['post', 'Sentence'], ['resp', 'Sentence'], ['score', Score]], 'dev': [['post', 'Sentence'], ['resp', 'Sentence']], 'test': [['post',",
"must be a list(or tuple) of lists(or tuples).') elif isinstance(data_fields, list) or isinstance(data_fields,",
"cut-off threshold of valid tokens. All tokens appear not less than `min_vocab_times` in",
"index changes between # different runs vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1],",
"fields for dataset(%s) ' % ', '.join(no_field_keys)) try: data_fields = {key: get_fields(data_fields[key]) for",
"} ''' if key not in self.key_name: raise ValueError(\"No set named %s.\" %",
"data_size = {} for key in self.key_name: data[key] = {} for data_key, field",
"self._general_load_data(self._file_path, data_fields, \\ self._min_vocab_times, self._max_sent_length, None, self._invalid_vocab_times) def _general_load_data(self, file_path, data_fields, min_vocab_times, max_sent_length,",
"self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value = hash_value return vocab_list, valid_vocab_len, data,",
"of posts \"resp_length\": numpy.array([5, 3]), # length of responses } ''' if key",
"file_path, data_fields, min_vocab_times, max_sent_length, max_turn_length, invalid_vocab_times): r'''This function implements a general loading process.",
"np.sum(np.maximum(np.array(turn_length) - max_turn_length, 0)) / sent_num else: max_turn_length_before_cut = 1 cut_sentence_rate = 0",
"the length of post in each batch. Size: ``[batch_size]`` * **post** (:class:`numpy.ndarray`): A",
"'Sentence'], ['resp', 'Sentence'], ['score', Score]], 'dev': [['post', 'Sentence'], ['resp', 'Sentence']], 'test': [['post', 'Sentence'],",
"in the raw file, the first line is a sentence and the second",
"valid vocabs. ``unk_id`` will be used if a word is not valid. Size:",
"in **training set** will be marked as valid words. max_sent_length (int): All sentences",
"* from collections import Counter import numpy as np from itertools import chain",
"sent_length = [] for data_key, field in data_fields[key]: sent_length.extend( [len(sent) for element in",
"# For example, # data_fields == {'train': [['sent', Sentence()], ['label', Label()]], # 'test':",
"= [] for data_key, field in fields: for element in dic[data_key]: vocabs.extend(field.iter_tokens(element)) return",
"res_post[res_post >= self.valid_vocab_len] = self.unk_id res_resp[res_resp >= self.valid_vocab_len] = self.unk_id if key=='train': res['score']=np.array([self.data[key]['score'][i]",
"\\ key=lambda pair: (-pair[1], pair[0])) left_vocab = [x[0] for x in vocab if",
"Size: ``[batch_size]`` * **post** (:class:`numpy.ndarray`): A 2-d padded array containing words of id",
"[['post', 'Sentence'], ['resp', 'Sentence']], 'test': [['post', 'Sentence'], ['resp', 'Sentence']], } return self._general_load_data(self._file_path, data_fields,",
"A cut-off threshold of invalid tokens. All tokens appear not less than ``invalid_vocab_times``",
"isinstance(fields, list) or isinstance(fields, tuple) return [(data_key, DataField.get_field(field)) for data_key, field in fields]",
"Its keys are the same as `self.key_name` that indicate the datasets, and the",
"assuming its constructor accepts no arguments), or a string(in this case, the instance",
"must be a list of (key, field) pairs. Field must be a DataField",
"in each batch. Size: ``[batch_size]`` * **post** (:class:`numpy.ndarray`): A 2-d padded array containing",
"max_turn_length_before_cut = max(turn_length) sent_num = sum(turn_length) cut_sentence_rate = np.sum(np.maximum(np.array(turn_length) - max_turn_length, 0)) /",
"w in enumerate(vocab_list)} data = {} data_size = {} for key in self.key_name:",
">= invalid_vocab_times and x[0] not in valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid vocab list length =",
"AssertionError: raise TypeError('If `data_field` is a dict, its value must be a list(or",
"pair: (-pair[1], pair[0])) left_vocab = [x[0] for x in vocab if x[1] >=",
"words) will be marked as invalid words. Otherwise, they are unknown words, which",
"datasets, and the values are lists as mentioned above. For example, data_fields =",
"model or metrics. Returns: (tuple): containing: * **all_vocab_list** (list): vocabulary list of the",
"tokenizer, remains_capital ): super().__init__(file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital) def _load_data(self):",
"2-d padded array containing words of id form in responses. Provide both valid",
"= [] for data_key, field in data_fields[key]: sent_length.extend( [len(sent) for element in origin_data[key][data_key]",
"''' if key not in self.key_name: raise ValueError(\"No set named %s.\" % key)",
"return element class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def __init__(self, file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\",
"unknown words, which are ignored both for model or metrics. Returns: (tuple): containing:",
"convert_ids_to_tokens: It's useless. This argument exists, just to keep the signature the same",
"res_resp[i, :len(resp)] = resp res[\"post_allvocabs\"] = res_post.copy() res[\"resp_allvocabs\"] = res_resp.copy() res_post[res_post >= self.valid_vocab_len]",
"DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value = hash_value return vocab_list, valid_vocab_len,",
"in data. ''' def get_fields(fields): assert isinstance(fields, list) or isinstance(fields, tuple) return [(data_key,",
"TypeError('`data_fields` must be a dict, or a list, or a tuple.') # now",
"cut_word_num / vocab_num, max_turn_length_before_cut, cut_sentence_rate)) # calculate hash value hash_value = DataloaderHash(ignore_tokens=(self.go_id, self.eos_id,",
"valid_vocab_len) print(\"vocab list length = %d\" % len(vocab_list)) word2id = {w: i for",
"of DataField(in this case, its instance will be used, assuming its constructor accepts",
"and invalid vocabs. * **valid_vocab_len** (int): the number of valid vocab. ``vocab_list[:valid_vocab_len]`` will",
"both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` Examples: >>> # all_vocab_list =",
"3, 0, 0], # second response: <go> hello <eos> <pad> <pad> ]), \"resp\":",
"max_sent_length (int): All sentences longer than ``max_sent_length`` will be shortened to first ``max_sent_length``",
"keep the signature the same as that of super class. \"\"\" return element",
"the next label(integer). Note that it may raise StopIteration. Args:{DataField.GET_NEXT_ARG} Examples: >>> dataset",
"key) vocab = chain_allvocab(origin_data[key], data_fields[key]) vocab_num = len(vocab) oov_num = sum([word not in",
"= chain_allvocab(origin_data[key], data_fields[key]) vocab_num = len(vocab) oov_num = sum([word not in word2id for",
"cut sentence rate: %f\") % \\ (key, invalid_num / vocab_num, oov_num / vocab_num,",
"max sentence length before cut: %d, \" + \\ \"cut word rate: %f\\n\\tmax",
"{} batch_size = len(indexes) res[\"post_length\"] = np.array(list(map(lambda i: len(self.data[key]['post'][i]), indexes)), dtype=int) res[\"resp_length\"] =",
"If it's a list(tuple), it must be a list of (key, field) pairs.",
"list or a tuple, different datasets have the same format). Its keys are",
"not in data_fields] if no_field_keys: raise ValueError('There is no data fields for dataset(%s)",
"first post: <go> are you <unk> <eos> [2, 7, 3, 0, 0], #",
"indexes]) return res def main(): max_sent_length = 50 loader = TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length,",
"key in self.key_name: data[key] = {} for data_key, field in data_fields[key]: origin_data[key][data_key] =",
"key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict): A dict at least contains: * **post_length** (:class:`numpy.ndarray`):",
"numpy.array([ [2, 8, 1, 1, 3], # first response: <go> i <unk> <unk>",
"tokenizer, remains_capital) def _load_data(self): data_fields = { 'train': [['post', 'Sentence'], ['resp', 'Sentence'], ['score',",
"will be ignored. invalid_vocab_times (int): A cut-off threshold of invalid tokens. All tokens",
"\"post_allvocabs\": numpy.array([ [2, 5, 6, 10, 3], # first post: <go> are you",
"containing words of id form in responses. Provide both valid and invalid vocabs.",
"RuntimeError( \"The data of input %s.txt contains different numbers of fields\" % key)",
"element in origin_data[key][data_key]] data[key][data_key] = [ field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length) for element in origin_data[key][data_key]]",
"\"<eos>\", \"how\", \"are\", \"you\", \"hello\", \"i\"] >>> dataloader.get_batch('train', [0, 1]) { \"post_allvocabs\": numpy.array([",
"dataset. convert_ids_to_tokens: It's useless. This argument exists, just to keep the signature the",
"the raw file, the first *several lines* is a session, *followed by an",
"(dict): a dict contains size of each item in data. ''' def get_fields(fields):",
"remains_capital) def _load_data(self): data_fields = { 'train': [['post', 'Sentence'], ['resp', 'Sentence'], ['score', Score]],",
"field.iter_tokens(element): if token in special_tokens: raise RuntimeError( 'The dataset contains special token \"%s\".",
"data = {} data_size = {} for key in self.key_name: data[key] = {}",
"\"%s\". This is not allowed.' % token) origin_data[key][data_key].append(element) except StopIteration: break def chain_allvocab(dic,",
"max(sent_length)]`` Examples: >>> # all_vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\",",
"a list, or a tuple.') # now data_fields is a dict. Keys are",
"are ignored both for model or metrics. Returns: (tuple): containing: * **all_vocab_list** (list):",
"its constructor accepts no arguments), or a string(in this case, the instance of",
"vocab_list = self.ext_vocab + list(left_vocab) valid_vocab_len = len(vocab_list) valid_vocab_set = set(vocab_list) for key",
"id form in responses. Provide both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]``",
"for data_key, field in fields] if isinstance(data_fields, dict): no_field_keys = [key for key",
"{} for key in self.key_name: data[key] = {} for data_key, field in data_fields[key]:",
"data_fields[key] if field.__class__ == Session] if session_keys: turn_length = list( map(len, chain.from_iterable((origin_data[key][sess_key] for",
"isinstance(data_fields, list) or isinstance(data_fields, tuple): data_fields = get_fields(data_fields) data_fields = {key: data_fields for",
"vocabs raw_vocab_list = chain_allvocab(origin_data['train'], data_fields['train']) # Important: Sort the words preventing the index",
"\\ tokenizer, remains_capital) def _load_data(self): data_fields = { 'train': [['post', 'Sentence'], ['resp', 'Sentence'],",
"(int): A cut-off threshold of invalid tokens. All tokens appear not less than",
"list, or a tuple.') # now data_fields is a dict. Keys are the",
"data_fields = {'train': [['sess', 'Session'], ['label', 'Label']], 'test': [['sess', 'session']]}, means that the",
"8, 9, 10, 3], # first response: <go> i am fine <eos> [2,",
"= iter([\"1\\n\", \"0\\n\"]) >>> field = Label() >>> field.get_next(dataset) 1 >>> field.get_next(dataset) 0",
"origin_data[key][data_key].append(element) except StopIteration: break def chain_allvocab(dic, fields): vocabs = [] for data_key, field",
"field, will be used). For example, data_fields=[['post', 'Sentence'], ['label', Label]] means that, in",
"sentence and the second line is a label. They are saved in a",
"numpy.array([ [2, 5, 6, 1, 3], # first post: <go> are you <unk>",
"= {} data_size = {} for key in self.key_name: data[key] = {} for",
"same as that of super class. \"\"\" return element class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def",
"dtype=int) res_resp = res[\"resp\"] = np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int) for i, j in enumerate(indexes):",
"res def main(): max_sent_length = 50 loader = TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length, 0, 'nltk',",
"0, 0], # second response: <go> hello <eos> <pad> <pad> ]), \"resp\": numpy.array([",
"', '.join(no_field_keys)) try: data_fields = {key: get_fields(data_fields[key]) for key in self.key_name} except AssertionError:",
"vocab_list, valid_vocab_len, data, data_size def get_batch(self, key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict): A dict",
"of valid tokens. All tokens appear not less than `min_vocab_times` in **training set**",
"be shorten to first ``max_turn_length`` sentences. If the dataset don't contains sessions, this",
"max(sent_length)]`` * **resp_length** (:class:`numpy.ndarray`): A 1-d array, the length of response in each",
"dtype=int) for i, j in enumerate(indexes): post = self.data[key]['post'][j] resp = self.data[key]['resp'][j] res_post[i,",
"(int): A cut-off threshold of valid tokens. All tokens appear not less than",
"indicate the datasets, and the values are lists as mentioned above. For example,",
"origin_data = {} for key in self.key_name: origin_data[key] = {data_key: [] for data_key,",
"sent_length.extend( [len(sent) for element in origin_data[key][data_key] for sent in field.iter_sentence(element)]) cut_word_num = np.sum(np.maximum(np.array(sent_length)",
"in fields: for element in dic[data_key]: vocabs.extend(field.iter_tokens(element)) return vocabs raw_vocab_list = chain_allvocab(origin_data['train'], data_fields['train'])",
"\"hello\", \"i\", \"am\", \"fine\"] >>> # vocab_size = 9 >>> # vocab_list =",
"means that, in the raw file, the first line is a sentence and",
"\"hello\", \"i\"] >>> dataloader.get_batch('train', [0, 1]) { \"post_allvocabs\": numpy.array([ [2, 5, 6, 10,",
"containing words of id form in posts. Provide both valid and invalid vocabs.",
"``max_sent_length`` will be shortened to first ``max_sent_length`` tokens. max_turn_length (int): All sessions, whose",
"np.max(res[\"post_length\"])), dtype=int) res_resp = res[\"resp\"] = np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int) for i, j in",
"= len(indexes) res[\"post_length\"] = np.array(list(map(lambda i: len(self.data[key]['post'][i]), indexes)), dtype=int) res[\"resp_length\"] = np.array(list(map(lambda i:",
"return [(data_key, DataField.get_field(field)) for data_key, field in fields] if isinstance(data_fields, dict): no_field_keys =",
"`data_field` is a dict, its value must be a list(or tuple) of lists(or",
":len(post)] = post res_resp[i, :len(resp)] = resp res[\"post_allvocabs\"] = res_post.copy() res[\"resp_allvocabs\"] = res_resp.copy()",
"itself. Args: element: An element of a dataset. convert_ids_to_tokens: It's useless. This argument",
"or a list, or a tuple.') # now data_fields is a dict. Keys",
"line6, ...]} data_fields=[['key1', 'Session'], ['key2', Label()]], means that, in the raw file, the",
"will be used if a word is not valid. Size: ``[batch_size, max(sent_length)]`` *",
"raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab = [x[0]",
"size of each item in data. ''' def get_fields(fields): assert isinstance(fields, list) or",
"[['sent', Sentence()], ['label', Label()]], # 'test': [['sent', Sentence()], ['label', Label()]]}. # Note, different",
"words. Otherwise, they are unknown words, which are ignored both for model or",
"`self.key_name` that indicate the datasets, and the values are lists as mentioned above.",
"**post_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form in posts.",
"<pad> ]), \"post\": numpy.array([ [2, 5, 6, 1, 3], # first post: <go>",
"res_resp[res_resp >= self.valid_vocab_len] = self.unk_id if key=='train': res['score']=np.array([self.data[key]['score'][i] for i in indexes]) return",
"10, 3], # first response: <go> i am fine <eos> [2, 7, 3,",
"an empty line*, and the next line is a label. dataset = {'key1':",
"50 loader = TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length, 0, 'nltk', False) loader.restart(\"train\",batch_size=2,shuffle=True) q=loader.get_next_batch(\"train\") print(len(q['score'])) print(q)",
"value must be a list(or tuple) of lists(or tuples).') elif isinstance(data_fields, list) or",
"dict, or a list, or a tuple.') # now data_fields is a dict.",
"whose __name__ is field, will be used). For example, data_fields=[['post', 'Sentence'], ['label', Label]]",
"x[1] >= invalid_vocab_times and x[0] not in valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid vocab list length",
"key in self.key_name} except AssertionError: raise TypeError('If `data_field` is a dict, its value",
"list of (key, field) pairs. Field must be a DataField instance, or a",
"data_fields = {key: data_fields for key in self.key_name} else: raise TypeError('`data_fields` must be",
"TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length, 0, 'nltk', False) loader.restart(\"train\",batch_size=2,shuffle=True) q=loader.get_next_batch(\"train\") print(len(q['score'])) print(q) if __name__ ==",
"line is a label. They are saved in a dict. dataset = {'post':",
"2-d padded array containing words of id form in responses. Only provide valid",
"_general_load_data(self, file_path, data_fields, min_vocab_times, max_sent_length, max_turn_length, invalid_vocab_times): r'''This function implements a general loading",
"get_resource_file_path from cotk.dataloader.dataloader import * from collections import Counter import numpy as np",
"or a subclass of DataField(in this case, its instance will be used, assuming",
"padded array containing words of id form in responses. Only provide valid vocabs.",
"file, the first *several lines* is a session, *followed by an empty line*,",
"@cotk._utils.hooks.hook_dataloader def __init__(self, file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital ): super().__init__(file_id,",
"if key == 'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair:",
"try: for data_key, field in data_fields[key]: element = field.convert_to_tokens(field.get_next(f_file), self.tokenize) for token in",
"vocabulary list of the datasets, including valid and invalid vocabs. * **valid_vocab_len** (int):",
"<unk> <unk> <eos> [2, 7, 3, 0, 0], # second response: <go> hello",
"enumerate(vocab_list)} data = {} data_size = {} for key in self.key_name: data[key] =",
"have different fields. special_tokens = set(self.ext_vocab) origin_data = {} for key in self.key_name:",
"line4, line6, ...]} data_fields=[['key1', 'Session'], ['key2', Label()]], means that, in the raw file,",
"<eos> <pad> <pad> ]), \"post_length\": numpy.array([5, 3]), # length of posts \"resp_length\": numpy.array([5,",
"key in self.key_name: if key == 'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab = sorted(Counter(raw_vocab_list).most_common(),",
"convert_ids_to_tokens=None): \"\"\" Returns the element itself. Args: element: An element of a dataset.",
"hello <eos> <pad> <pad> ]), \"resp\": numpy.array([ [2, 8, 1, 1, 3], #",
"score = next(dataset) return float(score.strip()) def _map_fun(self, element, convert_ids_to_tokens=None): \"\"\" Returns the element",
"{ \"post_allvocabs\": numpy.array([ [2, 5, 6, 10, 3], # first post: <go> are",
"calculate hash value hash_value = DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value",
"All tokens appear not less than `min_vocab_times` in **training set** will be marked",
"[] for data_key, _ in data_fields[key]} with open(\"%s/%s.txt\" % (file_path, key), encoding='utf-8') as",
"list of the datasets, including valid and invalid vocabs. * **valid_vocab_len** (int): the",
"the first *several lines* is a session, *followed by an empty line*, and",
"same as `self.key_name` that indicate the datasets, and the values are lists as",
"**data** (dict): a dict contains data. * **data_size** (dict): a dict contains size",
"res[\"resp\"] = np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int) for i, j in enumerate(indexes): post = self.data[key]['post'][j]",
"'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab",
"data_fields] if no_field_keys: raise ValueError('There is no data fields for dataset(%s) ' %",
"Returns the element itself. Args: element: An element of a dataset. convert_ids_to_tokens: It's",
"\"\"\" score = next(dataset) return float(score.strip()) def _map_fun(self, element, convert_ids_to_tokens=None): \"\"\" Returns the",
"label. dataset = {'key1': [session1, session2, ...], 'key2': [label1, label2, ...]} If it's",
"['label', Label()]], # 'test': [['sent', Sentence()], ['label', Label()]]}. # Note, different dataset may",
"it may raise StopIteration. Args:{DataField.GET_NEXT_ARG} Examples: >>> dataset = iter([\"1\\n\", \"0\\n\"]) >>> field",
"# data_fields == {'train': [['sent', Sentence()], ['label', Label()]], # 'test': [['sent', Sentence()], ['label',",
"pairs. # For example, # data_fields == {'train': [['sent', Sentence()], ['label', Label()]], #",
"= {key: data_fields for key in self.key_name} else: raise TypeError('`data_fields` must be a",
"= 0 print((\"%s set. invalid rate: %f, unknown rate: %f, max sentence length",
"<go> i am fine <eos> [2, 7, 3, 0, 0], # second response:",
"import numpy as np from itertools import chain class Score(DataField): def get_next(self, dataset):",
"fields\" % key) vocab = chain_allvocab(origin_data[key], data_fields[key]) vocab_num = len(vocab) oov_num = sum([word",
"= {} batch_size = len(indexes) res[\"post_length\"] = np.array(list(map(lambda i: len(self.data[key]['post'][i]), indexes)), dtype=int) res[\"resp_length\"]",
"Keys are the same as self.key_name('train', 'test', 'dev', etc.). Each value is #",
"not in valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid vocab list length = %d\" % valid_vocab_len) print(\"vocab",
"words of id form in responses. Provide both valid and invalid vocabs. Size:",
"pair[0])) left_vocab = [x[0] for x in vocab if x[1] >= invalid_vocab_times and",
"= np.sum(np.maximum(np.array(turn_length) - max_turn_length, 0)) / sent_num else: max_turn_length_before_cut = 1 cut_sentence_rate =",
"data_field(DataField)) pairs. # For example, # data_fields == {'train': [['sent', Sentence()], ['label', Label()]],",
"of a dataset. convert_ids_to_tokens: It's useless. This argument exists, just to keep the",
"\"i\"] >>> dataloader.get_batch('train', [0, 1]) { \"post_allvocabs\": numpy.array([ [2, 5, 6, 10, 3],",
"# first response: <go> i <unk> <unk> <eos> [2, 7, 3, 0, 0],",
"* **post_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form in",
"= DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value = hash_value return vocab_list,",
"= Label() >>> field.get_next(dataset) 1 >>> field.get_next(dataset) 0 \"\"\" score = next(dataset) return",
"invalid vocabs. * **data** (dict): a dict contains data. * **data_size** (dict): a",
"tuple): data_fields = get_fields(data_fields) data_fields = {key: data_fields for key in self.key_name} else:",
"allowed.' % token) origin_data[key][data_key].append(element) except StopIteration: break def chain_allvocab(dic, fields): vocabs = []",
"second post: <go> hello <eos> <pad> <pad> ]), \"resp_allvocabs\": numpy.array([ [2, 8, 9,",
"shorten to first ``max_turn_length`` sentences. If the dataset don't contains sessions, this parameter",
"0)) / sent_num else: max_turn_length_before_cut = 1 cut_sentence_rate = 0 print((\"%s set. invalid",
"= next(dataset) return float(score.strip()) def _map_fun(self, element, convert_ids_to_tokens=None): \"\"\" Returns the element itself.",
"They are saved in a dict. dataset = {'post': [line1, line3, line5, ...],",
"raise ValueError('There is no data fields for dataset(%s) ' % ', '.join(no_field_keys)) try:",
"hello <eos> <pad> <pad> ]), \"post_length\": numpy.array([5, 3]), # length of posts \"resp_length\":",
"the dataset don't contains sessions, this parameter will be ignored. invalid_vocab_times (int): A",
"a list of (key, field) pairs. Field must be a DataField instance, or",
"invalid vocabs. Size: ``[batch_size, max(sent_length)]`` * **resp_length** (:class:`numpy.ndarray`): A 1-d array, the length",
"the datasets, including valid and invalid vocabs. * **valid_vocab_len** (int): the number of",
"/ vocab_num, max_turn_length_before_cut, cut_sentence_rate)) # calculate hash value hash_value = DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id),",
"All sentences longer than ``max_sent_length`` will be shortened to first ``max_sent_length`` tokens. max_turn_length",
"responses. Provide both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` Examples: >>> #",
"Label()]], # 'test': [['sent', Sentence()], ['label', Label()]]}. # Note, different dataset may have",
"contains sessions, this parameter will be ignored. invalid_vocab_times (int): A cut-off threshold of",
"tuples).') elif isinstance(data_fields, list) or isinstance(data_fields, tuple): data_fields = get_fields(data_fields) data_fields = {key:",
"raise RuntimeError( \"The data of input %s.txt contains different numbers of fields\" %",
"not valid. Size: ``[batch_size, max(sent_length)]`` * **resp_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing",
"vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab = [x[0] for x",
">>> dataset = iter([\"1\\n\", \"0\\n\"]) >>> field = Label() >>> field.get_next(dataset) 1 >>>",
"its instance will be used, assuming its constructor accepts no arguments), or a",
"longer than ``max_turn_length`` will be shorten to first ``max_turn_length`` sentences. If the dataset",
"valid vocabs, while ``vocab_list[valid_vocab_len:]`` regarded as invalid vocabs. * **data** (dict): a dict",
"they are unknown words, which are ignored both for model or metrics. Returns:",
"res_post.copy() res[\"resp_allvocabs\"] = res_resp.copy() res_post[res_post >= self.valid_vocab_len] = self.unk_id res_resp[res_resp >= self.valid_vocab_len] =",
"= len(data[key][data_key]) elif data_size[key] != len(data[key][data_key]): raise RuntimeError( \"The data of input %s.txt",
"...], 'label': [line2, line4, line6, ...]} data_fields=[['key1', 'Session'], ['key2', Label()]], means that, in",
"= sum(turn_length) cut_sentence_rate = np.sum(np.maximum(np.array(turn_length) - max_turn_length, 0)) / sent_num else: max_turn_length_before_cut =",
"self._invalid_vocab_times) def _general_load_data(self, file_path, data_fields, min_vocab_times, max_sent_length, max_turn_length, invalid_vocab_times): r'''This function implements a",
"self.key_name: raise ValueError(\"No set named %s.\" % key) res = {} batch_size =",
"i in indexes]) return res def main(): max_sent_length = 50 loader = TranslationWithScore('./data/iwslt14_raml',",
"r'''This function implements a general loading process. Arguments: file_path (str): A string indicating",
"(except valid words) will be marked as invalid words. Otherwise, they are unknown",
"<pad> ]), \"resp\": numpy.array([ [2, 8, 1, 1, 3], # first response: <go>",
"class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def __init__(self, file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital",
"\\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital) def _load_data(self): data_fields = { 'train': [['post',",
"list(tuple), it must be a list of (key, field) pairs. Field must be",
"vocabs. Size: ``[batch_size, max(sent_length)]`` * **resp_length** (:class:`numpy.ndarray`): A 1-d array, the length of",
"implements a general loading process. Arguments: file_path (str): A string indicating the path",
"second response: <go> hello <eos> <pad> <pad> ]), \"post_length\": numpy.array([5, 3]), # length",
"of responses } ''' if key not in self.key_name: raise ValueError(\"No set named",
"dict at least contains: * **post_length** (:class:`numpy.ndarray`): A 1-d array, the length of",
"``[batch_size, max(sent_length)]`` * **resp_length** (:class:`numpy.ndarray`): A 1-d array, the length of response in",
"invalid_num = sum([word not in valid_vocab_set for word in vocab]) - oov_num sent_length",
"vocab_num, oov_num / vocab_num, max(sent_length), \\ cut_word_num / vocab_num, max_turn_length_before_cut, cut_sentence_rate)) # calculate",
"the index changes between # different runs vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair:",
"\"how\", \"are\", \"you\", \"hello\", \"i\"] >>> dataloader.get_batch('train', [0, 1]) { \"post_allvocabs\": numpy.array([ [2,",
"for i, w in enumerate(vocab_list)} data = {} data_size = {} for key",
"= get_fields(data_fields) data_fields = {key: data_fields for key in self.key_name} else: raise TypeError('`data_fields`",
"all_vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", >>> # \"hello\", \"i\",",
"marked as valid words. max_sent_length (int): All sentences longer than ``max_sent_length`` will be",
"set(self.ext_vocab) origin_data = {} for key in self.key_name: origin_data[key] = {data_key: [] for",
"the same format). Its keys are the same as `self.key_name` that indicate the",
"raise ValueError(\"No set named %s.\" % key) res = {} batch_size = len(indexes)",
"in vocab if x[1] >= min_vocab_times] vocab_list = self.ext_vocab + list(left_vocab) valid_vocab_len =",
"raise StopIteration. Args:{DataField.GET_NEXT_ARG} Examples: >>> dataset = iter([\"1\\n\", \"0\\n\"]) >>> field = Label()",
"if a word is not valid. Size: ``[batch_size, max(sent_length)]`` * **post_allvocabs** (:class:`numpy.ndarray`): A",
"def _general_load_data(self, file_path, data_fields, min_vocab_times, max_sent_length, max_turn_length, invalid_vocab_times): r'''This function implements a general",
"special_tokens: raise RuntimeError( 'The dataset contains special token \"%s\". This is not allowed.'",
"for sent in field.iter_sentence(element)]) cut_word_num = np.sum(np.maximum(np.array(sent_length) - max_sent_length, 0)) session_keys = [data_key",
"**training set** will be marked as valid words. max_sent_length (int): All sentences longer",
"only contains sessions. min_vocab_times (int): A cut-off threshold of valid tokens. All tokens",
"'Sentence'], ['resp', 'Sentence']], } return self._general_load_data(self._file_path, data_fields, \\ self._min_vocab_times, self._max_sent_length, None, self._invalid_vocab_times) def",
"``vocab_list[:valid_vocab_len]`` will be regarded as valid vocabs, while ``vocab_list[valid_vocab_len:]`` regarded as invalid vocabs.",
"invalid words. Otherwise, they are unknown words, which are ignored both for model",
"to keep the signature the same as that of super class. \"\"\" return",
"valid words. max_sent_length (int): All sentences longer than ``max_sent_length`` will be shortened to",
"...], 'key2': [label1, label2, ...]} If it's a dict, different datasets may have",
"keys are the same as `self.key_name` that indicate the datasets, and the values",
"or a tuple.') # now data_fields is a dict. Keys are the same",
"datasets have the same format). Its keys are the same as `self.key_name` that",
"the raw file, the first line is a sentence and the second line",
"For example, data_fields=[['post', 'Sentence'], ['label', Label]] means that, in the raw file, the",
"hello <eos> <pad> <pad> ]), \"post\": numpy.array([ [2, 5, 6, 1, 3], #",
"etc.). Each value is # a list(tuple) of lists(tuples), which means (data_key(str), data_field(DataField))",
"hello <eos> <pad> <pad> ]), \"resp_allvocabs\": numpy.array([ [2, 8, 9, 10, 3], #",
"indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict): A dict at least contains: * **post_length** (:class:`numpy.ndarray`): A",
">>> # \"hello\", \"i\", \"am\", \"fine\"] >>> # vocab_size = 9 >>> #",
"of the datasets, including valid and invalid vocabs. * **valid_vocab_len** (int): the number",
"3], # first response: <go> i <unk> <unk> <eos> [2, 7, 3, 0,",
"open(\"%s/%s.txt\" % (file_path, key), encoding='utf-8') as f_file: while True: try: for data_key, field",
"line5, ...], 'label': [line2, line4, line6, ...]} data_fields=[['key1', 'Session'], ['key2', Label()]], means that,",
"\"\"\" Returns the element itself. Args: element: An element of a dataset. convert_ids_to_tokens:",
"(str): A string indicating the path of dataset. data_fields (dict, list, tuple): If",
"Only provide valid words. ``unk_id`` will be used if a word is not",
"a DataField instance, or a subclass of DataField(in this case, its instance will",
"contains data. * **data_size** (dict): a dict contains size of each item in",
"of lists(or tuples).') elif isinstance(data_fields, list) or isinstance(data_fields, tuple): data_fields = get_fields(data_fields) data_fields",
"(int): All sentences longer than ``max_sent_length`` will be shortened to first ``max_sent_length`` tokens.",
"or isinstance(data_fields, tuple): data_fields = get_fields(data_fields) data_fields = {key: data_fields for key in",
"that, in the raw file, the first *several lines* is a session, *followed",
"def main(): max_sent_length = 50 loader = TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length, 0, 'nltk', False)",
"+ list(left_vocab) valid_vocab_len = len(vocab_list) valid_vocab_set = set(vocab_list) for key in self.key_name: if",
"dict contains data. * **data_size** (dict): a dict contains size of each item",
"length of response in each batch. Size: ``[batch_size]`` * **resp** (:class:`numpy.ndarray`): A 2-d",
"be a list(or tuple) of lists(or tuples).') elif isinstance(data_fields, list) or isinstance(data_fields, tuple):",
"min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital ): super().__init__(file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times,",
"<eos> [2, 7, 3, 0, 0], # second post: <go> hello <eos> <pad>",
"* **resp_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form in",
"0], # second response: <go> hello <eos> <pad> <pad> ]), \"resp\": numpy.array([ [2,",
"Note, different dataset may have different fields. special_tokens = set(self.ext_vocab) origin_data = {}",
"(file_path, key), encoding='utf-8') as f_file: while True: try: for data_key, field in data_fields[key]:",
"= [x[0] for x in vocab if x[1] >= invalid_vocab_times and x[0] not",
"{ 'train': [['post', 'Sentence'], ['resp', 'Sentence'], ['score', Score]], 'dev': [['post', 'Sentence'], ['resp', 'Sentence']],",
"res[\"post\"] = np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int) res_resp = res[\"resp\"] = np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int) for",
"oov_num sent_length = [] for data_key, field in data_fields[key]: sent_length.extend( [len(sent) for element",
"= self.unk_id if key=='train': res['score']=np.array([self.data[key]['score'][i] for i in indexes]) return res def main():",
"responses } ''' if key not in self.key_name: raise ValueError(\"No set named %s.\"",
"(int): All sessions, whose turn length is longer than ``max_turn_length`` will be shorten",
"lists as mentioned above. For example, data_fields = {'train': [['sess', 'Session'], ['label', 'Label']],",
"``invalid_vocab_times`` in the **whole dataset** (except valid words) will be marked as invalid",
"contains different numbers of fields\" % key) vocab = chain_allvocab(origin_data[key], data_fields[key]) vocab_num =",
"]), \"resp_allvocabs\": numpy.array([ [2, 8, 9, 10, 3], # first response: <go> i",
"]), \"resp\": numpy.array([ [2, 8, 1, 1, 3], # first response: <go> i",
"cotk from cotk._utils.file_utils import get_resource_file_path from cotk.dataloader.dataloader import * from collections import Counter",
"field in data_fields[key]: origin_data[key][data_key] = [field.convert_to_ids(element, word2id, self) for element in origin_data[key][data_key]] data[key][data_key]",
"be marked as invalid words. Otherwise, they are unknown words, which are ignored",
"valid_vocab_set for word in vocab]) - oov_num sent_length = [] for data_key, field",
"word is not valid. Size: ``[batch_size, max(sent_length)]`` * **post_allvocabs** (:class:`numpy.ndarray`): A 2-d padded",
"in word2id for word in vocab]) invalid_num = sum([word not in valid_vocab_set for",
"data_fields[key]: element = field.convert_to_tokens(field.get_next(f_file), self.tokenize) for token in field.iter_tokens(element): if token in special_tokens:",
"case, the instance of the class, whose __name__ is field, will be used).",
"tokens appear not less than ``invalid_vocab_times`` in the **whole dataset** (except valid words)",
"RuntimeError( 'The dataset contains special token \"%s\". This is not allowed.' % token)",
"are you <unk> <eos> [2, 7, 3, 0, 0], # second post: <go>",
"both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` * **resp_length** (:class:`numpy.ndarray`): A 1-d",
"dataset = {'post': [line1, line3, line5, ...], 'label': [line2, line4, line6, ...]} data_fields=[['key1',",
"# length of responses } ''' if key not in self.key_name: raise ValueError(\"No",
"0)) session_keys = [data_key for data_key, field in data_fields[key] if field.__class__ == Session]",
"numpy as np from itertools import chain class Score(DataField): def get_next(self, dataset): r\"\"\"read",
"'Sentence'], ['resp', 'Sentence']], 'test': [['post', 'Sentence'], ['resp', 'Sentence']], } return self._general_load_data(self._file_path, data_fields, \\",
"will be shorten to first ``max_turn_length`` sentences. If the dataset don't contains sessions,",
"indexes)), dtype=int) res[\"resp_length\"] = np.array(list(map(lambda i: len(self.data[key]['resp'][i]), indexes)), dtype=int) res_post = res[\"post\"] =",
"None, self._invalid_vocab_times) def _general_load_data(self, file_path, data_fields, min_vocab_times, max_sent_length, max_turn_length, invalid_vocab_times): r'''This function implements",
"batch. Size: ``[batch_size]`` * **post** (:class:`numpy.ndarray`): A 2-d padded array containing words of",
"%d, cut sentence rate: %f\") % \\ (key, invalid_num / vocab_num, oov_num /",
"chain.from_iterable((origin_data[key][sess_key] for sess_key in session_keys)))) max_turn_length_before_cut = max(turn_length) sent_num = sum(turn_length) cut_sentence_rate =",
"indicating the path of dataset. data_fields (dict, list, tuple): If it's a list(tuple),",
"from cotk.dataloader.dataloader import * from collections import Counter import numpy as np from",
"* **resp_length** (:class:`numpy.ndarray`): A 1-d array, the length of response in each batch.",
"= res_post.copy() res[\"resp_allvocabs\"] = res_resp.copy() res_post[res_post >= self.valid_vocab_len] = self.unk_id res_resp[res_resp >= self.valid_vocab_len]",
"are the same as `self.key_name` that indicate the datasets, and the values are",
"= [data_key for data_key, field in data_fields[key] if field.__class__ == Session] if session_keys:",
"''' def get_fields(fields): assert isinstance(fields, list) or isinstance(fields, tuple) return [(data_key, DataField.get_field(field)) for",
"no_field_keys: raise ValueError('There is no data fields for dataset(%s) ' % ', '.join(no_field_keys))",
"Size: ``[batch_size, max(sent_length)]`` * **resp_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words of",
"contains special token \"%s\". This is not allowed.' % token) origin_data[key][data_key].append(element) except StopIteration:",
"data_fields = {key: get_fields(data_fields[key]) for key in self.key_name} except AssertionError: raise TypeError('If `data_field`",
"elif isinstance(data_fields, list) or isinstance(data_fields, tuple): data_fields = get_fields(data_fields) data_fields = {key: data_fields",
"in self.key_name: data[key] = {} for data_key, field in data_fields[key]: origin_data[key][data_key] = [field.convert_to_ids(element,",
"pair[0])) left_vocab = [x[0] for x in vocab if x[1] >= min_vocab_times] vocab_list",
"{key: get_fields(data_fields[key]) for key in self.key_name} except AssertionError: raise TypeError('If `data_field` is a",
"is not valid. Size: ``[batch_size, max(sent_length)]`` * **post_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array",
"class. \"\"\" return element class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def __init__(self, file_id, min_vocab_times, \\ max_sent_length,",
"{'train': [['sess', 'Session'], ['label', 'Label']], 'test': [['sess', 'session']]}, means that the train set",
"data_key, _ in data_fields[key]} with open(\"%s/%s.txt\" % (file_path, key), encoding='utf-8') as f_file: while",
"itertools import chain class Score(DataField): def get_next(self, dataset): r\"\"\"read text and returns the",
"data_fields[key]) vocab_num = len(vocab) oov_num = sum([word not in word2id for word in",
"contains: * **post_length** (:class:`numpy.ndarray`): A 1-d array, the length of post in each",
"``[batch_size, max(sent_length)]`` * **post_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words of id",
"in data_fields[key] if field.__class__ == Session] if session_keys: turn_length = list( map(len, chain.from_iterable((origin_data[key][sess_key]",
"): super().__init__(file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital) def _load_data(self): data_fields =",
"to first ``max_turn_length`` sentences. If the dataset don't contains sessions, this parameter will",
"isinstance(data_fields, tuple): data_fields = get_fields(data_fields) data_fields = {key: data_fields for key in self.key_name}",
"'Sentence'], ['score', Score]], 'dev': [['post', 'Sentence'], ['resp', 'Sentence']], 'test': [['post', 'Sentence'], ['resp', 'Sentence']],",
"def __init__(self, file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital ): super().__init__(file_id, min_vocab_times,",
"lists(or tuples).') elif isinstance(data_fields, list) or isinstance(data_fields, tuple): data_fields = get_fields(data_fields) data_fields =",
"return self._general_load_data(self._file_path, data_fields, \\ self._min_vocab_times, self._max_sent_length, None, self._invalid_vocab_times) def _general_load_data(self, file_path, data_fields, min_vocab_times,",
"%f\\n\\tmax turn length before cut: %d, cut sentence rate: %f\") % \\ (key,",
"be used if a word is not valid. Size: ``[batch_size, max(sent_length)]`` * **resp_allvocabs**",
"3], # first post: <go> are you fine <eos> [2, 7, 3, 0,",
"\"resp\": numpy.array([ [2, 8, 1, 1, 3], # first response: <go> i <unk>",
"list, tuple): If it's a list(tuple), it must be a list of (key,",
"invalid tokens. All tokens appear not less than ``invalid_vocab_times`` in the **whole dataset**",
"set(vocab_list) for key in self.key_name: if key == 'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab",
"/ vocab_num, max(sent_length), \\ cut_word_num / vocab_num, max_turn_length_before_cut, cut_sentence_rate)) # calculate hash value",
"that of super class. \"\"\" return element class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def __init__(self, file_id,",
"posts. Only provide valid words. ``unk_id`` will be used if a word is",
"+ \\ \"cut word rate: %f\\n\\tmax turn length before cut: %d, cut sentence",
"res[\"post_length\"] = np.array(list(map(lambda i: len(self.data[key]['post'][i]), indexes)), dtype=int) res[\"resp_length\"] = np.array(list(map(lambda i: len(self.data[key]['resp'][i]), indexes)),",
"import get_resource_file_path from cotk.dataloader.dataloader import * from collections import Counter import numpy as",
"list length = %d\" % valid_vocab_len) print(\"vocab list length = %d\" % len(vocab_list))",
"'Sentence'], ['label', Label]] means that, in the raw file, the first line is",
"am fine <eos> [2, 7, 3, 0, 0], # second response: <go> hello",
"len(self.data[key]['resp'][i]), indexes)), dtype=int) res_post = res[\"post\"] = np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int) res_resp = res[\"resp\"]",
"r\"\"\"read text and returns the next label(integer). Note that it may raise StopIteration.",
"words of id form in posts. Provide both valid and invalid vocabs. Size:",
"dataset don't contains sessions, this parameter will be ignored. invalid_vocab_times (int): A cut-off",
"{key: data_fields for key in self.key_name} else: raise TypeError('`data_fields` must be a dict,",
"res[\"post_allvocabs\"] = res_post.copy() res[\"resp_allvocabs\"] = res_resp.copy() res_post[res_post >= self.valid_vocab_len] = self.unk_id res_resp[res_resp >=",
"array containing words of id form in responses. Provide both valid and invalid",
"\"\"\" return element class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def __init__(self, file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times,",
"for key in self.key_name} else: raise TypeError('`data_fields` must be a dict, or a",
"\"are\", \"you\", \"hello\", \"i\"] >>> dataloader.get_batch('train', [0, 1]) { \"post_allvocabs\": numpy.array([ [2, 5,",
"self) for element in origin_data[key][data_key]] data[key][data_key] = [ field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length) for element",
"tuple) of lists(or tuples).') elif isinstance(data_fields, list) or isinstance(data_fields, tuple): data_fields = get_fields(data_fields)",
"dataset(%s) ' % ', '.join(no_field_keys)) try: data_fields = {key: get_fields(data_fields[key]) for key in",
"'.join(no_field_keys)) try: data_fields = {key: get_fields(data_fields[key]) for key in self.key_name} except AssertionError: raise",
"= [field.convert_to_ids(element, word2id, self) for element in origin_data[key][data_key]] data[key][data_key] = [ field.cut(element, max_sent_length=max_sent_length,",
"vocab]) invalid_num = sum([word not in valid_vocab_set for word in vocab]) - oov_num",
"valid and invalid vocabs. * **valid_vocab_len** (int): the number of valid vocab. ``vocab_list[:valid_vocab_len]``",
"{'train': [['sent', Sentence()], ['label', Label()]], # 'test': [['sent', Sentence()], ['label', Label()]]}. # Note,",
"argument exists, just to keep the signature the same as that of super",
"data_key, field in data_fields[key]: origin_data[key][data_key] = [field.convert_to_ids(element, word2id, self) for element in origin_data[key][data_key]]",
"turn length before cut: %d, cut sentence rate: %f\") % \\ (key, invalid_num",
"6, 10, 3], # first post: <go> are you fine <eos> [2, 7,",
"data_fields[key]: origin_data[key][data_key] = [field.convert_to_ids(element, word2id, self) for element in origin_data[key][data_key]] data[key][data_key] = [",
"number of valid vocab. ``vocab_list[:valid_vocab_len]`` will be regarded as valid vocabs, while ``vocab_list[valid_vocab_len:]``",
"not in valid_vocab_set for word in vocab]) - oov_num sent_length = [] for",
"Args: element: An element of a dataset. convert_ids_to_tokens: It's useless. This argument exists,",
"raise RuntimeError( 'The dataset contains special token \"%s\". This is not allowed.' %",
"``unk_id`` will be used if a word is not valid. Size: ``[batch_size, max(sent_length)]``",
"and the next line is a label. dataset = {'key1': [session1, session2, ...],",
"the instance of the class, whose __name__ is field, will be used). For",
"vocabs.extend(field.iter_tokens(element)) return vocabs raw_vocab_list = chain_allvocab(origin_data['train'], data_fields['train']) # Important: Sort the words preventing",
"or a tuple, different datasets have the same format). Its keys are the",
"<go> are you <unk> <eos> [2, 7, 3, 0, 0], # second post:",
"appear not less than ``invalid_vocab_times`` in the **whole dataset** (except valid words) will",
"If the dataset don't contains sessions, this parameter will be ignored. invalid_vocab_times (int):",
"super class. \"\"\" return element class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def __init__(self, file_id, min_vocab_times, \\",
"[line1, line3, line5, ...], 'label': [line2, line4, line6, ...]} data_fields=[['key1', 'Session'], ['key2', Label()]],",
"self.key_name('train', 'test', 'dev', etc.). Each value is # a list(tuple) of lists(tuples), which",
"i am fine <eos> [2, 7, 3, 0, 0], # second response: <go>",
"* **data_size** (dict): a dict contains size of each item in data. '''",
"for i, j in enumerate(indexes): post = self.data[key]['post'][j] resp = self.data[key]['resp'][j] res_post[i, :len(post)]",
"DataField.get_field(field)) for data_key, field in fields] if isinstance(data_fields, dict): no_field_keys = [key for",
"Size: ``[batch_size, max(sent_length)]`` Examples: >>> # all_vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\",",
"Note that it may raise StopIteration. Args:{DataField.GET_NEXT_ARG} Examples: >>> dataset = iter([\"1\\n\", \"0\\n\"])",
"= post res_resp[i, :len(resp)] = resp res[\"post_allvocabs\"] = res_post.copy() res[\"resp_allvocabs\"] = res_resp.copy() res_post[res_post",
"\"resp_length\": numpy.array([5, 3]), # length of responses } ''' if key not in",
"key == 'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1],",
"word in vocab]) invalid_num = sum([word not in valid_vocab_set for word in vocab])",
"and x[0] not in valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid vocab list length = %d\" %",
"set named %s.\" % key) res = {} batch_size = len(indexes) res[\"post_length\"] =",
"import * from collections import Counter import numpy as np from itertools import",
"is a session, *followed by an empty line*, and the next line is",
"datasets, including valid and invalid vocabs. * **valid_vocab_len** (int): the number of valid",
"= [ field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length) for element in origin_data[key][data_key]] if key not in",
"vocabs. Size: ``[batch_size, max(sent_length)]`` Examples: >>> # all_vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\",",
"``max_turn_length`` will be shorten to first ``max_turn_length`` sentences. If the dataset don't contains",
"for data_key, field in data_fields[key]: element = field.convert_to_tokens(field.get_next(f_file), self.tokenize) for token in field.iter_tokens(element):",
"shortened to first ``max_sent_length`` tokens. max_turn_length (int): All sessions, whose turn length is",
"numbers of fields\" % key) vocab = chain_allvocab(origin_data[key], data_fields[key]) vocab_num = len(vocab) oov_num",
"resp = self.data[key]['resp'][j] res_post[i, :len(post)] = post res_resp[i, :len(resp)] = resp res[\"post_allvocabs\"] =",
"in self.key_name} else: raise TypeError('`data_fields` must be a dict, or a list, or",
"except StopIteration: break def chain_allvocab(dic, fields): vocabs = [] for data_key, field in",
"special token \"%s\". This is not allowed.' % token) origin_data[key][data_key].append(element) except StopIteration: break",
"different formats.(If `data_fields` is a list or a tuple, different datasets have the",
"vocab = chain_allvocab(origin_data[key], data_fields[key]) vocab_num = len(vocab) oov_num = sum([word not in word2id",
"returns the next label(integer). Note that it may raise StopIteration. Args:{DataField.GET_NEXT_ARG} Examples: >>>",
"= 9 >>> # vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\",",
"different fields. special_tokens = set(self.ext_vocab) origin_data = {} for key in self.key_name: origin_data[key]",
"Label()]], means that, in the raw file, the first *several lines* is a",
"form in posts. Only provide valid words. ``unk_id`` will be used if a",
"self.key_name: data[key] = {} for data_key, field in data_fields[key]: origin_data[key][data_key] = [field.convert_to_ids(element, word2id,",
"token \"%s\". This is not allowed.' % token) origin_data[key][data_key].append(element) except StopIteration: break def",
"sentence length before cut: %d, \" + \\ \"cut word rate: %f\\n\\tmax turn",
"**whole dataset** (except valid words) will be marked as invalid words. Otherwise, they",
"label. They are saved in a dict. dataset = {'post': [line1, line3, line5,",
"of fields\" % key) vocab = chain_allvocab(origin_data[key], data_fields[key]) vocab_num = len(vocab) oov_num =",
"sessions and labels, but the test set only contains sessions. min_vocab_times (int): A",
"dict. Keys are the same as self.key_name('train', 'test', 'dev', etc.). Each value is",
"fine <eos> [2, 7, 3, 0, 0], # second response: <go> hello <eos>",
"valid tokens. All tokens appear not less than `min_vocab_times` in **training set** will",
"= {key: get_fields(data_fields[key]) for key in self.key_name} except AssertionError: raise TypeError('If `data_field` is",
"return vocab_list, valid_vocab_len, data, data_size def get_batch(self, key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict): A",
"data_size: data_size[key] = len(data[key][data_key]) elif data_size[key] != len(data[key][data_key]): raise RuntimeError( \"The data of",
"10, max_sent_length, 0, 'nltk', False) loader.restart(\"train\",batch_size=2,shuffle=True) q=loader.get_next_batch(\"train\") print(len(q['score'])) print(q) if __name__ == '__main__':",
"and labels, but the test set only contains sessions. min_vocab_times (int): A cut-off",
"try: data_fields = {key: get_fields(data_fields[key]) for key in self.key_name} except AssertionError: raise TypeError('If",
"7, 3, 0, 0], # second response: <go> hello <eos> <pad> <pad> ]),",
">>> field.get_next(dataset) 1 >>> field.get_next(dataset) 0 \"\"\" score = next(dataset) return float(score.strip()) def",
"in valid_vocab_set for word in vocab]) - oov_num sent_length = [] for data_key,",
"array, the length of response in each batch. Size: ``[batch_size]`` * **resp** (:class:`numpy.ndarray`):",
"x[0] not in valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid vocab list length = %d\" % valid_vocab_len)",
"next line is a label. dataset = {'key1': [session1, session2, ...], 'key2': [label1,",
"if no_field_keys: raise ValueError('There is no data fields for dataset(%s) ' % ',",
"next label(integer). Note that it may raise StopIteration. Args:{DataField.GET_NEXT_ARG} Examples: >>> dataset =",
"key=='train': res['score']=np.array([self.data[key]['score'][i] for i in indexes]) return res def main(): max_sent_length = 50",
"x[1] >= min_vocab_times] vocab_list = self.ext_vocab + list(left_vocab) valid_vocab_len = len(vocab_list) valid_vocab_set =",
"min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital) def _load_data(self): data_fields = { 'train':",
"array containing words of id form in responses. Only provide valid vocabs. ``unk_id``",
"A string indicating the path of dataset. data_fields (dict, list, tuple): If it's",
"(int): the number of valid vocab. ``vocab_list[:valid_vocab_len]`` will be regarded as valid vocabs,",
"the number of valid vocab. ``vocab_list[:valid_vocab_len]`` will be regarded as valid vocabs, while",
"of valid vocab. ``vocab_list[:valid_vocab_len]`` will be regarded as valid vocabs, while ``vocab_list[valid_vocab_len:]`` regarded",
"field) pairs. Field must be a DataField instance, or a subclass of DataField(in",
"case, its instance will be used, assuming its constructor accepts no arguments), or",
"np.array(list(map(lambda i: len(self.data[key]['post'][i]), indexes)), dtype=int) res[\"resp_length\"] = np.array(list(map(lambda i: len(self.data[key]['resp'][i]), indexes)), dtype=int) res_post",
"left_vocab = [x[0] for x in vocab if x[1] >= min_vocab_times] vocab_list =",
"= len(vocab_list) valid_vocab_set = set(vocab_list) for key in self.key_name: if key == 'train':",
"# vocab_size = 9 >>> # vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\",",
"'test', 'dev', etc.). Each value is # a list(tuple) of lists(tuples), which means",
"is no data fields for dataset(%s) ' % ', '.join(no_field_keys)) try: data_fields =",
"All tokens appear not less than ``invalid_vocab_times`` in the **whole dataset** (except valid",
"useless. This argument exists, just to keep the signature the same as that",
"appear not less than `min_vocab_times` in **training set** will be marked as valid",
"a dataset. convert_ids_to_tokens: It's useless. This argument exists, just to keep the signature",
"vocabs = [] for data_key, field in fields: for element in dic[data_key]: vocabs.extend(field.iter_tokens(element))",
"% (file_path, key), encoding='utf-8') as f_file: while True: try: for data_key, field in",
"field in data_fields[key] if field.__class__ == Session] if session_keys: turn_length = list( map(len,",
"be ignored. invalid_vocab_times (int): A cut-off threshold of invalid tokens. All tokens appear",
"``[batch_size]`` * **resp** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form",
"a word is not valid. Size: ``[batch_size, max(sent_length)]`` * **resp_allvocabs** (:class:`numpy.ndarray`): A 2-d",
"from itertools import chain class Score(DataField): def get_next(self, dataset): r\"\"\"read text and returns",
"each batch. Size: ``[batch_size]`` * **resp** (:class:`numpy.ndarray`): A 2-d padded array containing words",
"max_sent_length, 0)) session_keys = [data_key for data_key, field in data_fields[key] if field.__class__ ==",
"* **data** (dict): a dict contains data. * **data_size** (dict): a dict contains",
"data_fields=[['post', 'Sentence'], ['label', Label]] means that, in the raw file, the first line",
"in vocab]) - oov_num sent_length = [] for data_key, field in data_fields[key]: sent_length.extend(",
"hash_value return vocab_list, valid_vocab_len, data, data_size def get_batch(self, key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict):",
"as invalid words. Otherwise, they are unknown words, which are ignored both for",
"length = %d\" % valid_vocab_len) print(\"vocab list length = %d\" % len(vocab_list)) word2id",
"have different formats.(If `data_fields` is a list or a tuple, different datasets have",
"next(dataset) return float(score.strip()) def _map_fun(self, element, convert_ids_to_tokens=None): \"\"\" Returns the element itself. Args:",
"left_vocab = [x[0] for x in vocab if x[1] >= invalid_vocab_times and x[0]",
"sess_key in session_keys)))) max_turn_length_before_cut = max(turn_length) sent_num = sum(turn_length) cut_sentence_rate = np.sum(np.maximum(np.array(turn_length) -",
"response: <go> hello <eos> <pad> <pad> ]), \"resp\": numpy.array([ [2, 8, 1, 1,",
"dataset. data_fields (dict, list, tuple): If it's a list(tuple), it must be a",
"'Sentence']], 'test': [['post', 'Sentence'], ['resp', 'Sentence']], } return self._general_load_data(self._file_path, data_fields, \\ self._min_vocab_times, self._max_sent_length,",
"encoding='utf-8') as f_file: while True: try: for data_key, field in data_fields[key]: element =",
"\"fine\"] >>> # vocab_size = 9 >>> # vocab_list = [\"<pad>\", \"<unk>\", \"<go>\",",
"the **whole dataset** (except valid words) will be marked as invalid words. Otherwise,",
"its value must be a list(or tuple) of lists(or tuples).') elif isinstance(data_fields, list)",
"dataset may have different fields. special_tokens = set(self.ext_vocab) origin_data = {} for key",
"max(sent_length)]`` * **resp_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form",
"DataField instance, or a subclass of DataField(in this case, its instance will be",
"If it's a dict, different datasets may have different formats.(If `data_fields` is a",
"[['sent', Sentence()], ['label', Label()]]}. # Note, different dataset may have different fields. special_tokens",
"invalid vocabs. Size: ``[batch_size, max(sent_length)]`` Examples: >>> # all_vocab_list = [\"<pad>\", \"<unk>\", \"<go>\",",
"with open(\"%s/%s.txt\" % (file_path, key), encoding='utf-8') as f_file: while True: try: for data_key,",
"= [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", >>> # \"hello\", \"i\", \"am\",",
"dic[data_key]: vocabs.extend(field.iter_tokens(element)) return vocabs raw_vocab_list = chain_allvocab(origin_data['train'], data_fields['train']) # Important: Sort the words",
"Examples: >>> dataset = iter([\"1\\n\", \"0\\n\"]) >>> field = Label() >>> field.get_next(dataset) 1",
"Score(DataField): def get_next(self, dataset): r\"\"\"read text and returns the next label(integer). Note that",
"f_file: while True: try: for data_key, field in data_fields[key]: element = field.convert_to_tokens(field.get_next(f_file), self.tokenize)",
"key), encoding='utf-8') as f_file: while True: try: for data_key, field in data_fields[key]: element",
"a tuple.') # now data_fields is a dict. Keys are the same as",
"data_fields[key]: sent_length.extend( [len(sent) for element in origin_data[key][data_key] for sent in field.iter_sentence(element)]) cut_word_num =",
"in self.key_name} except AssertionError: raise TypeError('If `data_field` is a dict, its value must",
"data_size[key] = len(data[key][data_key]) elif data_size[key] != len(data[key][data_key]): raise RuntimeError( \"The data of input",
"self._min_vocab_times, self._max_sent_length, None, self._invalid_vocab_times) def _general_load_data(self, file_path, data_fields, min_vocab_times, max_sent_length, max_turn_length, invalid_vocab_times): r'''This",
"dataloader.get_batch('train', [0, 1]) { \"post_allvocabs\": numpy.array([ [2, 5, 6, 10, 3], # first",
"invalid_vocab_times, \\ tokenizer, remains_capital ): super().__init__(file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital)",
"\"<go>\", \"<eos>\", \"how\", \"are\", \"you\", \"hello\", \"i\"] >>> dataloader.get_batch('train', [0, 1]) { \"post_allvocabs\":",
"A 2-d padded array containing words of id form in responses. Provide both",
"dataset): r\"\"\"read text and returns the next label(integer). Note that it may raise",
"which means (data_key(str), data_field(DataField)) pairs. # For example, # data_fields == {'train': [['sent',",
"= self.unk_id res_resp[res_resp >= self.valid_vocab_len] = self.unk_id if key=='train': res['score']=np.array([self.data[key]['score'][i] for i in",
"(list): vocabulary list of the datasets, including valid and invalid vocabs. * **valid_vocab_len**",
"Important: Sort the words preventing the index changes between # different runs vocab",
"= {'post': [line1, line3, line5, ...], 'label': [line2, line4, line6, ...]} data_fields=[['key1', 'Session'],",
"self.unk_id if key=='train': res['score']=np.array([self.data[key]['score'][i] for i in indexes]) return res def main(): max_sent_length",
"for dataset(%s) ' % ', '.join(no_field_keys)) try: data_fields = {key: get_fields(data_fields[key]) for key",
"example, # data_fields == {'train': [['sent', Sentence()], ['label', Label()]], # 'test': [['sent', Sentence()],",
"that indicate the datasets, and the values are lists as mentioned above. For",
"it must be a list of (key, field) pairs. Field must be a",
"response: <go> i <unk> <unk> <eos> [2, 7, 3, 0, 0], # second",
"<eos> <pad> <pad> ]), \"post\": numpy.array([ [2, 5, 6, 1, 3], # first",
"second line is a label. They are saved in a dict. dataset =",
"no_field_keys = [key for key in self.key_name if key not in data_fields] if",
"cut_sentence_rate = 0 print((\"%s set. invalid rate: %f, unknown rate: %f, max sentence",
"- max_sent_length, 0)) session_keys = [data_key for data_key, field in data_fields[key] if field.__class__",
"= chain_allvocab(origin_data['train'], data_fields['train']) # Important: Sort the words preventing the index changes between",
"than `min_vocab_times` in **training set** will be marked as valid words. max_sent_length (int):",
"``[batch_size]`` * **post** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form",
"the length of response in each batch. Size: ``[batch_size]`` * **resp** (:class:`numpy.ndarray`): A",
"data[key] = {} for data_key, field in data_fields[key]: origin_data[key][data_key] = [field.convert_to_ids(element, word2id, self)",
"different datasets may have different formats.(If `data_fields` is a list or a tuple,",
"= field.convert_to_tokens(field.get_next(f_file), self.tokenize) for token in field.iter_tokens(element): if token in special_tokens: raise RuntimeError(",
"will be used, assuming its constructor accepts no arguments), or a string(in this",
"field = Label() >>> field.get_next(dataset) 1 >>> field.get_next(dataset) 0 \"\"\" score = next(dataset)",
"{'post': [line1, line3, line5, ...], 'label': [line2, line4, line6, ...]} data_fields=[['key1', 'Session'], ['key2',",
"<eos> <pad> <pad> ]), \"resp_allvocabs\": numpy.array([ [2, 8, 9, 10, 3], # first",
"* **all_vocab_list** (list): vocabulary list of the datasets, including valid and invalid vocabs.",
"length of post in each batch. Size: ``[batch_size]`` * **post** (:class:`numpy.ndarray`): A 2-d",
"be regarded as valid vocabs, while ``vocab_list[valid_vocab_len:]`` regarded as invalid vocabs. * **data**",
"<go> hello <eos> <pad> <pad> ]), \"resp\": numpy.array([ [2, 8, 1, 1, 3],",
"res[\"resp_allvocabs\"] = res_resp.copy() res_post[res_post >= self.valid_vocab_len] = self.unk_id res_resp[res_resp >= self.valid_vocab_len] = self.unk_id",
"['resp', 'Sentence']], } return self._general_load_data(self._file_path, data_fields, \\ self._min_vocab_times, self._max_sent_length, None, self._invalid_vocab_times) def _general_load_data(self,",
"post in each batch. Size: ``[batch_size]`` * **post** (:class:`numpy.ndarray`): A 2-d padded array",
"* **resp** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form in",
"= 50 loader = TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length, 0, 'nltk', False) loader.restart(\"train\",batch_size=2,shuffle=True) q=loader.get_next_batch(\"train\") print(len(q['score']))",
"invalid_num / vocab_num, oov_num / vocab_num, max(sent_length), \\ cut_word_num / vocab_num, max_turn_length_before_cut, cut_sentence_rate))",
"self.tokenize) for token in field.iter_tokens(element): if token in special_tokens: raise RuntimeError( 'The dataset",
"field in fields] if isinstance(data_fields, dict): no_field_keys = [key for key in self.key_name",
"line is a label. dataset = {'key1': [session1, session2, ...], 'key2': [label1, label2,",
"Otherwise, they are unknown words, which are ignored both for model or metrics.",
"``max_sent_length`` tokens. max_turn_length (int): All sessions, whose turn length is longer than ``max_turn_length``",
"= self.ext_vocab + list(left_vocab) valid_vocab_len = len(vocab_list) valid_vocab_set = set(vocab_list) for key in",
"np.sum(np.maximum(np.array(sent_length) - max_sent_length, 0)) session_keys = [data_key for data_key, field in data_fields[key] if",
"1-d array, the length of post in each batch. Size: ``[batch_size]`` * **post**",
"have the same format). Its keys are the same as `self.key_name` that indicate",
"self._max_sent_length, None, self._invalid_vocab_times) def _general_load_data(self, file_path, data_fields, min_vocab_times, max_sent_length, max_turn_length, invalid_vocab_times): r'''This function",
"(key, field) pairs. Field must be a DataField instance, or a subclass of",
"9 >>> # vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", \"hello\",",
"<unk> <eos> [2, 7, 3, 0, 0], # second post: <go> hello <eos>",
"\"are\", \"you\", >>> # \"hello\", \"i\", \"am\", \"fine\"] >>> # vocab_size = 9",
"of dataset. data_fields (dict, list, tuple): If it's a list(tuple), it must be",
"(:class:`numpy.ndarray`): A 2-d padded array containing words of id form in posts. Only",
"x in vocab if x[1] >= invalid_vocab_times and x[0] not in valid_vocab_set] vocab_list.extend(left_vocab)",
"regarded as valid vocabs, while ``vocab_list[valid_vocab_len:]`` regarded as invalid vocabs. * **data** (dict):",
"True: try: for data_key, field in data_fields[key]: element = field.convert_to_tokens(field.get_next(f_file), self.tokenize) for token",
"\"you\", >>> # \"hello\", \"i\", \"am\", \"fine\"] >>> # vocab_size = 9 >>>",
"TypeError('If `data_field` is a dict, its value must be a list(or tuple) of",
"of id form in posts. Provide both valid and invalid vocabs. Size: ``[batch_size,",
"provide valid words. ``unk_id`` will be used if a word is not valid.",
"of input %s.txt contains different numbers of fields\" % key) vocab = chain_allvocab(origin_data[key],",
"[\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", \"hello\", \"i\"] >>> dataloader.get_batch('train', [0, 1])",
"# 'test': [['sent', Sentence()], ['label', Label()]]}. # Note, different dataset may have different",
"not in data_size: data_size[key] = len(data[key][data_key]) elif data_size[key] != len(data[key][data_key]): raise RuntimeError( \"The",
"first post: <go> are you fine <eos> [2, 7, 3, 0, 0], #",
"# all_vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", >>> # \"hello\",",
"the train set contains sessions and labels, but the test set only contains",
"data_fields, \\ self._min_vocab_times, self._max_sent_length, None, self._invalid_vocab_times) def _general_load_data(self, file_path, data_fields, min_vocab_times, max_sent_length, max_turn_length,",
"if key=='train': res['score']=np.array([self.data[key]['score'][i] for i in indexes]) return res def main(): max_sent_length =",
"saved in a dict. dataset = {'post': [line1, line3, line5, ...], 'label': [line2,",
"== 'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0]))",
"different datasets have the same format). Its keys are the same as `self.key_name`",
"subclass of DataField(in this case, its instance will be used, assuming its constructor",
"Session] if session_keys: turn_length = list( map(len, chain.from_iterable((origin_data[key][sess_key] for sess_key in session_keys)))) max_turn_length_before_cut",
"a dict contains data. * **data_size** (dict): a dict contains size of each",
"session_keys: turn_length = list( map(len, chain.from_iterable((origin_data[key][sess_key] for sess_key in session_keys)))) max_turn_length_before_cut = max(turn_length)",
"cotk.dataloader.dataloader import * from collections import Counter import numpy as np from itertools",
"field.convert_to_tokens(field.get_next(f_file), self.tokenize) for token in field.iter_tokens(element): if token in special_tokens: raise RuntimeError( 'The",
"different dataset may have different fields. special_tokens = set(self.ext_vocab) origin_data = {} for",
"__init__(self, file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital ): super().__init__(file_id, min_vocab_times, \\",
"get_fields(fields): assert isinstance(fields, list) or isinstance(fields, tuple) return [(data_key, DataField.get_field(field)) for data_key, field",
"min_vocab_times] vocab_list = self.ext_vocab + list(left_vocab) valid_vocab_len = len(vocab_list) valid_vocab_set = set(vocab_list) for",
"'test': [['sent', Sentence()], ['label', Label()]]}. # Note, different dataset may have different fields.",
"fields): vocabs = [] for data_key, field in fields: for element in dic[data_key]:",
"data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value = hash_value return vocab_list, valid_vocab_len, data, data_size def get_batch(self,",
"Field must be a DataField instance, or a subclass of DataField(in this case,",
"StopIteration: break def chain_allvocab(dic, fields): vocabs = [] for data_key, field in fields:",
"For example, data_fields = {'train': [['sess', 'Session'], ['label', 'Label']], 'test': [['sess', 'session']]}, means",
"'label': [line2, line4, line6, ...]} data_fields=[['key1', 'Session'], ['key2', Label()]], means that, in the",
"used, assuming its constructor accepts no arguments), or a string(in this case, the",
"while True: try: for data_key, field in data_fields[key]: element = field.convert_to_tokens(field.get_next(f_file), self.tokenize) for",
"line is a sentence and the second line is a label. They are",
"['resp', 'Sentence'], ['score', Score]], 'dev': [['post', 'Sentence'], ['resp', 'Sentence']], 'test': [['post', 'Sentence'], ['resp',",
"means that, in the raw file, the first *several lines* is a session,",
"**resp** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form in responses.",
"form in responses. Only provide valid vocabs. ``unk_id`` will be used if a",
"for data_key, _ in data_fields[key]} with open(\"%s/%s.txt\" % (file_path, key), encoding='utf-8') as f_file:",
"res['score']=np.array([self.data[key]['score'][i] for i in indexes]) return res def main(): max_sent_length = 50 loader",
"vocabs. * **valid_vocab_len** (int): the number of valid vocab. ``vocab_list[:valid_vocab_len]`` will be regarded",
"def get_batch(self, key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict): A dict at least contains: *",
"A 2-d padded array containing words of id form in posts. Only provide",
"or a string(in this case, the instance of the class, whose __name__ is",
"rate: %f, unknown rate: %f, max sentence length before cut: %d, \" +",
"in posts. Only provide valid words. ``unk_id`` will be used if a word",
"Size: ``[batch_size, max(sent_length)]`` * **post_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words of",
"sessions. min_vocab_times (int): A cut-off threshold of valid tokens. All tokens appear not",
"tuple): If it's a list(tuple), it must be a list of (key, field)",
"data_fields[key]} with open(\"%s/%s.txt\" % (file_path, key), encoding='utf-8') as f_file: while True: try: for",
"is not valid. Size: ``[batch_size, max(sent_length)]`` * **resp_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array",
"main(): max_sent_length = 50 loader = TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length, 0, 'nltk', False) loader.restart(\"train\",batch_size=2,shuffle=True)",
"first response: <go> i <unk> <unk> <eos> [2, 7, 3, 0, 0], #",
"may have different formats.(If `data_fields` is a list or a tuple, different datasets",
"tuple.') # now data_fields is a dict. Keys are the same as self.key_name('train',",
"This is not allowed.' % token) origin_data[key][data_key].append(element) except StopIteration: break def chain_allvocab(dic, fields):",
"[2, 7, 3, 0, 0], # second response: <go> hello <eos> <pad> <pad>",
"invalid_vocab_times (int): A cut-off threshold of invalid tokens. All tokens appear not less",
"...]} If it's a dict, different datasets may have different formats.(If `data_fields` is",
"in vocab]) invalid_num = sum([word not in valid_vocab_set for word in vocab]) -",
"as valid words. max_sent_length (int): All sentences longer than ``max_sent_length`` will be shortened",
"**valid_vocab_len** (int): the number of valid vocab. ``vocab_list[:valid_vocab_len]`` will be regarded as valid",
"words preventing the index changes between # different runs vocab = sorted(Counter(raw_vocab_list).most_common(), \\",
"than ``max_turn_length`` will be shorten to first ``max_turn_length`` sentences. If the dataset don't",
"res_post = res[\"post\"] = np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int) res_resp = res[\"resp\"] = np.zeros((batch_size, np.max(res[\"resp_length\"])),",
"used if a word is not valid. Size: ``[batch_size, max(sent_length)]`` * **resp_allvocabs** (:class:`numpy.ndarray`):",
"in self.key_name: origin_data[key] = {data_key: [] for data_key, _ in data_fields[key]} with open(\"%s/%s.txt\"",
"of super class. \"\"\" return element class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def __init__(self, file_id, min_vocab_times,",
"value hash_value = DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value = hash_value",
"that it may raise StopIteration. Args:{DataField.GET_NEXT_ARG} Examples: >>> dataset = iter([\"1\\n\", \"0\\n\"]) >>>",
"threshold of invalid tokens. All tokens appear not less than ``invalid_vocab_times`` in the",
"in data_size: data_size[key] = len(data[key][data_key]) elif data_size[key] != len(data[key][data_key]): raise RuntimeError( \"The data",
"fields. special_tokens = set(self.ext_vocab) origin_data = {} for key in self.key_name: origin_data[key] =",
"6, 1, 3], # first post: <go> are you <unk> <eos> [2, 7,",
"= {'train': [['sess', 'Session'], ['label', 'Label']], 'test': [['sess', 'session']]}, means that the train",
"changes between # different runs vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0]))",
"words, which are ignored both for model or metrics. Returns: (tuple): containing: *",
"# second post: <go> hello <eos> <pad> <pad> ]), \"post\": numpy.array([ [2, 5,",
"return res def main(): max_sent_length = 50 loader = TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length, 0,",
"self.valid_vocab_len] = self.unk_id res_resp[res_resp >= self.valid_vocab_len] = self.unk_id if key=='train': res['score']=np.array([self.data[key]['score'][i] for i",
"used). For example, data_fields=[['post', 'Sentence'], ['label', Label]] means that, in the raw file,",
"min_vocab_times (int): A cut-off threshold of valid tokens. All tokens appear not less",
"# length of posts \"resp_length\": numpy.array([5, 3]), # length of responses } '''",
"chain_allvocab(dic, fields): vocabs = [] for data_key, field in fields: for element in",
"max(sent_length), \\ cut_word_num / vocab_num, max_turn_length_before_cut, cut_sentence_rate)) # calculate hash value hash_value =",
"A cut-off threshold of valid tokens. All tokens appear not less than `min_vocab_times`",
"return float(score.strip()) def _map_fun(self, element, convert_ids_to_tokens=None): \"\"\" Returns the element itself. Args: element:",
"valid_vocab_set = set(vocab_list) for key in self.key_name: if key == 'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key],",
"[2, 5, 6, 10, 3], # first post: <go> are you fine <eos>",
"valid words) will be marked as invalid words. Otherwise, they are unknown words,",
"\"you\", \"hello\", \"i\"] >>> dataloader.get_batch('train', [0, 1]) { \"post_allvocabs\": numpy.array([ [2, 5, 6,",
"be shortened to first ``max_sent_length`` tokens. max_turn_length (int): All sessions, whose turn length",
"# first post: <go> are you <unk> <eos> [2, 7, 3, 0, 0],",
"[['sess', 'Session'], ['label', 'Label']], 'test': [['sess', 'session']]}, means that the train set contains",
"invalid rate: %f, unknown rate: %f, max sentence length before cut: %d, \"",
"vocab_size = 9 >>> # vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\",",
"continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab =",
"'session']]}, means that the train set contains sessions and labels, but the test",
"assert isinstance(fields, list) or isinstance(fields, tuple) return [(data_key, DataField.get_field(field)) for data_key, field in",
"containing: * **all_vocab_list** (list): vocabulary list of the datasets, including valid and invalid",
"as mentioned above. For example, data_fields = {'train': [['sess', 'Session'], ['label', 'Label']], 'test':",
"1 cut_sentence_rate = 0 print((\"%s set. invalid rate: %f, unknown rate: %f, max",
"don't contains sessions, this parameter will be ignored. invalid_vocab_times (int): A cut-off threshold",
">>> field = Label() >>> field.get_next(dataset) 1 >>> field.get_next(dataset) 0 \"\"\" score =",
"get_fields(data_fields[key]) for key in self.key_name} except AssertionError: raise TypeError('If `data_field` is a dict,",
"if x[1] >= invalid_vocab_times and x[0] not in valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid vocab list",
"if key not in data_fields] if no_field_keys: raise ValueError('There is no data fields",
"input %s.txt contains different numbers of fields\" % key) vocab = chain_allvocab(origin_data[key], data_fields[key])",
"vocab. ``vocab_list[:valid_vocab_len]`` will be regarded as valid vocabs, while ``vocab_list[valid_vocab_len:]`` regarded as invalid",
"vocab if x[1] >= invalid_vocab_times and x[0] not in valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid vocab",
"vocab]) - oov_num sent_length = [] for data_key, field in data_fields[key]: sent_length.extend( [len(sent)",
"Sentence()], ['label', Label()]]}. # Note, different dataset may have different fields. special_tokens =",
"key in self.key_name if key not in data_fields] if no_field_keys: raise ValueError('There is",
"arguments), or a string(in this case, the instance of the class, whose __name__",
"are lists as mentioned above. For example, data_fields = {'train': [['sess', 'Session'], ['label',",
"\"cut word rate: %f\\n\\tmax turn length before cut: %d, cut sentence rate: %f\")",
"= [x[0] for x in vocab if x[1] >= min_vocab_times] vocab_list = self.ext_vocab",
"field.__class__ == Session] if session_keys: turn_length = list( map(len, chain.from_iterable((origin_data[key][sess_key] for sess_key in",
"%s.\" % key) res = {} batch_size = len(indexes) res[\"post_length\"] = np.array(list(map(lambda i:",
"is not allowed.' % token) origin_data[key][data_key].append(element) except StopIteration: break def chain_allvocab(dic, fields): vocabs",
"1, 3], # first response: <go> i <unk> <unk> <eos> [2, 7, 3,",
"or metrics. Returns: (tuple): containing: * **all_vocab_list** (list): vocabulary list of the datasets,",
"oov_num = sum([word not in word2id for word in vocab]) invalid_num = sum([word",
"key in self.key_name: origin_data[key] = {data_key: [] for data_key, _ in data_fields[key]} with",
"8, 1, 1, 3], # first response: <go> i <unk> <unk> <eos> [2,",
"from collections import Counter import numpy as np from itertools import chain class",
"id form in posts. Only provide valid words. ``unk_id`` will be used if",
"line3, line5, ...], 'label': [line2, line4, line6, ...]} data_fields=[['key1', 'Session'], ['key2', Label()]], means",
"padded array containing words of id form in posts. Provide both valid and",
"= np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int) res_resp = res[\"resp\"] = np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int) for i,",
"(data_key(str), data_field(DataField)) pairs. # For example, # data_fields == {'train': [['sent', Sentence()], ['label',",
"= sum([word not in word2id for word in vocab]) invalid_num = sum([word not",
"above. For example, data_fields = {'train': [['sess', 'Session'], ['label', 'Label']], 'test': [['sess', 'session']]},",
"Each value is # a list(tuple) of lists(tuples), which means (data_key(str), data_field(DataField)) pairs.",
"max_turn_length_before_cut, cut_sentence_rate)) # calculate hash value hash_value = DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data, data_fields,",
"# now data_fields is a dict. Keys are the same as self.key_name('train', 'test',",
"\"am\", \"fine\"] >>> # vocab_size = 9 >>> # vocab_list = [\"<pad>\", \"<unk>\",",
"= set(self.ext_vocab) origin_data = {} for key in self.key_name: origin_data[key] = {data_key: []",
"np.max(res[\"resp_length\"])), dtype=int) for i, j in enumerate(indexes): post = self.data[key]['post'][j] resp = self.data[key]['resp'][j]",
"in origin_data[key][data_key]] if key not in data_size: data_size[key] = len(data[key][data_key]) elif data_size[key] !=",
"is a dict, its value must be a list(or tuple) of lists(or tuples).')",
"*several lines* is a session, *followed by an empty line*, and the next",
"\"<go>\", \"<eos>\", \"how\", \"are\", \"you\", >>> # \"hello\", \"i\", \"am\", \"fine\"] >>> #",
"0, 0], # second post: <go> hello <eos> <pad> <pad> ]), \"resp_allvocabs\": numpy.array([",
"\"0\\n\"]) >>> field = Label() >>> field.get_next(dataset) 1 >>> field.get_next(dataset) 0 \"\"\" score",
"max_sent_length, 0, 'nltk', False) loader.restart(\"train\",batch_size=2,shuffle=True) q=loader.get_next_batch(\"train\") print(len(q['score'])) print(q) if __name__ == '__main__': main()",
"before cut: %d, \" + \\ \"cut word rate: %f\\n\\tmax turn length before",
"(key, invalid_num / vocab_num, oov_num / vocab_num, max(sent_length), \\ cut_word_num / vocab_num, max_turn_length_before_cut,",
"Counter import numpy as np from itertools import chain class Score(DataField): def get_next(self,",
"(:class:`numpy.ndarray`): A 1-d array, the length of response in each batch. Size: ``[batch_size]``",
"in field.iter_sentence(element)]) cut_word_num = np.sum(np.maximum(np.array(sent_length) - max_sent_length, 0)) session_keys = [data_key for data_key,",
"= %d\" % valid_vocab_len) print(\"vocab list length = %d\" % len(vocab_list)) word2id =",
"% len(vocab_list)) word2id = {w: i for i, w in enumerate(vocab_list)} data =",
"be a dict, or a list, or a tuple.') # now data_fields is",
"np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int) for i, j in enumerate(indexes): post = self.data[key]['post'][j] resp =",
"invalid_vocab_times): r'''This function implements a general loading process. Arguments: file_path (str): A string",
"self.data[key]['resp'][j] res_post[i, :len(post)] = post res_resp[i, :len(resp)] = resp res[\"post_allvocabs\"] = res_post.copy() res[\"resp_allvocabs\"]",
"turn length is longer than ``max_turn_length`` will be shorten to first ``max_turn_length`` sentences.",
"is a sentence and the second line is a label. They are saved",
"of response in each batch. Size: ``[batch_size]`` * **resp** (:class:`numpy.ndarray`): A 2-d padded",
"A 2-d padded array containing words of id form in posts. Provide both",
"``vocab_list[valid_vocab_len:]`` regarded as invalid vocabs. * **data** (dict): a dict contains data. *",
"list( map(len, chain.from_iterable((origin_data[key][sess_key] for sess_key in session_keys)))) max_turn_length_before_cut = max(turn_length) sent_num = sum(turn_length)",
"session, *followed by an empty line*, and the next line is a label.",
"<pad> <pad> ]), \"resp_allvocabs\": numpy.array([ [2, 8, 9, 10, 3], # first response:",
"for element in origin_data[key][data_key]] if key not in data_size: data_size[key] = len(data[key][data_key]) elif",
"as that of super class. \"\"\" return element class TranslationWithScore(cotk.dataloader.SingleTurnDialog): @cotk._utils.hooks.hook_dataloader def __init__(self,",
"is field, will be used). For example, data_fields=[['post', 'Sentence'], ['label', Label]] means that,",
"the next line is a label. dataset = {'key1': [session1, session2, ...], 'key2':",
"response: <go> i am fine <eos> [2, 7, 3, 0, 0], # second",
"Returns: (tuple): containing: * **all_vocab_list** (list): vocabulary list of the datasets, including valid",
"different runs vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab = [x[0]",
"key) res = {} batch_size = len(indexes) res[\"post_length\"] = np.array(list(map(lambda i: len(self.data[key]['post'][i]), indexes)),",
"print(\"vocab list length = %d\" % len(vocab_list)) word2id = {w: i for i,",
"'test': [['sess', 'session']]}, means that the train set contains sessions and labels, but",
"in field.iter_tokens(element): if token in special_tokens: raise RuntimeError( 'The dataset contains special token",
"element itself. Args: element: An element of a dataset. convert_ids_to_tokens: It's useless. This",
"in data_fields[key]: element = field.convert_to_tokens(field.get_next(f_file), self.tokenize) for token in field.iter_tokens(element): if token in",
"dataset = iter([\"1\\n\", \"0\\n\"]) >>> field = Label() >>> field.get_next(dataset) 1 >>> field.get_next(dataset)",
"<go> hello <eos> <pad> <pad> ]), \"resp_allvocabs\": numpy.array([ [2, 8, 9, 10, 3],",
"else: max_turn_length_before_cut = 1 cut_sentence_rate = 0 print((\"%s set. invalid rate: %f, unknown",
"a dict, different datasets may have different formats.(If `data_fields` is a list or",
"or isinstance(fields, tuple) return [(data_key, DataField.get_field(field)) for data_key, field in fields] if isinstance(data_fields,",
"from cotk._utils.file_utils import get_resource_file_path from cotk.dataloader.dataloader import * from collections import Counter import",
"/ sent_num else: max_turn_length_before_cut = 1 cut_sentence_rate = 0 print((\"%s set. invalid rate:",
"id form in responses. Only provide valid vocabs. ``unk_id`` will be used if",
"9, 10, 3], # first response: <go> i am fine <eos> [2, 7,",
"be a list of (key, field) pairs. Field must be a DataField instance,",
"both for model or metrics. Returns: (tuple): containing: * **all_vocab_list** (list): vocabulary list",
"length before cut: %d, \" + \\ \"cut word rate: %f\\n\\tmax turn length",
"string(in this case, the instance of the class, whose __name__ is field, will",
"= list( map(len, chain.from_iterable((origin_data[key][sess_key] for sess_key in session_keys)))) max_turn_length_before_cut = max(turn_length) sent_num =",
"[2, 5, 6, 1, 3], # first post: <go> are you <unk> <eos>",
"exists, just to keep the signature the same as that of super class.",
"padded array containing words of id form in responses. Provide both valid and",
"= %d\" % len(vocab_list)) word2id = {w: i for i, w in enumerate(vocab_list)}",
"for data_key, field in data_fields[key] if field.__class__ == Session] if session_keys: turn_length =",
"in data_fields] if no_field_keys: raise ValueError('There is no data fields for dataset(%s) '",
"provide valid vocabs. ``unk_id`` will be used if a word is not valid.",
"sent in field.iter_sentence(element)]) cut_word_num = np.sum(np.maximum(np.array(sent_length) - max_sent_length, 0)) session_keys = [data_key for",
"parameter will be ignored. invalid_vocab_times (int): A cut-off threshold of invalid tokens. All",
"vocab_num, max(sent_length), \\ cut_word_num / vocab_num, max_turn_length_before_cut, cut_sentence_rate)) # calculate hash value hash_value",
"in valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid vocab list length = %d\" % valid_vocab_len) print(\"vocab list",
"of (key, field) pairs. Field must be a DataField instance, or a subclass",
"batch. Size: ``[batch_size]`` * **resp** (:class:`numpy.ndarray`): A 2-d padded array containing words of",
"threshold of valid tokens. All tokens appear not less than `min_vocab_times` in **training",
"as invalid vocabs. * **data** (dict): a dict contains data. * **data_size** (dict):",
"not in self.key_name: raise ValueError(\"No set named %s.\" % key) res = {}",
"a sentence and the second line is a label. They are saved in",
"\\ (key, invalid_num / vocab_num, oov_num / vocab_num, max(sent_length), \\ cut_word_num / vocab_num,",
"data_fields=[['key1', 'Session'], ['key2', Label()]], means that, in the raw file, the first *several",
"words. max_sent_length (int): All sentences longer than ``max_sent_length`` will be shortened to first",
"def _map_fun(self, element, convert_ids_to_tokens=None): \"\"\" Returns the element itself. Args: element: An element",
"float(score.strip()) def _map_fun(self, element, convert_ids_to_tokens=None): \"\"\" Returns the element itself. Args: element: An",
"[\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", >>> # \"hello\", \"i\", \"am\", \"fine\"]",
"marked as invalid words. Otherwise, they are unknown words, which are ignored both",
"[] for data_key, field in data_fields[key]: sent_length.extend( [len(sent) for element in origin_data[key][data_key] for",
"word2id, self) for element in origin_data[key][data_key]] data[key][data_key] = [ field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length) for",
"<go> i <unk> <unk> <eos> [2, 7, 3, 0, 0], # second response:",
"import chain class Score(DataField): def get_next(self, dataset): r\"\"\"read text and returns the next",
"(:class:`numpy.ndarray`): A 2-d padded array containing words of id form in responses. Provide",
"containing words of id form in posts. Only provide valid words. ``unk_id`` will",
"'The dataset contains special token \"%s\". This is not allowed.' % token) origin_data[key][data_key].append(element)",
"for key in self.key_name: if key == 'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab =",
"different numbers of fields\" % key) vocab = chain_allvocab(origin_data[key], data_fields[key]) vocab_num = len(vocab)",
"\"The data of input %s.txt contains different numbers of fields\" % key) vocab",
"'Session'], ['label', 'Label']], 'test': [['sess', 'session']]}, means that the train set contains sessions",
"= res[\"post\"] = np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int) res_resp = res[\"resp\"] = np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int)",
"super().__init__(file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital) def _load_data(self): data_fields = {",
"'train': [['post', 'Sentence'], ['resp', 'Sentence'], ['score', Score]], 'dev': [['post', 'Sentence'], ['resp', 'Sentence']], 'test':",
"a list or a tuple, different datasets have the same format). Its keys",
"<pad> ]), \"resp_allvocabs\": numpy.array([ [2, 8, 9, 10, 3], # first response: <go>",
"(-pair[1], pair[0])) left_vocab = [x[0] for x in vocab if x[1] >= invalid_vocab_times",
"%f, unknown rate: %f, max sentence length before cut: %d, \" + \\",
"word2id for word in vocab]) invalid_num = sum([word not in valid_vocab_set for word",
"**all_vocab_list** (list): vocabulary list of the datasets, including valid and invalid vocabs. *",
"data_key, field in fields] if isinstance(data_fields, dict): no_field_keys = [key for key in",
"0], # second response: <go> hello <eos> <pad> <pad> ]), \"post_length\": numpy.array([5, 3]),",
"this case, its instance will be used, assuming its constructor accepts no arguments),",
"def chain_allvocab(dic, fields): vocabs = [] for data_key, field in fields: for element",
"for element in origin_data[key][data_key] for sent in field.iter_sentence(element)]) cut_word_num = np.sum(np.maximum(np.array(sent_length) - max_sent_length,",
"post: <go> hello <eos> <pad> <pad> ]), \"post\": numpy.array([ [2, 5, 6, 1,",
"posts \"resp_length\": numpy.array([5, 3]), # length of responses } ''' if key not",
"be used, assuming its constructor accepts no arguments), or a string(in this case,",
"contains sessions. min_vocab_times (int): A cut-off threshold of valid tokens. All tokens appear",
"3, 0, 0], # second post: <go> hello <eos> <pad> <pad> ]), \"post\":",
"invalid vocabs. * **valid_vocab_len** (int): the number of valid vocab. ``vocab_list[:valid_vocab_len]`` will be",
"a label. They are saved in a dict. dataset = {'post': [line1, line3,",
"{w: i for i, w in enumerate(vocab_list)} data = {} data_size = {}",
"words. ``unk_id`` will be used if a word is not valid. Size: ``[batch_size,",
"field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length) for element in origin_data[key][data_key]] if key not in data_size: data_size[key]",
"cut_word_num = np.sum(np.maximum(np.array(sent_length) - max_sent_length, 0)) session_keys = [data_key for data_key, field in",
"*followed by an empty line*, and the next line is a label. dataset",
"set contains sessions and labels, but the test set only contains sessions. min_vocab_times",
"in each batch. Size: ``[batch_size]`` * **resp** (:class:`numpy.ndarray`): A 2-d padded array containing",
"i: len(self.data[key]['resp'][i]), indexes)), dtype=int) res_post = res[\"post\"] = np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int) res_resp =",
"oov_num / vocab_num, max(sent_length), \\ cut_word_num / vocab_num, max_turn_length_before_cut, cut_sentence_rate)) # calculate hash",
"is a list or a tuple, different datasets have the same format). Its",
"key not in self.key_name: raise ValueError(\"No set named %s.\" % key) res =",
"field.iter_sentence(element)]) cut_word_num = np.sum(np.maximum(np.array(sent_length) - max_sent_length, 0)) session_keys = [data_key for data_key, field",
"for key in self.key_name if key not in data_fields] if no_field_keys: raise ValueError('There",
"are the same as self.key_name('train', 'test', 'dev', etc.). Each value is # a",
"cut: %d, \" + \\ \"cut word rate: %f\\n\\tmax turn length before cut:",
"break def chain_allvocab(dic, fields): vocabs = [] for data_key, field in fields: for",
"i, w in enumerate(vocab_list)} data = {} data_size = {} for key in",
"the words preventing the index changes between # different runs vocab = sorted(Counter(raw_vocab_list).most_common(),",
"loader = TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length, 0, 'nltk', False) loader.restart(\"train\",batch_size=2,shuffle=True) q=loader.get_next_batch(\"train\") print(len(q['score'])) print(q) if",
"in dic[data_key]: vocabs.extend(field.iter_tokens(element)) return vocabs raw_vocab_list = chain_allvocab(origin_data['train'], data_fields['train']) # Important: Sort the",
"0, 0], # second post: <go> hello <eos> <pad> <pad> ]), \"post\": numpy.array([",
"a session, *followed by an empty line*, and the next line is a",
"2-d padded array containing words of id form in posts. Provide both valid",
"posts. Provide both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` * **resp_length** (:class:`numpy.ndarray`):",
"in data_fields[key]: sent_length.extend( [len(sent) for element in origin_data[key][data_key] for sent in field.iter_sentence(element)]) cut_word_num",
"print(\"valid vocab list length = %d\" % valid_vocab_len) print(\"vocab list length = %d\"",
"instance will be used, assuming its constructor accepts no arguments), or a string(in",
"values are lists as mentioned above. For example, data_fields = {'train': [['sess', 'Session'],",
"token in special_tokens: raise RuntimeError( 'The dataset contains special token \"%s\". This is",
"preventing the index changes between # different runs vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda",
"{data_key: [] for data_key, _ in data_fields[key]} with open(\"%s/%s.txt\" % (file_path, key), encoding='utf-8')",
"['label', Label]] means that, in the raw file, the first line is a",
"dict. dataset = {'post': [line1, line3, line5, ...], 'label': [line2, line4, line6, ...]}",
"token) origin_data[key][data_key].append(element) except StopIteration: break def chain_allvocab(dic, fields): vocabs = [] for data_key,",
"5, 6, 1, 3], # first post: <go> are you <unk> <eos> [2,",
"label(integer). Note that it may raise StopIteration. Args:{DataField.GET_NEXT_ARG} Examples: >>> dataset = iter([\"1\\n\",",
"[2, 8, 9, 10, 3], # first response: <go> i am fine <eos>",
"= { 'train': [['post', 'Sentence'], ['resp', 'Sentence'], ['score', Score]], 'dev': [['post', 'Sentence'], ['resp',",
"vocab_num = len(vocab) oov_num = sum([word not in word2id for word in vocab])",
"in self.key_name: if key == 'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab = sorted(Counter(raw_vocab_list).most_common(), \\",
"Sentence()], ['label', Label()]], # 'test': [['sent', Sentence()], ['label', Label()]]}. # Note, different dataset",
"1]) { \"post_allvocabs\": numpy.array([ [2, 5, 6, 10, 3], # first post: <go>",
"in vocab if x[1] >= invalid_vocab_times and x[0] not in valid_vocab_set] vocab_list.extend(left_vocab) print(\"valid",
"dict, its value must be a list(or tuple) of lists(or tuples).') elif isinstance(data_fields,",
"word2id = {w: i for i, w in enumerate(vocab_list)} data = {} data_size",
"numpy.array([5, 3]), # length of responses } ''' if key not in self.key_name:",
"== {'train': [['sent', Sentence()], ['label', Label()]], # 'test': [['sent', Sentence()], ['label', Label()]]}. #",
"[session1, session2, ...], 'key2': [label1, label2, ...]} If it's a dict, different datasets",
"a dict, or a list, or a tuple.') # now data_fields is a",
"import cotk from cotk._utils.file_utils import get_resource_file_path from cotk.dataloader.dataloader import * from collections import",
"len(vocab) oov_num = sum([word not in word2id for word in vocab]) invalid_num =",
"\\ tokenizer, remains_capital ): super().__init__(file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital) def",
"if x[1] >= min_vocab_times] vocab_list = self.ext_vocab + list(left_vocab) valid_vocab_len = len(vocab_list) valid_vocab_set",
"max_sent_length = 50 loader = TranslationWithScore('./data/iwslt14_raml', 10, max_sent_length, 0, 'nltk', False) loader.restart(\"train\",batch_size=2,shuffle=True) q=loader.get_next_batch(\"train\")",
">>> # vocab_size = 9 >>> # vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\",",
"for data_key, field in fields: for element in dic[data_key]: vocabs.extend(field.iter_tokens(element)) return vocabs raw_vocab_list",
"A dict at least contains: * **post_length** (:class:`numpy.ndarray`): A 1-d array, the length",
"of id form in posts. Only provide valid words. ``unk_id`` will be used",
"post = self.data[key]['post'][j] resp = self.data[key]['resp'][j] res_post[i, :len(post)] = post res_resp[i, :len(resp)] =",
"empty line*, and the next line is a label. dataset = {'key1': [session1,",
"for i in indexes]) return res def main(): max_sent_length = 50 loader =",
"of post in each batch. Size: ``[batch_size]`` * **post** (:class:`numpy.ndarray`): A 2-d padded",
"unk_id=self.unk_id).hash_datasets(data, data_fields, vocab_list[len( self.ext_vocab):valid_vocab_len]) self.__hash_value = hash_value return vocab_list, valid_vocab_len, data, data_size def",
"# second post: <go> hello <eos> <pad> <pad> ]), \"resp_allvocabs\": numpy.array([ [2, 8,",
"example, data_fields=[['post', 'Sentence'], ['label', Label]] means that, in the raw file, the first",
"and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` * **resp_length** (:class:`numpy.ndarray`): A 1-d array, the",
"1, 1, 3], # first response: <go> i <unk> <unk> <eos> [2, 7,",
"data_fields (dict, list, tuple): If it's a list(tuple), it must be a list",
"sessions, this parameter will be ignored. invalid_vocab_times (int): A cut-off threshold of invalid",
"[2, 7, 3, 0, 0], # second post: <go> hello <eos> <pad> <pad>",
"will be shortened to first ``max_sent_length`` tokens. max_turn_length (int): All sessions, whose turn",
"vocab_list = [\"<pad>\", \"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", \"hello\", \"i\"] >>> dataloader.get_batch('train',",
"is a label. They are saved in a dict. dataset = {'post': [line1,",
"max(turn_length) sent_num = sum(turn_length) cut_sentence_rate = np.sum(np.maximum(np.array(turn_length) - max_turn_length, 0)) / sent_num else:",
"may raise StopIteration. Args:{DataField.GET_NEXT_ARG} Examples: >>> dataset = iter([\"1\\n\", \"0\\n\"]) >>> field =",
"be marked as valid words. max_sent_length (int): All sentences longer than ``max_sent_length`` will",
"def _load_data(self): data_fields = { 'train': [['post', 'Sentence'], ['resp', 'Sentence'], ['score', Score]], 'dev':",
"['key2', Label()]], means that, in the raw file, the first *several lines* is",
"[['sess', 'session']]}, means that the train set contains sessions and labels, but the",
"res_resp.copy() res_post[res_post >= self.valid_vocab_len] = self.unk_id res_resp[res_resp >= self.valid_vocab_len] = self.unk_id if key=='train':",
"first ``max_sent_length`` tokens. max_turn_length (int): All sessions, whose turn length is longer than",
"field in data_fields[key]: element = field.convert_to_tokens(field.get_next(f_file), self.tokenize) for token in field.iter_tokens(element): if token",
"raw_vocab_list = chain_allvocab(origin_data['train'], data_fields['train']) # Important: Sort the words preventing the index changes",
"is a label. dataset = {'key1': [session1, session2, ...], 'key2': [label1, label2, ...]}",
"it's a dict, different datasets may have different formats.(If `data_fields` is a list",
"in data_fields[key]} with open(\"%s/%s.txt\" % (file_path, key), encoding='utf-8') as f_file: while True: try:",
"each batch. Size: ``[batch_size]`` * **post** (:class:`numpy.ndarray`): A 2-d padded array containing words",
"invalid_vocab_times, \\ tokenizer, remains_capital) def _load_data(self): data_fields = { 'train': [['post', 'Sentence'], ['resp',",
"of lists(tuples), which means (data_key(str), data_field(DataField)) pairs. # For example, # data_fields ==",
"are saved in a dict. dataset = {'post': [line1, line3, line5, ...], 'label':",
"self.key_name if key not in data_fields] if no_field_keys: raise ValueError('There is no data",
"\"<unk>\", \"<go>\", \"<eos>\", \"how\", \"are\", \"you\", \"hello\", \"i\"] >>> dataloader.get_batch('train', [0, 1]) {",
"10, 3], # first post: <go> are you fine <eos> [2, 7, 3,",
"example, data_fields = {'train': [['sess', 'Session'], ['label', 'Label']], 'test': [['sess', 'session']]}, means that",
"vocabs. * **data** (dict): a dict contains data. * **data_size** (dict): a dict",
"metrics. Returns: (tuple): containing: * **all_vocab_list** (list): vocabulary list of the datasets, including",
"the same as `self.key_name` that indicate the datasets, and the values are lists",
"which are ignored both for model or metrics. Returns: (tuple): containing: * **all_vocab_list**",
"origin_data[key][data_key] = [field.convert_to_ids(element, word2id, self) for element in origin_data[key][data_key]] data[key][data_key] = [ field.cut(element,",
"[label1, label2, ...]} If it's a dict, different datasets may have different formats.(If",
"indexes)), dtype=int) res_post = res[\"post\"] = np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int) res_resp = res[\"resp\"] =",
"dtype=int) res[\"resp_length\"] = np.array(list(map(lambda i: len(self.data[key]['resp'][i]), indexes)), dtype=int) res_post = res[\"post\"] = np.zeros((batch_size,",
"must be a DataField instance, or a subclass of DataField(in this case, its",
"of invalid tokens. All tokens appear not less than ``invalid_vocab_times`` in the **whole",
"= {} for data_key, field in data_fields[key]: origin_data[key][data_key] = [field.convert_to_ids(element, word2id, self) for",
"<pad> <pad> ]), \"resp\": numpy.array([ [2, 8, 1, 1, 3], # first response:",
"= np.array(list(map(lambda i: len(self.data[key]['resp'][i]), indexes)), dtype=int) res_post = res[\"post\"] = np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int)",
"3]), # length of responses } ''' if key not in self.key_name: raise",
"self.key_name} except AssertionError: raise TypeError('If `data_field` is a dict, its value must be",
"res_resp = res[\"resp\"] = np.zeros((batch_size, np.max(res[\"resp_length\"])), dtype=int) for i, j in enumerate(indexes): post",
"= [key for key in self.key_name if key not in data_fields] if no_field_keys:",
"but the test set only contains sessions. min_vocab_times (int): A cut-off threshold of",
"dataset** (except valid words) will be marked as invalid words. Otherwise, they are",
"element in dic[data_key]: vocabs.extend(field.iter_tokens(element)) return vocabs raw_vocab_list = chain_allvocab(origin_data['train'], data_fields['train']) # Important: Sort",
"7, 3, 0, 0], # second post: <go> hello <eos> <pad> <pad> ]),",
"iter([\"1\\n\", \"0\\n\"]) >>> field = Label() >>> field.get_next(dataset) 1 >>> field.get_next(dataset) 0 \"\"\"",
"# first post: <go> are you fine <eos> [2, 7, 3, 0, 0],",
"a list(or tuple) of lists(or tuples).') elif isinstance(data_fields, list) or isinstance(data_fields, tuple): data_fields",
"data. * **data_size** (dict): a dict contains size of each item in data.",
"loading process. Arguments: file_path (str): A string indicating the path of dataset. data_fields",
"\"i\", \"am\", \"fine\"] >>> # vocab_size = 9 >>> # vocab_list = [\"<pad>\",",
"for element in dic[data_key]: vocabs.extend(field.iter_tokens(element)) return vocabs raw_vocab_list = chain_allvocab(origin_data['train'], data_fields['train']) # Important:",
"a subclass of DataField(in this case, its instance will be used, assuming its",
"at least contains: * **post_length** (:class:`numpy.ndarray`): A 1-d array, the length of post",
"form in responses. Provide both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` Examples:",
"between # different runs vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab",
"a list(tuple) of lists(tuples), which means (data_key(str), data_field(DataField)) pairs. # For example, #",
"not less than `min_vocab_times` in **training set** will be marked as valid words.",
"\"post\": numpy.array([ [2, 5, 6, 1, 3], # first post: <go> are you",
"sentence rate: %f\") % \\ (key, invalid_num / vocab_num, oov_num / vocab_num, max(sent_length),",
"raise TypeError('`data_fields` must be a dict, or a list, or a tuple.') #",
"in responses. Provide both valid and invalid vocabs. Size: ``[batch_size, max(sent_length)]`` Examples: >>>",
"to first ``max_sent_length`` tokens. max_turn_length (int): All sessions, whose turn length is longer",
"value is # a list(tuple) of lists(tuples), which means (data_key(str), data_field(DataField)) pairs. #",
"be used if a word is not valid. Size: ``[batch_size, max(sent_length)]`` * **post_allvocabs**",
"list(left_vocab) valid_vocab_len = len(vocab_list) valid_vocab_set = set(vocab_list) for key in self.key_name: if key",
"res[\"resp_length\"] = np.array(list(map(lambda i: len(self.data[key]['resp'][i]), indexes)), dtype=int) res_post = res[\"post\"] = np.zeros((batch_size, np.max(res[\"post_length\"])),",
"i: len(self.data[key]['post'][i]), indexes)), dtype=int) res[\"resp_length\"] = np.array(list(map(lambda i: len(self.data[key]['resp'][i]), indexes)), dtype=int) res_post =",
"valid words. ``unk_id`` will be used if a word is not valid. Size:",
"a label. dataset = {'key1': [session1, session2, ...], 'key2': [label1, label2, ...]} If",
"field.get_next(dataset) 0 \"\"\" score = next(dataset) return float(score.strip()) def _map_fun(self, element, convert_ids_to_tokens=None): \"\"\"",
"'key2': [label1, label2, ...]} If it's a dict, different datasets may have different",
"= {} for key in self.key_name: origin_data[key] = {data_key: [] for data_key, _",
"for x in vocab if x[1] >= min_vocab_times] vocab_list = self.ext_vocab + list(left_vocab)",
"words of id form in posts. Only provide valid words. ``unk_id`` will be",
"...]} data_fields=[['key1', 'Session'], ['key2', Label()]], means that, in the raw file, the first",
"self.key_name: if key == 'train': continue raw_vocab_list.extend(chain_allvocab(origin_data[key], data_fields[key])) vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda",
"this case, the instance of the class, whose __name__ is field, will be",
"data_fields == {'train': [['sent', Sentence()], ['label', Label()]], # 'test': [['sent', Sentence()], ['label', Label()]]}.",
"origin_data[key][data_key] for sent in field.iter_sentence(element)]) cut_word_num = np.sum(np.maximum(np.array(sent_length) - max_sent_length, 0)) session_keys =",
"a dict. dataset = {'post': [line1, line3, line5, ...], 'label': [line2, line4, line6,",
"<go> hello <eos> <pad> <pad> ]), \"post\": numpy.array([ [2, 5, 6, 1, 3],",
"Returns: (dict): A dict at least contains: * **post_length** (:class:`numpy.ndarray`): A 1-d array,",
"function implements a general loading process. Arguments: file_path (str): A string indicating the",
"[ field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length) for element in origin_data[key][data_key]] if key not in data_size:",
"post res_resp[i, :len(resp)] = resp res[\"post_allvocabs\"] = res_post.copy() res[\"resp_allvocabs\"] = res_resp.copy() res_post[res_post >=",
"labels, but the test set only contains sessions. min_vocab_times (int): A cut-off threshold",
"list length = %d\" % len(vocab_list)) word2id = {w: i for i, w",
"5, 6, 10, 3], # first post: <go> are you fine <eos> [2,",
"in self.key_name: raise ValueError(\"No set named %s.\" % key) res = {} batch_size",
"def get_fields(fields): assert isinstance(fields, list) or isinstance(fields, tuple) return [(data_key, DataField.get_field(field)) for data_key,",
"not allowed.' % token) origin_data[key][data_key].append(element) except StopIteration: break def chain_allvocab(dic, fields): vocabs =",
"0 print((\"%s set. invalid rate: %f, unknown rate: %f, max sentence length before",
"tokens appear not less than `min_vocab_times` in **training set** will be marked as",
"element, convert_ids_to_tokens=None): \"\"\" Returns the element itself. Args: element: An element of a",
"remains_capital ): super().__init__(file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital) def _load_data(self): data_fields",
"raw file, the first line is a sentence and the second line is",
"<go> hello <eos> <pad> <pad> ]), \"post_length\": numpy.array([5, 3]), # length of posts",
"== Session] if session_keys: turn_length = list( map(len, chain.from_iterable((origin_data[key][sess_key] for sess_key in session_keys))))",
"key=lambda pair: (-pair[1], pair[0])) left_vocab = [x[0] for x in vocab if x[1]",
"be a DataField instance, or a subclass of DataField(in this case, its instance",
"the class, whose __name__ is field, will be used). For example, data_fields=[['post', 'Sentence'],",
"data_fields, min_vocab_times, max_sent_length, max_turn_length, invalid_vocab_times): r'''This function implements a general loading process. Arguments:",
"and the second line is a label. They are saved in a dict.",
"= np.array(list(map(lambda i: len(self.data[key]['post'][i]), indexes)), dtype=int) res[\"resp_length\"] = np.array(list(map(lambda i: len(self.data[key]['resp'][i]), indexes)), dtype=int)",
"field in fields: for element in dic[data_key]: vocabs.extend(field.iter_tokens(element)) return vocabs raw_vocab_list = chain_allvocab(origin_data['train'],",
"as np from itertools import chain class Score(DataField): def get_next(self, dataset): r\"\"\"read text",
"element in origin_data[key][data_key]] if key not in data_size: data_size[key] = len(data[key][data_key]) elif data_size[key]",
"and the values are lists as mentioned above. For example, data_fields = {'train':",
"%f, max sentence length before cut: %d, \" + \\ \"cut word rate:",
"# \"hello\", \"i\", \"am\", \"fine\"] >>> # vocab_size = 9 >>> # vocab_list",
"A 1-d array, the length of post in each batch. Size: ``[batch_size]`` *",
"process. Arguments: file_path (str): A string indicating the path of dataset. data_fields (dict,",
"list) or isinstance(fields, tuple) return [(data_key, DataField.get_field(field)) for data_key, field in fields] if",
"3]), # length of posts \"resp_length\": numpy.array([5, 3]), # length of responses }",
"**data_size** (dict): a dict contains size of each item in data. ''' def",
"np.array(list(map(lambda i: len(self.data[key]['resp'][i]), indexes)), dtype=int) res_post = res[\"post\"] = np.zeros((batch_size, np.max(res[\"post_length\"])), dtype=int) res_resp",
"/ vocab_num, oov_num / vocab_num, max(sent_length), \\ cut_word_num / vocab_num, max_turn_length_before_cut, cut_sentence_rate)) #",
"<pad> <pad> ]), \"post\": numpy.array([ [2, 5, 6, 1, 3], # first post:",
"raw file, the first *several lines* is a session, *followed by an empty",
"[] for data_key, field in fields: for element in dic[data_key]: vocabs.extend(field.iter_tokens(element)) return vocabs",
"\\ max_sent_length, invalid_vocab_times, \\ tokenizer, remains_capital ): super().__init__(file_id, min_vocab_times, \\ max_sent_length, invalid_vocab_times, \\",
"sum(turn_length) cut_sentence_rate = np.sum(np.maximum(np.array(turn_length) - max_turn_length, 0)) / sent_num else: max_turn_length_before_cut = 1",
"dict, different datasets may have different formats.(If `data_fields` is a list or a",
"ignored both for model or metrics. Returns: (tuple): containing: * **all_vocab_list** (list): vocabulary",
"vocabs. ``unk_id`` will be used if a word is not valid. Size: ``[batch_size,",
"min_vocab_times, max_sent_length, max_turn_length, invalid_vocab_times): r'''This function implements a general loading process. Arguments: file_path",
"cut-off threshold of invalid tokens. All tokens appear not less than ``invalid_vocab_times`` in",
"**resp_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form in responses.",
"max_sent_length=max_sent_length, max_turn_length=max_turn_length) for element in origin_data[key][data_key]] if key not in data_size: data_size[key] =",
"data_key, field in data_fields[key]: element = field.convert_to_tokens(field.get_next(f_file), self.tokenize) for token in field.iter_tokens(element): if",
"**post** (:class:`numpy.ndarray`): A 2-d padded array containing words of id form in posts.",
"[x[0] for x in vocab if x[1] >= min_vocab_times] vocab_list = self.ext_vocab +",
"**resp_length** (:class:`numpy.ndarray`): A 1-d array, the length of response in each batch. Size:",
"'test': [['post', 'Sentence'], ['resp', 'Sentence']], } return self._general_load_data(self._file_path, data_fields, \\ self._min_vocab_times, self._max_sent_length, None,",
"data_fields[key])) vocab = sorted(Counter(raw_vocab_list).most_common(), \\ key=lambda pair: (-pair[1], pair[0])) left_vocab = [x[0] for",
"data_fields for key in self.key_name} else: raise TypeError('`data_fields` must be a dict, or",
"in origin_data[key][data_key] for sent in field.iter_sentence(element)]) cut_word_num = np.sum(np.maximum(np.array(sent_length) - max_sent_length, 0)) session_keys",
"valid. Size: ``[batch_size, max(sent_length)]`` * **post_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words",
"data, data_size def get_batch(self, key, indexes): '''{LanguageProcessingBase.GET_BATCH_DOC_WITHOUT_RETURNS} Returns: (dict): A dict at least",
"list(tuple) of lists(tuples), which means (data_key(str), data_field(DataField)) pairs. # For example, # data_fields",
"session_keys = [data_key for data_key, field in data_fields[key] if field.__class__ == Session] if",
"length is longer than ``max_turn_length`` will be shorten to first ``max_turn_length`` sentences. If",
"vocab if x[1] >= min_vocab_times] vocab_list = self.ext_vocab + list(left_vocab) valid_vocab_len = len(vocab_list)",
"as `self.key_name` that indicate the datasets, and the values are lists as mentioned",
"``[batch_size, max(sent_length)]`` * **resp_allvocabs** (:class:`numpy.ndarray`): A 2-d padded array containing words of id",
"= {} for key in self.key_name: data[key] = {} for data_key, field in",
"you <unk> <eos> [2, 7, 3, 0, 0], # second post: <go> hello",
"= 1 cut_sentence_rate = 0 print((\"%s set. invalid rate: %f, unknown rate: %f,",
"sent_num = sum(turn_length) cut_sentence_rate = np.sum(np.maximum(np.array(turn_length) - max_turn_length, 0)) / sent_num else: max_turn_length_before_cut",
"is a dict. Keys are the same as self.key_name('train', 'test', 'dev', etc.). Each",
"each item in data. ''' def get_fields(fields): assert isinstance(fields, list) or isinstance(fields, tuple)",
"i <unk> <unk> <eos> [2, 7, 3, 0, 0], # second response: <go>",
"vocabs, while ``vocab_list[valid_vocab_len:]`` regarded as invalid vocabs. * **data** (dict): a dict contains",
"'Label']], 'test': [['sess', 'session']]}, means that the train set contains sessions and labels,",
"(dict): A dict at least contains: * **post_length** (:class:`numpy.ndarray`): A 1-d array, the",
"i for i, w in enumerate(vocab_list)} data = {} data_size = {} for",
"print((\"%s set. invalid rate: %f, unknown rate: %f, max sentence length before cut:",
"max_turn_length (int): All sessions, whose turn length is longer than ``max_turn_length`` will be",
"data[key][data_key] = [ field.cut(element, max_sent_length=max_sent_length, max_turn_length=max_turn_length) for element in origin_data[key][data_key]] if key not",
"field in data_fields[key]: sent_length.extend( [len(sent) for element in origin_data[key][data_key] for sent in field.iter_sentence(element)])",
"turn_length = list( map(len, chain.from_iterable((origin_data[key][sess_key] for sess_key in session_keys)))) max_turn_length_before_cut = max(turn_length) sent_num",
"Score]], 'dev': [['post', 'Sentence'], ['resp', 'Sentence']], 'test': [['post', 'Sentence'], ['resp', 'Sentence']], } return",
"max_sent_length, max_turn_length, invalid_vocab_times): r'''This function implements a general loading process. Arguments: file_path (str):",
"list(or tuple) of lists(or tuples).') elif isinstance(data_fields, list) or isinstance(data_fields, tuple): data_fields =",
"]), \"post\": numpy.array([ [2, 5, 6, 1, 3], # first post: <go> are",
"% ', '.join(no_field_keys)) try: data_fields = {key: get_fields(data_fields[key]) for key in self.key_name} except",
"{} data_size = {} for key in self.key_name: data[key] = {} for data_key,",
"!= len(data[key][data_key]): raise RuntimeError( \"The data of input %s.txt contains different numbers of",
"Arguments: file_path (str): A string indicating the path of dataset. data_fields (dict, list,",
"this parameter will be ignored. invalid_vocab_times (int): A cut-off threshold of invalid tokens.",
"vocab_num, max_turn_length_before_cut, cut_sentence_rate)) # calculate hash value hash_value = DataloaderHash(ignore_tokens=(self.go_id, self.eos_id, self.pad_id), unk_id=self.unk_id).hash_datasets(data,",
"accepts no arguments), or a string(in this case, the instance of the class,"
] |
[
"hero_data = HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class TestStringManipulation(TestCase): '''Tests string manipulation''' def test_sort_hero_name_change(self): '''str:",
"manipulation''' def test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\") returns \"io\"''' dictionary = ('wisp', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary))",
"\"linken s sphere\"''' dictionary = ('sphere', None) self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self): '''str:",
"<reponame>arthurazs/dotapatch '''Tests for HeropediaData functions''' from unittest import TestCase, main as unit_main from",
"to check''' cls.DATA_DIR = HeropediaData.DATA_DIR def test_data_dir_exist(self): '''file: assert 'data' folder exists''' self.assertTrue(path.exists(self.DATA_DIR))",
"folder exists''' self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self): '''file: assert 'itemdata' file exists''' item_data = HeropediaData.ITEM_DATA",
"def test_sort_item_name_not_change(self): '''str: sort(\"linken s sphere\") returns \"linken s sphere\"''' dictionary = ('linken",
"HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self): '''str: sort(\"io\") returns \"io\"''' dictionary = ('io', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary))",
"\"io\"''' dictionary = ('io', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self): '''str: sort(\"linken s sphere\")",
"= ('io', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self): '''str: sort(\"linken s sphere\") returns \"linken",
"\"io\"''' dictionary = ('wisp', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self): '''str: sort_item(\"sphere\") returns \"linken",
"s sphere', None) self.assertEqual( 'linken s sphere', HeropediaData.sort_item(dictionary)) if __name__ == '__main__': unit_main()",
"returns \"linken s sphere\"''' dictionary = ('linken s sphere', None) self.assertEqual( 'linken s",
"self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class TestStringManipulation(TestCase): '''Tests string manipulation''' def test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\") returns \"io\"'''",
"assert 'data' folder exists''' self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self): '''file: assert 'itemdata' file exists''' item_data",
"item_data = HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def test_hero_data_exist(self): '''file: assert 'herodata' file exists''' hero_data",
"HeropediaData.DATA_DIR def test_data_dir_exist(self): '''file: assert 'data' folder exists''' self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self): '''file: assert",
"s sphere\") returns \"linken s sphere\"''' dictionary = ('linken s sphere', None) self.assertEqual(",
"for HeropediaData functions''' from unittest import TestCase, main as unit_main from dotapatch.data import",
"exists''' self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self): '''file: assert 'itemdata' file exists''' item_data = HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR,",
"sphere\") returns \"linken s sphere\"''' dictionary = ('linken s sphere', None) self.assertEqual( 'linken",
"'''file: assert 'data' folder exists''' self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self): '''file: assert 'itemdata' file exists'''",
"main as unit_main from dotapatch.data import HeropediaData import os.path as path class TestDataFiles(TestCase):",
"class TestDataFiles(TestCase): '''Test if files/folders exists''' @classmethod def setUpClass(cls): '''Sets up directory to",
"= HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class TestStringManipulation(TestCase): '''Tests string manipulation''' def test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\")",
"('io', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self): '''str: sort(\"linken s sphere\") returns \"linken s",
"s sphere\"''' dictionary = ('sphere', None) self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self): '''str: sort(\"io\")",
"s sphere\"''' dictionary = ('linken s sphere', None) self.assertEqual( 'linken s sphere', HeropediaData.sort_item(dictionary))",
"TestDataFiles(TestCase): '''Test if files/folders exists''' @classmethod def setUpClass(cls): '''Sets up directory to check'''",
"test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\") returns \"io\"''' dictionary = ('wisp', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self):",
"files/folders exists''' @classmethod def setUpClass(cls): '''Sets up directory to check''' cls.DATA_DIR = HeropediaData.DATA_DIR",
"test_data_dir_exist(self): '''file: assert 'data' folder exists''' self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self): '''file: assert 'itemdata' file",
"'''file: assert 'herodata' file exists''' hero_data = HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class TestStringManipulation(TestCase): '''Tests",
"dotapatch.data import HeropediaData import os.path as path class TestDataFiles(TestCase): '''Test if files/folders exists'''",
"test_sort_hero_name_not_change(self): '''str: sort(\"io\") returns \"io\"''' dictionary = ('io', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self):",
"os.path as path class TestDataFiles(TestCase): '''Test if files/folders exists''' @classmethod def setUpClass(cls): '''Sets",
"None) self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self): '''str: sort(\"io\") returns \"io\"''' dictionary = ('io',",
"import HeropediaData import os.path as path class TestDataFiles(TestCase): '''Test if files/folders exists''' @classmethod",
"sphere\"''' dictionary = ('sphere', None) self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self): '''str: sort(\"io\") returns",
"returns \"linken s sphere\"''' dictionary = ('sphere', None) self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self):",
"'''file: assert 'itemdata' file exists''' item_data = HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def test_hero_data_exist(self): '''file:",
"dictionary = ('wisp', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self): '''str: sort_item(\"sphere\") returns \"linken s",
"up directory to check''' cls.DATA_DIR = HeropediaData.DATA_DIR def test_data_dir_exist(self): '''file: assert 'data' folder",
"returns \"io\"''' dictionary = ('io', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self): '''str: sort(\"linken s",
"hero_data))) class TestStringManipulation(TestCase): '''Tests string manipulation''' def test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\") returns \"io\"''' dictionary",
"returns \"io\"''' dictionary = ('wisp', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self): '''str: sort_item(\"sphere\") returns",
"('wisp', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self): '''str: sort_item(\"sphere\") returns \"linken s sphere\"''' dictionary",
"dictionary = ('sphere', None) self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self): '''str: sort(\"io\") returns \"io\"'''",
"def test_data_dir_exist(self): '''file: assert 'data' folder exists''' self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self): '''file: assert 'itemdata'",
"import os.path as path class TestDataFiles(TestCase): '''Test if files/folders exists''' @classmethod def setUpClass(cls):",
"def test_sort_hero_name_not_change(self): '''str: sort(\"io\") returns \"io\"''' dictionary = ('io', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def",
"exists''' hero_data = HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class TestStringManipulation(TestCase): '''Tests string manipulation''' def test_sort_hero_name_change(self):",
"path class TestDataFiles(TestCase): '''Test if files/folders exists''' @classmethod def setUpClass(cls): '''Sets up directory",
"assert 'itemdata' file exists''' item_data = HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def test_hero_data_exist(self): '''file: assert",
"sort_hero(\"wisp\") returns \"io\"''' dictionary = ('wisp', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self): '''str: sort_item(\"sphere\")",
"as path class TestDataFiles(TestCase): '''Test if files/folders exists''' @classmethod def setUpClass(cls): '''Sets up",
"HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class TestStringManipulation(TestCase): '''Tests string manipulation''' def test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\") returns",
"directory to check''' cls.DATA_DIR = HeropediaData.DATA_DIR def test_data_dir_exist(self): '''file: assert 'data' folder exists'''",
"def test_item_data_exist(self): '''file: assert 'itemdata' file exists''' item_data = HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def",
"\"linken s sphere\"''' dictionary = ('linken s sphere', None) self.assertEqual( 'linken s sphere',",
"sort(\"linken s sphere\") returns \"linken s sphere\"''' dictionary = ('linken s sphere', None)",
"string manipulation''' def test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\") returns \"io\"''' dictionary = ('wisp', None) self.assertEqual('io',",
"HeropediaData import os.path as path class TestDataFiles(TestCase): '''Test if files/folders exists''' @classmethod def",
"self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self): '''str: sort(\"io\") returns \"io\"''' dictionary = ('io', None)",
"('linken s sphere', None) self.assertEqual( 'linken s sphere', HeropediaData.sort_item(dictionary)) if __name__ == '__main__':",
"None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self): '''str: sort_item(\"sphere\") returns \"linken s sphere\"''' dictionary =",
"None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self): '''str: sort(\"linken s sphere\") returns \"linken s sphere\"'''",
"TestStringManipulation(TestCase): '''Tests string manipulation''' def test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\") returns \"io\"''' dictionary = ('wisp',",
"as unit_main from dotapatch.data import HeropediaData import os.path as path class TestDataFiles(TestCase): '''Test",
"self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self): '''file: assert 'itemdata' file exists''' item_data = HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data)))",
"test_item_data_exist(self): '''file: assert 'itemdata' file exists''' item_data = HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def test_hero_data_exist(self):",
"self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def test_hero_data_exist(self): '''file: assert 'herodata' file exists''' hero_data = HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR,",
"'''str: sort(\"io\") returns \"io\"''' dictionary = ('io', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self): '''str:",
"HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def test_hero_data_exist(self): '''file: assert 'herodata' file exists''' hero_data = HeropediaData.HERO_DATA",
"functions''' from unittest import TestCase, main as unit_main from dotapatch.data import HeropediaData import",
"assert 'herodata' file exists''' hero_data = HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class TestStringManipulation(TestCase): '''Tests string",
"item_data))) def test_hero_data_exist(self): '''file: assert 'herodata' file exists''' hero_data = HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data)))",
"'''Test if files/folders exists''' @classmethod def setUpClass(cls): '''Sets up directory to check''' cls.DATA_DIR",
"test_sort_item_name_change(self): '''str: sort_item(\"sphere\") returns \"linken s sphere\"''' dictionary = ('sphere', None) self.assertEqual( \"linken's_sphere\",",
"check''' cls.DATA_DIR = HeropediaData.DATA_DIR def test_data_dir_exist(self): '''file: assert 'data' folder exists''' self.assertTrue(path.exists(self.DATA_DIR)) def",
"= ('sphere', None) self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self): '''str: sort(\"io\") returns \"io\"''' dictionary",
"dictionary = ('io', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self): '''str: sort(\"linken s sphere\") returns",
"sphere\"''' dictionary = ('linken s sphere', None) self.assertEqual( 'linken s sphere', HeropediaData.sort_item(dictionary)) if",
"HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self): '''str: sort(\"linken s sphere\") returns \"linken s sphere\"''' dictionary =",
"= HeropediaData.DATA_DIR def test_data_dir_exist(self): '''file: assert 'data' folder exists''' self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self): '''file:",
"test_sort_item_name_not_change(self): '''str: sort(\"linken s sphere\") returns \"linken s sphere\"''' dictionary = ('linken s",
"self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self): '''str: sort(\"linken s sphere\") returns \"linken s sphere\"''' dictionary",
"'''Tests for HeropediaData functions''' from unittest import TestCase, main as unit_main from dotapatch.data",
"'''str: sort_hero(\"wisp\") returns \"io\"''' dictionary = ('wisp', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self): '''str:",
"import TestCase, main as unit_main from dotapatch.data import HeropediaData import os.path as path",
"def test_hero_data_exist(self): '''file: assert 'herodata' file exists''' hero_data = HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class",
"'''str: sort(\"linken s sphere\") returns \"linken s sphere\"''' dictionary = ('linken s sphere',",
"from dotapatch.data import HeropediaData import os.path as path class TestDataFiles(TestCase): '''Test if files/folders",
"if files/folders exists''' @classmethod def setUpClass(cls): '''Sets up directory to check''' cls.DATA_DIR =",
"file exists''' item_data = HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def test_hero_data_exist(self): '''file: assert 'herodata' file",
"HeropediaData functions''' from unittest import TestCase, main as unit_main from dotapatch.data import HeropediaData",
"'''Sets up directory to check''' cls.DATA_DIR = HeropediaData.DATA_DIR def test_data_dir_exist(self): '''file: assert 'data'",
"class TestStringManipulation(TestCase): '''Tests string manipulation''' def test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\") returns \"io\"''' dictionary =",
"'data' folder exists''' self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self): '''file: assert 'itemdata' file exists''' item_data =",
"def setUpClass(cls): '''Sets up directory to check''' cls.DATA_DIR = HeropediaData.DATA_DIR def test_data_dir_exist(self): '''file:",
"= ('wisp', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self): '''str: sort_item(\"sphere\") returns \"linken s sphere\"'''",
"setUpClass(cls): '''Sets up directory to check''' cls.DATA_DIR = HeropediaData.DATA_DIR def test_data_dir_exist(self): '''file: assert",
"unittest import TestCase, main as unit_main from dotapatch.data import HeropediaData import os.path as",
"file exists''' hero_data = HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class TestStringManipulation(TestCase): '''Tests string manipulation''' def",
"'''str: sort_item(\"sphere\") returns \"linken s sphere\"''' dictionary = ('sphere', None) self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary))",
"@classmethod def setUpClass(cls): '''Sets up directory to check''' cls.DATA_DIR = HeropediaData.DATA_DIR def test_data_dir_exist(self):",
"exists''' item_data = HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def test_hero_data_exist(self): '''file: assert 'herodata' file exists'''",
"'''Tests string manipulation''' def test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\") returns \"io\"''' dictionary = ('wisp', None)",
"dictionary = ('linken s sphere', None) self.assertEqual( 'linken s sphere', HeropediaData.sort_item(dictionary)) if __name__",
"TestCase, main as unit_main from dotapatch.data import HeropediaData import os.path as path class",
"def test_sort_hero_name_change(self): '''str: sort_hero(\"wisp\") returns \"io\"''' dictionary = ('wisp', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def",
"cls.DATA_DIR = HeropediaData.DATA_DIR def test_data_dir_exist(self): '''file: assert 'data' folder exists''' self.assertTrue(path.exists(self.DATA_DIR)) def test_item_data_exist(self):",
"= HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def test_hero_data_exist(self): '''file: assert 'herodata' file exists''' hero_data =",
"\"linken's_sphere\", HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self): '''str: sort(\"io\") returns \"io\"''' dictionary = ('io', None) self.assertEqual('io',",
"sort(\"io\") returns \"io\"''' dictionary = ('io', None) self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_not_change(self): '''str: sort(\"linken",
"self.assertEqual('io', HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self): '''str: sort_item(\"sphere\") returns \"linken s sphere\"''' dictionary = ('sphere',",
"'herodata' file exists''' hero_data = HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class TestStringManipulation(TestCase): '''Tests string manipulation'''",
"('sphere', None) self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary)) def test_sort_hero_name_not_change(self): '''str: sort(\"io\") returns \"io\"''' dictionary =",
"unit_main from dotapatch.data import HeropediaData import os.path as path class TestDataFiles(TestCase): '''Test if",
"test_hero_data_exist(self): '''file: assert 'herodata' file exists''' hero_data = HeropediaData.HERO_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, hero_data))) class TestStringManipulation(TestCase):",
"= ('linken s sphere', None) self.assertEqual( 'linken s sphere', HeropediaData.sort_item(dictionary)) if __name__ ==",
"def test_sort_item_name_change(self): '''str: sort_item(\"sphere\") returns \"linken s sphere\"''' dictionary = ('sphere', None) self.assertEqual(",
"'itemdata' file exists''' item_data = HeropediaData.ITEM_DATA self.assertTrue(path.isfile(path.join(self.DATA_DIR, item_data))) def test_hero_data_exist(self): '''file: assert 'herodata'",
"exists''' @classmethod def setUpClass(cls): '''Sets up directory to check''' cls.DATA_DIR = HeropediaData.DATA_DIR def",
"HeropediaData.sort_hero(dictionary)) def test_sort_item_name_change(self): '''str: sort_item(\"sphere\") returns \"linken s sphere\"''' dictionary = ('sphere', None)",
"sort_item(\"sphere\") returns \"linken s sphere\"''' dictionary = ('sphere', None) self.assertEqual( \"linken's_sphere\", HeropediaData.sort_item(dictionary)) def",
"from unittest import TestCase, main as unit_main from dotapatch.data import HeropediaData import os.path"
] |