hexsha stringlengths 40 40 | size int64 3 1.03M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 972 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 972 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 116k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 972 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 3 1.03M | avg_line_length float64 1.13 941k | max_line_length int64 2 941k | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7c74c0dc505ba1b7931433012246c35690d6cd20 | 184 | py | Python | aws-s3-django-postgresql-rest/app/core/serializers.py | MdSauravChowdhury/cheat-project | 8602d1479e0b2adad48265404e4509ab6a45b8e3 | [
"MIT"
] | null | null | null | aws-s3-django-postgresql-rest/app/core/serializers.py | MdSauravChowdhury/cheat-project | 8602d1479e0b2adad48265404e4509ab6a45b8e3 | [
"MIT"
] | null | null | null | aws-s3-django-postgresql-rest/app/core/serializers.py | MdSauravChowdhury/cheat-project | 8602d1479e0b2adad48265404e4509ab6a45b8e3 | [
"MIT"
] | null | null | null | from rest_framework import serializers
from .models import S3Box
class S3BoxSerializer(serializers.ModelSerializer):
class Meta:
model = S3Box
fields = '__all__' | 23 | 51 | 0.728261 |
1325e70bb906f9a092ce51f47b6b3f02f3c23dc9 | 5,650 | py | Python | tests/cli/test_add.py | elmirjagudin/symstore | c84f7481f2a10a40011b630a06ea1265c7168b83 | [
"MIT"
] | 26 | 2015-11-18T17:45:35.000Z | 2021-03-15T07:38:08.000Z | tests/cli/test_add.py | elmirjagudin/symstore | c84f7481f2a10a40011b630a06ea1265c7168b83 | [
"MIT"
] | 17 | 2016-08-20T07:17:21.000Z | 2021-06-03T06:59:14.000Z | tests/cli/test_add.py | elmirjagudin/symstore | c84f7481f2a10a40011b630a06ea1265c7168b83 | [
"MIT"
] | 14 | 2015-10-02T23:04:46.000Z | 2021-05-28T23:34:26.000Z | import unittest
import tempfile
import shutil
from os import path
from symstore import cab
from tests.cli import util
class TestNewStore(util.CliTester):
"""
Test publishing files to a new symstore.
"""
def setUp(self):
self.recordStartTime()
# set test's symstore path to a non-existing directory,
# so that we can test code path that creates new symstore directory
tmp_path = tempfile.mkdtemp()
self.symstore_path = path.join(tmp_path, "empty")
def tearDown(self):
# make sure we remove created temp directory
shutil.rmtree(path.dirname(self.symstore_path))
def test_add_pdb(self):
self.run_add_command(["--product-name", "dummyprod"],
["bigage.pdb", "dummyprog.pdb"])
self.assertSymstoreDir("new_store.zip")
@unittest.skipIf(cab.compress is None, util.NO_COMP_SKIP)
def test_add_compressed_pdb(self):
self.run_add_command(["--compress", "--product-name", "dummyprod"],
["dummyprog.pdb"])
self.assertSymstoreDir("new_store_compressed.zip")
class TestAlternativeExtensions(util.CliTester):
"""
Test the case when files have non-standard extensions.
For example, some common file extensions can be:
scr : Screensaver (PE/EXE file format)
sys : Driver (PE/DLL file format)
for more details: https://github.com/symstore/symstore/issues/20
"""
RENAMED_FILES = [
("dummyprog.exe", "dummyprog.src"),
("dummylib.dll", "dummylib.sys"),
("dummyprog.pdb", "dummyprog.hej")
]
def setUp(self):
self.recordStartTime()
# create new, initially empty, symbols store
tmp_path = tempfile.mkdtemp()
self.symstore_path = path.join(tmp_path, "renamed")
# create some files with alternative extensions,
# by copying existing test files to a temp directory
# with new names
self.renamed_files_dir = tempfile.mkdtemp()
for src, dest in self.RENAMED_FILES:
shutil.copyfile(util.symfile_path(src),
path.join(self.renamed_files_dir, dest))
def tearDown(self):
# make sure we remove created temp directories
shutil.rmtree(path.dirname(self.symstore_path))
shutil.rmtree(self.renamed_files_dir)
def test_publish(self):
files = [f for _, f in self.RENAMED_FILES]
retcode, stderr = util.run_script(self.symstore_path, files,
symfiles_dir=self.renamed_files_dir)
self.assertEqual(retcode, 0)
self.assertEqual(stderr, b"")
self.assertSymstoreDir("renamed.zip")
class TestExistingStore(util.CliTester):
initial_dir_zip = "new_store.zip"
def test_add_pdb(self):
self.run_add_command(["--product-name", "dummylib"],
["dummylib.pdb"])
self.assertSymstoreDir("existing_store.zip")
def test_republish(self):
self.run_add_command(["--product-name", "dummyprod"],
["dummyprog.pdb"])
self.assertSymstoreDir("republished.zip")
def test_special_pdb(self):
# test adding two pdbs with following properties:
#
# mono.pdb - root stream spans multiple pages
# vc140.pdb - no DBI stream
self.run_add_command(["--product-name", "specpdbs"],
["mono.pdb", "vc140.pdb"])
self.assertSymstoreDir("special_pdbs.zip")
def test_longroot(self):
# test adding a pdb file with long root stream,
# a root stream which need more then one page
# to store it's indexes
self.run_add_command(["--product-name", "longroot"],
["longroot.pdb"])
self.assertSymstoreDir("longroot_store.zip")
class TestSkipPublished(util.CliTester):
"""
test adding new transaction with '--skip-published' flag enabled
"""
initial_dir_zip = "new_store.zip"
def test_skip(self):
"""
test adding two files, where:
dummyprog.pdb - is already published
dummylib.dll - have not been published yet
"""
self.run_add_command(
["--skip-published", "--product-name", "dummylib"],
["dummylib.dll", "dummyprog.pdb"])
self.assertSymstoreDir("skip_republish.zip")
def test_skip_no_new_files(self):
"""
test adding one file that already have been published
"""
retcode, stderr = util.run_script(self.symstore_path,
["dummyprog.pdb"],
["--skip-published"])
# we should get an error message, as there is nothing new to publish
self.assertEqual(retcode, 1)
self.assertEqual(stderr.decode(), "no new files to publish\n")
class TestRepublishCompressed(util.CliTester):
initial_dir_zip = "new_store_compressed.zip"
@unittest.skipIf(cab.compress is None, util.NO_COMP_SKIP)
def test_republish(self):
self.run_add_command(["--compress", "--product-name", "dummyprod"],
["dummyprog.pdb"])
self.assertSymstoreDir("republished_compressed.zip")
class TestPublishPE(util.CliTester):
initial_dir_zip = "existing_store.zip"
def test_add_pdb(self):
self.run_add_command(["--product-name", "peprods",
"--product-version", "1.0.1"],
["dummylib.dll", "dummyprog.exe"])
self.assertSymstoreDir("pe_store.zip")
| 33.040936 | 78 | 0.610619 |
2cf9a9948b3d07129060072e7d1868c5d4286f84 | 5,702 | py | Python | tests/test_comp_ops.py | Ben-Wu/ShrugProgrammingLanguage | 1aa95acfe02ebfac147bd23c4a028a4b7b78645c | [
"MIT"
] | 2 | 2018-09-25T06:57:55.000Z | 2019-06-07T19:07:46.000Z | tests/test_comp_ops.py | Ben-Wu/ShrugProgrammingLanguage | 1aa95acfe02ebfac147bd23c4a028a4b7b78645c | [
"MIT"
] | 4 | 2018-09-21T22:03:55.000Z | 2019-06-07T19:07:05.000Z | tests/test_comp_ops.py | Ben-Wu/ShrugProgrammingLanguage | 1aa95acfe02ebfac147bd23c4a028a4b7b78645c | [
"MIT"
] | null | null | null | import unittest
from shrug_lang.operators import CompOp
from .utils import BaseTokenParserTestCase, TokenGenerator
class TestCompOperations(unittest.TestCase):
def test_equality(self):
self.assertTrue(CompOp.eq(('',), ('',)))
self.assertTrue(CompOp.eq(('abc',), ('abc',)))
self.assertTrue(CompOp.eq((1,), (1,)))
self.assertTrue(CompOp.eq((True,), (True,)))
self.assertTrue(CompOp.eq((True,), (1,)))
self.assertFalse(CompOp.eq(('',), ('a',)))
self.assertFalse(CompOp.eq((2,), (1,)))
self.assertFalse(CompOp.eq((False,), (True,)))
self.assertFalse(CompOp.eq((True,), (2,)))
def test_inequality(self):
self.assertFalse(CompOp.neq(('',), ('',)))
self.assertFalse(CompOp.neq(('abc',), ('abc',)))
self.assertFalse(CompOp.neq((1,), (1,)))
self.assertFalse(CompOp.neq((True,), (True,)))
self.assertFalse(CompOp.neq((True,), (1,)))
self.assertTrue(CompOp.neq(('',), ('a',)))
self.assertTrue(CompOp.neq((2,), (1,)))
self.assertTrue(CompOp.neq((False,), (True,)))
self.assertTrue(CompOp.neq((True,), (2,)))
def test_gt(self):
self.assertTrue(CompOp.gt(('b',), ('a',)))
self.assertTrue(CompOp.gt((2,), (1,)))
self.assertRaises(TypeError, CompOp.gt, 'a', 1)
self.assertRaises(TypeError, CompOp.gt, 1, '')
self.assertFalse(CompOp.gt(('a',), ('a',)))
self.assertFalse(CompOp.gt((1,), (1,)))
self.assertFalse(CompOp.gt(('a',), ('b',)))
self.assertFalse(CompOp.gt((1,), (2,)))
def test_gte(self):
self.assertTrue(CompOp.gte(('b',), ('a',)))
self.assertTrue(CompOp.gte((2,), (1,)))
self.assertRaises(TypeError, CompOp.gte, 'a', 1)
self.assertRaises(TypeError, CompOp.gte, 1, '')
self.assertTrue(CompOp.gte(('a',), ('a',)))
self.assertTrue(CompOp.gte((1,), (1,)))
self.assertFalse(CompOp.gte(('a',), ('b',)))
self.assertFalse(CompOp.gte((1,), (2,)))
def test_lt(self):
self.assertFalse(CompOp.lt(('b',), ('a',)))
self.assertFalse(CompOp.lt((2,), (1,)))
self.assertRaises(TypeError, CompOp.lt, 'a', 1)
self.assertRaises(TypeError, CompOp.lt, 1, '')
self.assertFalse(CompOp.lt(('a',), ('a',)))
self.assertFalse(CompOp.lt((1,), (1,)))
self.assertTrue(CompOp.lt(('a',), ('b',)))
self.assertTrue(CompOp.lt((1,), (2,)))
def test_lte(self):
self.assertFalse(CompOp.lte(('b',), ('a',)))
self.assertFalse(CompOp.lte((2,), (1,)))
self.assertRaises(TypeError, CompOp.lte, 'a', 1)
self.assertRaises(TypeError, CompOp.lte, 1, '')
self.assertTrue(CompOp.lte(('a',), ('a',)))
self.assertTrue(CompOp.lte((1,), (1,)))
self.assertTrue(CompOp.lte(('a',), ('b',)))
self.assertTrue(CompOp.lte((1,), (2,)))
class TestCompParser(BaseTokenParserTestCase):
def test_var_var_eq(self):
tokens = [TokenGenerator.get_id('a'), TokenGenerator.get_number(5),
TokenGenerator.get_eol(),
TokenGenerator.get_id('b'), TokenGenerator.get_number(5),
TokenGenerator.get_eol(),
TokenGenerator.get_shrug(), TokenGenerator.get_shrug(),
TokenGenerator.get_id('a'), TokenGenerator.get_id('b'),
TokenGenerator.get_eol()]
expected = [True]
self.assertEqual(expected, self.process_tokens(tokens))
def test_int_int_neq(self):
tokens = [TokenGenerator.get_shrug(), TokenGenerator.get_shrug(),
TokenGenerator.get_number(4), TokenGenerator.get_shrug(),
TokenGenerator.get_number(4), TokenGenerator.get_eol()]
expected = [False]
self.assertEqual(expected, self.process_tokens(tokens))
def test_int_int_gt(self):
tokens = [TokenGenerator.get_shrug(), TokenGenerator.get_shrug(),
TokenGenerator.get_number(4), TokenGenerator.get_shrug(),
TokenGenerator.get_shrug(), TokenGenerator.get_number(2),
TokenGenerator.get_eol()]
expected = [True]
self.assertEqual(expected, self.process_tokens(tokens))
def test_int_int_gte(self):
tokens = [TokenGenerator.get_shrug(), TokenGenerator.get_shrug(),
TokenGenerator.get_number(3), TokenGenerator.get_shrug(),
TokenGenerator.get_shrug(), TokenGenerator.get_shrug(),
TokenGenerator.get_number(4), TokenGenerator.get_eol()]
expected = [False]
self.assertEqual(expected, self.process_tokens(tokens))
def test_str_str_lt(self):
tokens = [TokenGenerator.get_shrug(), TokenGenerator.get_shrug(),
TokenGenerator.get_number('abc'), TokenGenerator.get_shrug(),
TokenGenerator.get_shrug(), TokenGenerator.get_shrug(),
TokenGenerator.get_shrug(), TokenGenerator.get_number('abd'),
TokenGenerator.get_eol()]
expected = [True]
self.assertEqual(expected, self.process_tokens(tokens))
def test_str_str_lte(self):
tokens = [TokenGenerator.get_shrug(), TokenGenerator.get_shrug(),
TokenGenerator.get_number('abc'), TokenGenerator.get_shrug(),
TokenGenerator.get_shrug(), TokenGenerator.get_shrug(),
TokenGenerator.get_shrug(), TokenGenerator.get_shrug(),
TokenGenerator.get_number('abc'), TokenGenerator.get_eol()]
expected = [True]
self.assertEqual(expected, self.process_tokens(tokens))
if __name__ == '__main__':
unittest.main()
| 40.439716 | 79 | 0.594528 |
3144306ef4ad85deb15e86b9824832896c2b0939 | 5,172 | py | Python | Groups/Group_ID_35/MULDA/mulda.py | aryapushpa/DataScience | 89ba01c18d3ed36942ffdf3e1f3c68fd08b05324 | [
"MIT"
] | 5 | 2020-12-13T07:53:22.000Z | 2020-12-20T18:49:27.000Z | Groups/Group_ID_35/MULDA/mulda.py | Gulnaz-Tabassum/DataScience | 1fd771f873a9bc0800458fd7c05e228bb6c4e8a0 | [
"MIT"
] | null | null | null | Groups/Group_ID_35/MULDA/mulda.py | Gulnaz-Tabassum/DataScience | 1fd771f873a9bc0800458fd7c05e228bb6c4e8a0 | [
"MIT"
] | 24 | 2020-12-12T11:23:28.000Z | 2021-10-04T13:09:38.000Z | # For Understanding the functionality perfomed by each function refer to .ipynb file it has everything explained in detail
# Authors
# Kanishk Gupta(0801CS171031)
# Aadeesh Jain (0801CS171001)
# Harsh Pastaria(0801CS171027
import numpy as np
import pandas as pd
import math
import os
class MULDA:
def selfCovarianceX(self,X,n):
Cxx=np.dot(X,X.T)
Cxx=Cxx/n
return Cxx
def selfCovarianceY(self,Y,n):
Cyy=np.dot(Y,Y.T)
Cyy=Cyy/n
return Cyy
def covarianceAcrossXY(self,X,Y,n):
Cxy=np.dot(X,Y.T)
Cxy=Cxy/n
return Cxy
def diagMatrixW(self,row,col,n):
row,col=(n,n)
W=[]
for i in range(col):
c=[]
for j in range(row):
if i==j:
c.append(1/n)
else:
c.append(0)
W.append(c)
return W
def identityMatrixI(self,row,col):
I=[]
for i in range(col):
c1=[]
for j in range(row):
if i==j:
c1.append(1)
else:
c1.append(0)
I.append(c1)
return I
def betweennclassScattermatrixX(self,X,row,col,n):
W=self.diagMatrixW(row,col,n)
t=np.dot(X,W)
Sbx=np.dot(t,X.T)
Sbx=Sbx/n
return Sbx
def totalScattermatrixX(self,X,n):
Stx=np.dot(X,X.T)
Stx=Stx/n
return Stx
def betweennclassScattermatrixY(self,Y,row,col,n):
W=self.diagMatrixW(row,col,n)
t=np.dot(Y,W)
Sby=np.dot(t,Y.T)
Sby=Sby/n
return Sby
def totalScattermatrixY(self,Y,n):
Sty=np.dot(Y,Y.T)
Sty=Sty/n
return Sty
def calculatingSigma(self,X,Y,n):
Stx = self.totalScattermatrixX(X,n)
Sty = self.totalScattermatrixY(Y,n)
sigma1= Stx.trace()
sigma2= Sty.trace()
sigma= sigma1/sigma2
return sigma
def fit(self,X,Y,n,row,col):
Stx = self.totalScattermatrixX(X,n)
Sty = self.totalScattermatrixY(Y,n)
Sbx = self.betweennclassScattermatrixX(X,row,col,n)
Cxy = self.covarianceAcrossXY(X,Y,n)
Sby = self.betweennclassScattermatrixY(Y,row,col,n)
Cxx = self.selfCovarianceX(X,n)
Cyy = self.selfCovarianceY(Y,n)
sigma = self.calculatingSigma(X,Y,n)
I = self.identityMatrixI(row,col)
d = Stx.shape[0]
Dx = [ [ 0 for i in range(row) ] for j in range(col) ]
Dy = [ [ 0 for i in range(row) ] for j in range(col) ]
for u in range(0,d):
#calculating Px
p=np.dot(Stx,np.transpose(Dx))
p1=np.dot((np.dot(Dx,Stx)),np.transpose(Dx))
p1_inv=np.linalg.pinv(p1)
Px=np.dot((np.dot(p,p1_inv)),Dx)
Px = I - Px
#Calculating Py
P=np.dot(Sty,np.transpose(Dy))
P1=np.dot((np.dot(Dy,Sty)),np.transpose(Dy))
P1_inv=np.linalg.pinv(P1)
Py=np.dot((np.dot(P,P1_inv)),Dy)
Py= I-Py
#Wx and Wy
A = Sty*Px*Sbx
A = sigma*A
B = Sty*Px*Cxy
B = sigma*B
C = Stx*Py*Cxy
D = Stx*Py*Sby
Inv_a=np.linalg.pinv(A)
Inv_d=np.linalg.pinv(D)
F1=np.dot(Inv_a,B)
F2=np.dot(F1,Inv_d)
F=np.dot(F2,C)
F[F<0]=0
F_Final=np.sqrt(F)
U,D,V=np.linalg.svd(F_Final)
V=V.T
Cxxi=np.linalg.inv(Cxx)
Cxxi[Cxxi<0]=0
Cxx_sqrt=np.sqrt(Cxxi)
wx=np.dot(Cxx_sqrt,U)
Cyyi=np.linalg.pinv(Cyy)
Cyyi[Cyyi<0]=0
Cyy_sqrt=np.sqrt(Cyyi)
wy=np.dot(Cyy_sqrt,V)
#rth vector pair
wValues, vVectors = np.linalg.eig(wx)
index = np.argmax(wValues, axis=0)
l = [0]*row
for i in range (0,row):
l[i] = wx[i][index]
for i in range(len(l)):
Dx[i][u]=l[i]
wValuesY, vVectorsY = np.linalg.eig(wy)
indexY = np.argmax(wValuesY, axis=0)
l1 = [0]*row
for i in range (0,row):
l1[i] = wy[i][indexY]
for i in range(len(l1)):
Dy[i][u]=l1[i]
d_net = [Dx,Dy]
return d_net
def combined_Features(self,X,Y,n,r,c):
d_net = self.fit(X,Y,n,r,c)
Dx = d_net[0]
Dy = d_net[1]
temp = np.array(Dx)
temp.reshape(r,c)
Wx = temp
temp1 = np.array(Dy)
temp1.reshape(r,c)
Wy = temp1
Wy.shape
Res1 = Wy.dot(X)
Res2 = Wx.dot(Y)
Z= [[0]*1]*2
Z[0] = Res1
Z[1] = Res2
return Z
| 27.078534 | 124 | 0.458237 |
83d2cf77e824b6336c4945f0c92e4362be1722f7 | 8,646 | py | Python | fastai/text.py | royalbhati/fastai | 745ddabcf9301b0078a16ac6333cd41684df149b | [
"Apache-2.0"
] | 7 | 2018-10-23T23:43:15.000Z | 2021-12-25T01:08:09.000Z | fastai/text.py | royalbhati/fastai | 745ddabcf9301b0078a16ac6333cd41684df149b | [
"Apache-2.0"
] | 8 | 2021-03-18T20:46:24.000Z | 2022-03-11T23:26:30.000Z | fastai/text.py | royalbhati/fastai | 745ddabcf9301b0078a16ac6333cd41684df149b | [
"Apache-2.0"
] | 11 | 2019-01-19T08:10:46.000Z | 2021-10-02T06:45:42.000Z | from .core import *
from .learner import *
from .lm_rnn import *
from torch.utils.data.sampler import Sampler
import spacy
from spacy.symbols import ORTH
re_tok = re.compile(f'([{string.punctuation}“”¨«»®´·º½¾¿¡§£₤‘’])')
def tokenize(s): return re_tok.sub(r' \1 ', s).split()
def texts_labels_from_folders(path, folders):
texts,labels = [],[]
for idx,label in enumerate(folders):
for fname in glob(os.path.join(path, label, '*.*')):
texts.append(open(fname, 'r').read())
labels.append(idx)
return texts, np.array(labels).astype(np.int64)
def numericalize_tok(tokens, max_vocab=50000, min_freq=0, unk_tok="_unk_", pad_tok="_pad_", bos_tok="_bos_", eos_tok="_eos_"):
"""Takes in text tokens and returns int2tok and tok2int converters
Arguments:
tokens(list): List of tokens. Can be a list of strings, or a list of lists of strings.
max_vocab(int): Number of tokens to return in the vocab (sorted by frequency)
min_freq(int): Minimum number of instances a token must be present in order to be preserved.
unk_tok(str): Token to use when unknown tokens are encountered in the source text.
pad_tok(str): Token to use when padding sequences.
"""
if isinstance(tokens, str):
raise ValueError("Expected to receive a list of tokens. Received a string instead")
if isinstance(tokens[0], list):
tokens = [p for o in tokens for p in o]
freq = Counter(tokens)
int2tok = [o for o,c in freq.most_common(max_vocab) if c>min_freq]
unk_id = 3
int2tok.insert(0, bos_tok)
int2tok.insert(1, pad_tok)
int2tok.insert(2, eos_tok)
int2tok.insert(unk_id, unk_tok)
tok2int = collections.defaultdict(lambda:unk_id, {v:k for k,v in enumerate(int2tok)})
return int2tok, tok2int
class Tokenizer():
def __init__(self, lang='en'):
self.re_br = re.compile(r'<\s*br\s*/?>', re.IGNORECASE)
self.tok = spacy.load(lang)
for w in ('<eos>','<bos>','<unk>'):
self.tok.tokenizer.add_special_case(w, [{ORTH: w}])
def sub_br(self,x): return self.re_br.sub("\n", x)
def spacy_tok(self,x):
return [t.text for t in self.tok.tokenizer(self.sub_br(x))]
re_rep = re.compile(r'(\S)(\1{3,})')
re_word_rep = re.compile(r'(\b\w+\W+)(\1{3,})')
@staticmethod
def replace_rep(m):
TK_REP = 'tk_rep'
c,cc = m.groups()
return f' {TK_REP} {len(cc)+1} {c} '
@staticmethod
def replace_wrep(m):
TK_WREP = 'tk_wrep'
c,cc = m.groups()
return f' {TK_WREP} {len(cc.split())+1} {c} '
@staticmethod
def do_caps(ss):
TOK_UP,TOK_SENT,TOK_MIX = ' t_up ',' t_st ',' t_mx '
res = []
prev='.'
re_word = re.compile('\w')
re_nonsp = re.compile('\S')
for s in re.findall(r'\w+|\W+', ss):
res += ([TOK_UP,s.lower()] if (s.isupper() and (len(s)>2))
# else [TOK_SENT,s.lower()] if (s.istitle() and re_word.search(prev))
else [s.lower()])
# if re_nonsp.search(s): prev = s
return ''.join(res)
def proc_text(self, s):
s = self.re_rep.sub(Tokenizer.replace_rep, s)
s = self.re_word_rep.sub(Tokenizer.replace_wrep, s)
s = Tokenizer.do_caps(s)
s = re.sub(r'([/#])', r' \1 ', s)
s = re.sub(' {2,}', ' ', s)
return self.spacy_tok(s)
@staticmethod
def proc_all(ss, lang):
tok = Tokenizer(lang)
return [tok.proc_text(s) for s in ss]
@staticmethod
def proc_all_mp(ss, lang='en', ncpus = None):
ncpus = ncpus or num_cpus()//2
with ProcessPoolExecutor(ncpus) as e:
return sum(e.map(Tokenizer.proc_all, ss, [lang]*len(ss)), [])
class TextDataset(Dataset):
def __init__(self, x, y, backwards=False, sos=None, eos=None):
self.x,self.y,self.backwards,self.sos,self.eos = x,y,backwards,sos,eos
def __getitem__(self, idx):
x = self.x[idx]
if self.backwards: x = list(reversed(x))
if self.eos is not None: x = x + [self.eos]
if self.sos is not None: x = [self.sos]+x
return np.array(x),self.y[idx]
def __len__(self): return len(self.x)
class SortSampler(Sampler):
def __init__(self, data_source, key): self.data_source,self.key = data_source,key
def __len__(self): return len(self.data_source)
def __iter__(self):
return iter(sorted(range(len(self.data_source)), key=self.key, reverse=True))
class SortishSampler(Sampler):
"""Returns an iterator that traverses the the data in randomly ordered batches that are approximately the same size.
The max key size batch is always returned in the first call because of pytorch cuda memory allocation sequencing.
Without that max key returned first multiple buffers may be allocated when the first created isn't large enough
to hold the next in the sequence.
"""
def __init__(self, data_source, key, bs):
self.data_source,self.key,self.bs = data_source,key,bs
def __len__(self): return len(self.data_source)
def __iter__(self):
idxs = np.random.permutation(len(self.data_source))
sz = self.bs*50
ck_idx = [idxs[i:i+sz] for i in range(0, len(idxs), sz)]
sort_idx = np.concatenate([sorted(s, key=self.key, reverse=True) for s in ck_idx])
sz = self.bs
ck_idx = [sort_idx[i:i+sz] for i in range(0, len(sort_idx), sz)]
max_ck = np.argmax([self.key(ck[0]) for ck in ck_idx]) # find the chunk with the largest key,
ck_idx[0],ck_idx[max_ck] = ck_idx[max_ck],ck_idx[0] # then make sure it goes first.
sort_idx = np.concatenate(np.random.permutation(ck_idx[1:]))
sort_idx = np.concatenate((ck_idx[0], sort_idx))
return iter(sort_idx)
class LanguageModelLoader():
""" Returns a language model iterator that iterates through batches that are of length N(bptt,5)
The first batch returned is always bptt+25; the max possible width. This is done because of they way that pytorch
allocates cuda memory in order to prevent multiple buffers from being created as the batch width grows.
"""
def __init__(self, nums, bs, bptt, backwards=False):
self.bs,self.bptt,self.backwards = bs,bptt,backwards
self.data = self.batchify(nums)
self.i,self.iter = 0,0
self.n = len(self.data)
def __iter__(self):
self.i,self.iter = 0,0
while self.i < self.n-1 and self.iter<len(self):
if self.i == 0:
seq_len = self.bptt + 5 * 5
else:
bptt = self.bptt if np.random.random() < 0.95 else self.bptt / 2.
seq_len = max(5, int(np.random.normal(bptt, 5)))
res = self.get_batch(self.i, seq_len)
self.i += seq_len
self.iter += 1
yield res
def __len__(self): return self.n // self.bptt - 1
def batchify(self, data):
nb = data.shape[0] // self.bs
data = np.array(data[:nb*self.bs])
data = data.reshape(self.bs, -1).T
if self.backwards: data=data[::-1]
return T(data)
def get_batch(self, i, seq_len):
source = self.data
seq_len = min(seq_len, len(source) - 1 - i)
return source[i:i+seq_len], source[i+1:i+1+seq_len].view(-1)
class LanguageModel(BasicModel):
def get_layer_groups(self):
m = self.model[0]
return [*zip(m.rnns, m.dropouths), (self.model[1], m.dropouti)]
class LanguageModelData():
def __init__(self, path, pad_idx, n_tok, trn_dl, val_dl, test_dl=None, **kwargs):
self.path,self.pad_idx,self.n_tok = path,pad_idx,n_tok
self.trn_dl,self.val_dl,self.test_dl = trn_dl,val_dl,test_dl
def get_model(self, opt_fn, emb_sz, n_hid, n_layers, **kwargs):
m = get_language_model(self.n_tok, emb_sz, n_hid, n_layers, self.pad_idx, **kwargs)
model = LanguageModel(to_gpu(m))
return RNN_Learner(self, model, opt_fn=opt_fn)
class RNN_Learner(Learner):
def __init__(self, data, models, **kwargs):
super().__init__(data, models, **kwargs)
def _get_crit(self, data): return F.cross_entropy
def fit(self, *args, **kwargs): return super().fit(*args, **kwargs, seq_first=True)
def save_encoder(self, name): save_model(self.model[0], self.get_model_path(name))
def load_encoder(self, name): load_model(self.model[0], self.get_model_path(name))
class TextModel(BasicModel):
def get_layer_groups(self):
m = self.model[0]
return [(m.encoder, m.dropouti), *zip(m.rnns, m.dropouths), (self.model[1])]
| 38.945946 | 126 | 0.62607 |
54b4ed1af049feb0425c65c7a4259a956927e72c | 126 | py | Python | profile_test.py | LudwigVonChesterfield/Asciiglet | d06d4fc5b63b1ab334b7597c6edccff95f80bc8e | [
"MIT"
] | null | null | null | profile_test.py | LudwigVonChesterfield/Asciiglet | d06d4fc5b63b1ab334b7597c6edccff95f80bc8e | [
"MIT"
] | null | null | null | profile_test.py | LudwigVonChesterfield/Asciiglet | d06d4fc5b63b1ab334b7597c6edccff95f80bc8e | [
"MIT"
] | null | null | null | import cProfile
p = cProfile.Profile()
p.enable()
import test
p.disable()
# p.print_stats()
p.dump_stats("results.prof")
| 9.692308 | 28 | 0.706349 |
c04d434e220a65c92aa50923dfd6ca452c645a5c | 1,229 | py | Python | 09-revisao/practice_python/guessing_game_one.py | lcnodc/codes | 068e04323362737c3f840b4e21a73cf0718aa401 | [
"MIT"
] | 1 | 2019-09-16T18:00:47.000Z | 2019-09-16T18:00:47.000Z | 09-revisao/practice_python/guessing_game_one.py | lcnodc/codes | 068e04323362737c3f840b4e21a73cf0718aa401 | [
"MIT"
] | null | null | null | 09-revisao/practice_python/guessing_game_one.py | lcnodc/codes | 068e04323362737c3f840b4e21a73cf0718aa401 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Exercise 9: Guess a number.
Generate a random number between 1 and 9 (including 1 and 9). Ask the
user to guess the number, then tell them whether they guessed too low,
too high, or exactly right. (Hint: remember to use the user input
lessons from the very first exercise)
Extras:
- Keep the game going until the user types “exit”
- Keep track of how many guesses the user has taken, and when the
game ends, print this out.
"""
from random import randint
attempts = 0
guessed = False
hits = 0
repeat = True
while repeat:
random_number = randint(1, 9)
while not guessed:
user_number = int(input("Guess the number (1 - 9):"))
message, guessed, attempts, hits = \
("Gotcha!", True, attempts + 1, hits + 1) if user_number == random_number else \
("Too low!", False, attempts + 1, hits + 0) if user_number < random_number else \
("Too high!", False, attempts + 1, hits + 0)
print(message)
repeat, guessed = \
(False, False) if input("Try again (Type 'exit' to exit)? ").lower() == "exit" else \
(True, False)
print("Attempts: %d\nHits: %d" % (attempts, hits))
| 31.512821 | 97 | 0.627339 |
98c48df01b6ad0a326613a7f9346883265b46af4 | 1,451 | py | Python | utils.py | edward-zhu/neural-transform | af0829733e21ea3a1f1748b33a42ebbc0e041969 | [
"Apache-2.0"
] | 3 | 2018-05-14T05:09:31.000Z | 2021-01-11T09:51:03.000Z | utils.py | edward-zhu/neural-transform | af0829733e21ea3a1f1748b33a42ebbc0e041969 | [
"Apache-2.0"
] | null | null | null | utils.py | edward-zhu/neural-transform | af0829733e21ea3a1f1748b33a42ebbc0e041969 | [
"Apache-2.0"
] | null | null | null | import torch
from torchvision import transforms
import numpy as np
from PIL import Image
def get_mean_var(c):
n_batch, n_ch, h, w = c.size()
c_view = c.view(n_batch, n_ch, h * w)
c_mean = c_view.mean(2)
c_mean = c_mean.view(n_batch, n_ch, 1, 1).expand_as(c)
c_var = c_view.var(2)
c_var = c_var.view(n_batch, n_ch, 1, 1).expand_as(c)
# c_var = c_var * (h * w - 1) / float(h * w) # unbiased variance
return c_mean, c_var
def save_image(tensor_orig, tensor_transformed, style, filename):
assert tensor_orig.size() == tensor_transformed.size()
def recover(t):
t = t.cpu().numpy()[0].transpose(1, 2, 0) * 255.
t = t.clip(0, 255).astype(np.uint8)
return t
result = Image.fromarray(recover(tensor_transformed))
orig = Image.fromarray(recover(tensor_orig))
style = Image.fromarray(recover(style))
new_im = Image.new('RGB', (result.size[0] * 3 + 5 * 2, result.size[1]))
new_im.paste(orig, (0, 0))
new_im.paste(result, (result.size[0] + 5, 0))
new_im.paste(style, (result.size[0] * 2 + 10, 0))
new_im.save(filename)
def recover_from_ImageNet(img):
'''
recover from ImageNet normalized rep to real img rep [0, 1]
'''
img *= torch.Tensor([0.229, 0.224, 0.225]
).view(1, 3, 1, 1).expand_as(img)
img += torch.Tensor([0.485, 0.456, 0.406]
).view(1, 3, 1, 1).expand_as(img)
return img
| 29.02 | 75 | 0.608546 |
945623500cde0ef435e8d8d91f7b36f2ce119040 | 4,943 | py | Python | featureflags/evaluations/segment.py | meghamathur03/ff-python-server-sdk | 33b599aea44c0fe0854836f271642b23c96b7bb2 | [
"Apache-2.0"
] | null | null | null | featureflags/evaluations/segment.py | meghamathur03/ff-python-server-sdk | 33b599aea44c0fe0854836f271642b23c96b7bb2 | [
"Apache-2.0"
] | null | null | null | featureflags/evaluations/segment.py | meghamathur03/ff-python-server-sdk | 33b599aea44c0fe0854836f271642b23c96b7bb2 | [
"Apache-2.0"
] | null | null | null | from typing import Any, Dict, List, Type, TypeVar, Union
import attr
from featureflags.models import UNSET, Unset
from .auth_target import Target
from .clause import Clause, Clauses
from .tag import Tag
T = TypeVar("T", bound="Segment")
@attr.s(auto_attribs=True)
class Segment(object):
identifier: str
name: str
environment: Union[Unset, str] = UNSET
tags: Union[Unset, List[Tag]] = UNSET
included: Union[Unset, List[str]] = UNSET
excluded: Union[Unset, List[str]] = UNSET
rules: Union[Unset, 'Clauses'] = UNSET
created_at: Union[Unset, int] = UNSET
modified_at: Union[Unset, int] = UNSET
version: Union[Unset, int] = UNSET
additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)
def evaluate(self, target: Target) -> bool:
if not isinstance(self.included, Unset):
if target.identifier in self.included:
return True
if not isinstance(self.excluded, Unset):
if target.identifier in self.excluded:
return True
if not isinstance(self.rules, Unset):
if self.rules.evaluate(target, None):
return True
return False
def to_dict(self) -> Dict[str, Any]:
identifier = self.identifier
name = self.name
environment = self.environment
tags: Union[Unset, List[Dict[str, Any]]] = UNSET
if not isinstance(self.tags, Unset):
tags = []
for tags_item_data in self.tags:
tags_item = tags_item_data.to_dict()
tags.append(tags_item)
included = self.included
excluded = self.excluded
rules: Union[Unset, List[Dict[str, Any]]] = UNSET
if not isinstance(self.rules, Unset):
rules = []
for rules_item_data in self.rules:
rules_item = rules_item_data.to_dict()
rules.append(rules_item)
created_at = self.created_at
modified_at = self.modified_at
version = self.version
field_dict: Dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"identifier": identifier,
"name": name,
}
)
if environment is not UNSET:
field_dict["environment"] = environment
if tags is not UNSET:
field_dict["tags"] = tags
if included is not UNSET:
field_dict["included"] = included
if excluded is not UNSET:
field_dict["excluded"] = excluded
if rules is not UNSET:
field_dict["rules"] = rules
if created_at is not UNSET:
field_dict["createdAt"] = created_at
if modified_at is not UNSET:
field_dict["modifiedAt"] = modified_at
if version is not UNSET:
field_dict["version"] = version
return field_dict
@classmethod
def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
d = src_dict.copy()
identifier = d.pop("identifier")
name = d.pop("name")
environment = d.pop("environment", UNSET)
tags = []
_tags = d.pop("tags", UNSET)
for tags_item_data in _tags or []:
tags_item = Tag.from_dict(tags_item_data)
tags.append(tags_item)
included = d.pop("included", UNSET)
excluded = d.pop("excluded", UNSET)
rules: Clauses = Clauses()
_rules = d.pop("rules", UNSET)
for rules_item_data in _rules or []:
rules_item = Clause.from_dict(rules_item_data)
rules.append(rules_item)
created_at = d.pop("createdAt", UNSET)
modified_at = d.pop("modifiedAt", UNSET)
version = d.pop("version", UNSET)
segment = cls(
identifier=identifier,
name=name,
environment=environment,
tags=tags,
included=included,
excluded=excluded,
rules=rules,
created_at=created_at,
modified_at=modified_at,
version=version,
)
segment.additional_properties = d
return segment
@property
def additional_keys(self) -> List[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties
class Segments(Dict[str, Segment]):
def evaluate(self, target: Target) -> bool:
for _, segment in self.items():
if not segment.evaluate(target):
return False
return True
| 29.422619 | 77 | 0.588711 |
99cbb1134bfe0e20df3a314b1706fe982d43916b | 2,813 | py | Python | tests/test_prepare_data.py | Abhishek2304/Cerebro-System-Ray | 1e2f2ae291cd449573f87bb83fb2bda12e606b3a | [
"Apache-2.0"
] | 16 | 2020-05-09T03:55:38.000Z | 2022-02-27T01:06:09.000Z | tests/test_prepare_data.py | Abhishek2304/Cerebro-System-Ray | 1e2f2ae291cd449573f87bb83fb2bda12e606b3a | [
"Apache-2.0"
] | 16 | 2020-04-20T20:47:10.000Z | 2021-12-02T05:11:09.000Z | tests/test_prepare_data.py | Abhishek2304/Cerebro-System-Ray | 1e2f2ae291cd449573f87bb83fb2bda12e606b3a | [
"Apache-2.0"
] | 6 | 2020-06-08T01:27:03.000Z | 2021-12-02T12:06:44.000Z | # Copyright 2020 Supun Nakandala, Yuhao Zhang, and Arun Kumar. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import unittest
import tensorflow as tf
from cerebro.backend import SparkBackend
from cerebro.keras import SparkEstimator
from cerebro.storage import LocalStore
from cerebro.tune import RandomSearch, GridSearch, hp_choice
from pyspark.sql import SparkSession
def estimator_gen_fn(params):
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Input(shape=692, name='features'))
model.add(tf.keras.layers.Dense(100, input_dim=692))
model.add(tf.keras.layers.Dense(1, input_dim=100))
model.add(tf.keras.layers.Activation('sigmoid'))
optimizer = tf.keras.optimizers.Adam(lr=params['lr'])
loss = 'binary_crossentropy'
keras_estimator = SparkEstimator(
model=model,
optimizer=optimizer,
loss=loss,
metrics=['acc'],
batch_size=10)
return keras_estimator
class TestPrepareData(unittest.TestCase):
def test_prepare_data(self):
spark = SparkSession \
.builder \
.master("local[3]") \
.appName("Python Spark SQL basic example") \
.getOrCreate()
# Load training data
df = spark.read.format("libsvm").load("./tests/sample_libsvm_data.txt").repartition(8)
df.printSchema()
backend = SparkBackend(spark_context=spark.sparkContext, num_workers=3)
store = LocalStore('/tmp', train_path='/tmp/train_data', val_path='/tmp/val_data')
backend.prepare_data(store, df, validation=0.25)
######## Random Search ###########
search_space = {'lr': hp_choice([0.01, 0.001, 0.0001])}
random_search = RandomSearch(backend, store, estimator_gen_fn, search_space, 3, 1,
validation=0.25,
evaluation_metric='loss',
feature_columns=['features'], label_columns=['label'])
model = random_search.fit_on_prepared_data()
output_df = model.transform(df)
output_df.select('label', 'label__output').show(n=10)
assert True
if __name__ == "__main__":
unittest.main() | 36.064103 | 94 | 0.646996 |
f1177e19b45772734c3642f939466e6cc8751cf5 | 5,381 | py | Python | hub-sim/sim.py | concord-consortium/sensaurus | 36f0229d1bb527eb05d1cc96dd2bd331a2c193f4 | [
"MIT"
] | null | null | null | hub-sim/sim.py | concord-consortium/sensaurus | 36f0229d1bb527eb05d1cc96dd2bd331a2c193f4 | [
"MIT"
] | null | null | null | hub-sim/sim.py | concord-consortium/sensaurus | 36f0229d1bb527eb05d1cc96dd2bd331a2c193f4 | [
"MIT"
] | null | null | null | import paho.mqtt.client as paho
import ssl
import time
import json
import random
import hjson
class Hub(object):
def __init__(self, config):
self.mqttc = None
self.connected = False
self.devices = []
self.owner_id = config['owner_id']
self.config = config
self.id = config['hub_id']
self.send_interval = None
self.status_sent = False
# connect to the MQTT service (broker)
def connect(self):
self.mqttc = paho.Client()
self.mqttc.on_connect = self.on_connect
self.mqttc.on_message = self.on_message
self.mqttc.tls_set(self.config['ca_path'], certfile=self.config['cert_path'], keyfile=self.config['key_path'],
cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
self.mqttc.connect(self.config['host'], 8883, keepalive=60)
self.mqttc.loop_start()
self.mqttc.subscribe('%s/hub/%s/command' % (self.owner_id, self.id))
self.mqttc.subscribe('%s/hub/%s/actuators' % (self.owner_id, self.id))
def on_connect(self, client, userdata, flags, rc):
self.connected = True
print('connected (result: %s)' % rc)
# handle incoming messages on subscribed topics
def on_message(self, client, userdata, msg):
if msg.topic.endswith('command'):
message = json.loads(msg.payload)
command = message['command']
if command == 'req_status':
self.send_status()
elif command == 'req_devices':
self.send_device_info()
elif command == 'set_send_interval':
self.send_interval = message['send_interval']
print('send interval: %.2f seconds' % self.send_interval)
elif command == 'update_firmware':
print('firmware update: %s' % message['url'])
elif msg.topic.endswith('actuators'):
message = json.loads(msg.payload)
for (k, v) in message.items():
print('setting actuator %s to %s' % (k, v))
def add_device(self, device):
self.devices.append(device)
if self.connected:
self.send_device_info()
# send info to status topic for this hub
def send_status(self):
message = {
'wifi_network': 'abc',
'wifi_password': '123',
'host': self.config['host'],
}
topic_name = '%s/hub/%s/status' % (self.owner_id, self.id)
self.mqttc.publish(topic_name, json.dumps(message))
self.status_sent = True
print('sent status');
# send info about devices currently connected to this hub
def send_device_info(self):
device_infos = {}
plug = 1
for d in self.devices:
device_info = {
'version': 1,
'plug': plug,
'components': d.components, # components is a list of dictionaries
}
device_infos[d.id] = device_info
topic_name = '%s/device/%s' % (self.owner_id, d.id)
self.mqttc.publish(topic_name, self.id, qos=1) # send hub ID for this device
plug += 1
topic_name = '%s/hub/%s/devices' % (self.owner_id, self.id)
self.mqttc.publish(topic_name, json.dumps(device_infos), qos=1) # send list of device info dictionaries
print('sent %d devices' % len(device_infos))
# send sensor values from devices connected to this hub
def send_sensor_values(self):
values = {}
values['time'] = int(time.time())
for d in self.devices:
for c in d.components:
if c['dir'] == 'i':
value = random.uniform(10.0, 20.0)
values[c['id']] = '%.2f' % value
topic_name = '%s/hub/%s/sensors' % (self.owner_id, self.id)
self.mqttc.publish(topic_name, json.dumps(values), qos=1)
print('sending %d sensor values to %s' % (len(values) - 1, topic_name))
# send simulated data
def run(self):
while True:
if self.send_interval:
time.sleep(self.send_interval) # not quite going to match send interval, but that's ok for this simulation
else:
time.sleep(0.5)
if self.connected:
if not self.status_sent:
self.send_status()
self.send_device_info()
if self.send_interval:
self.send_sensor_values()
else:
print('waiting for connection...')
class Device(object):
def __init__(self, id, components): # components should be a list of dictionaries
self.id = id
self.components = components
for c in self.components:
c['id'] = '%x-%s' % (self.id, c['type'][:5]) # construct a component ID using device ID and component type
print('loaded component %s' % c['id'])
# create hub and devices
config = hjson.loads(open('config.hjson').read())
hub = Hub(config)
for device_info in config['devices']:
device = Device(device_info['id'], device_info['components'])
hub.add_device(device)
if 'send_interval' in config:
hub.send_interval = int(config['send_interval'])
# connect to the MQTT service (broker)
hub.connect()
# start generating sensor data
hub.run()
| 36.856164 | 123 | 0.584092 |
15f56902a780b4e05b5ed5f4c2768ce13a31ef6f | 3,513 | py | Python | XYZHubConnector/xyz_qgis/loader/space_loader.py | heremaps/xyz-qgis-plugin | 570402e1bb886db5dd36d2b2d2f278a25ef8ad12 | [
"MIT"
] | 19 | 2019-03-06T18:25:17.000Z | 2021-07-21T10:08:20.000Z | XYZHubConnector/xyz_qgis/loader/space_loader.py | heremaps/xyz-qgis-plugin | 570402e1bb886db5dd36d2b2d2f278a25ef8ad12 | [
"MIT"
] | 28 | 2019-03-07T18:18:44.000Z | 2021-11-16T13:49:39.000Z | XYZHubConnector/xyz_qgis/loader/space_loader.py | heremaps/xyz-qgis-plugin | 570402e1bb886db5dd36d2b2d2f278a25ef8ad12 | [
"MIT"
] | 8 | 2019-03-01T10:41:08.000Z | 2021-01-18T18:02:56.000Z | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (c) 2019 HERE Europe B.V.
#
# SPDX-License-Identifier: MIT
# License-Filename: LICENSE
#
###############################################################################
from qgis.PyQt.QtCore import QThreadPool
from ..controller import ChainController, NetworkFun, WorkerFun
from ..network import net_handler
class LoadSpaceController(ChainController):
"""load space metadata (list space)
Args:
conn_info: token
"""
# Feature
def __init__(self, network):
super().__init__()
self.pool = QThreadPool() # .globalInstance() will crash afterward
self._config(network)
def start(self, conn_info):
super().start(conn_info)
def _config(self, network):
self.config_fun(
[
NetworkFun(network.list_spaces),
WorkerFun(network.on_received, self.pool),
]
)
class StatSpaceController(ChainController):
"""get statistics of given space (count, byteSize, bbox)
Args:
conn_info: token
"""
# Feature
def __init__(self, network):
super().__init__()
self.pool = QThreadPool() # .globalInstance() will crash afterward
self._config(network)
def start(self, conn_info):
super().start(conn_info)
def _config(self, network):
self.config_fun(
[
NetworkFun(network.get_statistics),
# NetworkFun( network.get_count),
WorkerFun(network.on_received, self.pool),
]
)
class DeleteSpaceController(ChainController):
"""Delete space
Args:
conn_info: token + space_id
"""
# Feature
def __init__(self, network):
super().__init__()
self.pool = QThreadPool() # .globalInstance() will crash afterward
self._config(network)
def start(self, conn_info):
super().start(conn_info)
def _config(self, network):
self.config_fun(
[
NetworkFun(network.del_space),
WorkerFun(network.on_received, self.pool),
]
)
class EditSpaceController(ChainController):
"""Edit space metadata
Args:
conn_info: token + space_id
meta: new metadata/space_info (title, description)
"""
# Feature
def __init__(self, network):
super().__init__()
self.pool = QThreadPool() # .globalInstance() will crash afterward
self._config(network)
def start(self, conn_info, meta):
super().start(conn_info, meta)
def _config(self, network):
self.config_fun(
[
NetworkFun(network.edit_space),
WorkerFun(network.on_received, self.pool),
]
)
class CreateSpaceController(ChainController):
"""Create new space
Args:
conn_info: token + space_id
meta: new metadata/space_info (title, description)
"""
def __init__(self, network):
super().__init__()
self.pool = QThreadPool() # .globalInstance() will crash afterward
self._config(network)
def start(self, conn_info, meta):
super().start(conn_info, meta)
def _config(self, network):
self.config_fun(
[
NetworkFun(network.add_space),
WorkerFun(network.on_received, self.pool),
]
)
| 25.642336 | 79 | 0.56419 |
62c10bf396bd6c8e93dca24f45b9d086a4be6fea | 1,300 | py | Python | hat11/analyze.py | bmorris3/friedrich | a2a4d9c446a60e78879bdfcd66a37bd5946a4ef9 | [
"MIT"
] | null | null | null | hat11/analyze.py | bmorris3/friedrich | a2a4d9c446a60e78879bdfcd66a37bd5946a4ef9 | [
"MIT"
] | null | null | null | hat11/analyze.py | bmorris3/friedrich | a2a4d9c446a60e78879bdfcd66a37bd5946a4ef9 | [
"MIT"
] | null | null | null |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# Import dev version of friedrich:
import sys
sys.path.insert(0, '../')
from friedrich.analysis import MCMCResults
from friedrich.lightcurve import hat11_params_morris
from glob import glob
import matplotlib.pyplot as plt
#archive_path = ('/gscratch/stf/bmmorris/friedrich/chains{0:03d}.hdf5'
# .format(int(sys.argv[1])))
# archive_path = ('/media/PASSPORT/friedrich/chains{0:03d}.hdf5'
# .format(int(sys.argv[1])))
#
# m = MCMCResults(archive_path)
# # m.plot_corner()
# # m.plot_lnprob()
# # m.plot_max_lnp_lc(hat11_params_morris())
# # m.plot_lat_lon()
# # m.plot_star()
# m.plot_star_projected()
# plt.savefig('tmp/{0:03d}.png'.format(int(sys.argv[1])))
# #plt.show()
archive_paths = sorted(glob('/local/tmp/friedrich/hat11/chains???.hdf5'))
#archive_paths = ['/astro/users/bmmorris/Desktop/chains000.hdf5']
for archive_path in archive_paths:
m = MCMCResults(archive_path, hat11_params_morris())
#m.max_lnp_theta_phi()
m.plot_lnprob()
m.plot_corner()
#m.plot_star_projected()
transit_number = m.index.split('chains')[1]
#plt.savefig('tmp/{0:03d}.png'.format(int(transit_number)))
plt.show()
#plt.close()
#plt.show()
| 31.707317 | 73 | 0.690769 |
719c06daed5dc41ae568598682fbd3636bd1f829 | 318 | py | Python | PythonExercicios/Mundo 2/8_estrutura_de_repeticao_for/ex055.py | GuilhermoCampos/Curso-Python3-curso-em-video | 723767bc6069e9c1fa9e28fe412e694f9eb8d05e | [
"MIT"
] | null | null | null | PythonExercicios/Mundo 2/8_estrutura_de_repeticao_for/ex055.py | GuilhermoCampos/Curso-Python3-curso-em-video | 723767bc6069e9c1fa9e28fe412e694f9eb8d05e | [
"MIT"
] | null | null | null | PythonExercicios/Mundo 2/8_estrutura_de_repeticao_for/ex055.py | GuilhermoCampos/Curso-Python3-curso-em-video | 723767bc6069e9c1fa9e28fe412e694f9eb8d05e | [
"MIT"
] | null | null | null | maior = 0
menor = 300
for pes in range(1, 6):
peso = float(input('Digite o Peso(kg) da {}º pessoa: '.format(pes)))
if peso > maior:
maior = peso
elif peso < menor:
menor = peso
print('O Maior peso registrado foi de {}kg, enquanto o Menor peso Registrado foi de {}kg.'.format(maior, menor))
| 31.8 | 112 | 0.625786 |
abf09d567632228af50c74cd88859e2d8232cc80 | 2,810 | py | Python | keystone/identity/mapping_backends/base.py | ISCAS-VDI/keystone | 11af181c06d78026c89a873f62931558e80f3192 | [
"Apache-2.0"
] | null | null | null | keystone/identity/mapping_backends/base.py | ISCAS-VDI/keystone | 11af181c06d78026c89a873f62931558e80f3192 | [
"Apache-2.0"
] | null | null | null | keystone/identity/mapping_backends/base.py | ISCAS-VDI/keystone | 11af181c06d78026c89a873f62931558e80f3192 | [
"Apache-2.0"
] | null | null | null | # Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
from keystone import exception
@six.add_metaclass(abc.ABCMeta)
class MappingDriverV8(object):
"""Interface description for an ID Mapping driver."""
@abc.abstractmethod
def get_public_id(self, local_entity):
"""Return the public ID for the given local entity.
:param dict local_entity: Containing the entity domain, local ID and
type ('user' or 'group').
:returns: public ID, or None if no mapping is found.
"""
raise exception.NotImplemented() # pragma: no cover
@abc.abstractmethod
def get_id_mapping(self, public_id):
"""Return the local mapping.
:param public_id: The public ID for the mapping required.
:returns dict: Containing the entity domain, local ID and type. If no
mapping is found, it returns None.
"""
raise exception.NotImplemented() # pragma: no cover
@abc.abstractmethod
def create_id_mapping(self, local_entity, public_id=None):
"""Create and store a mapping to a public_id.
:param dict local_entity: Containing the entity domain, local ID and
type ('user' or 'group').
:param public_id: If specified, this will be the public ID. If this
is not specified, a public ID will be generated.
:returns: public ID
"""
raise exception.NotImplemented() # pragma: no cover
@abc.abstractmethod
def delete_id_mapping(self, public_id):
"""Delete an entry for the given public_id.
:param public_id: The public ID for the mapping to be deleted.
The method is silent if no mapping is found.
"""
raise exception.NotImplemented() # pragma: no cover
@abc.abstractmethod
def purge_mappings(self, purge_filter):
"""Purge selected identity mappings.
:param dict purge_filter: Containing the attributes of the filter that
defines which entries to purge. An empty
filter means purge all mappings.
"""
raise exception.NotImplemented() # pragma: no cover
| 34.268293 | 78 | 0.64911 |
af91059f642aaf41f102062b5aa0d44454785265 | 322 | py | Python | Projekteuler/projecteuler_aufgabe003.py | kilian-funk/Python-Kurs | f5ef5a2fb2a875d2e80d77c1a6c3596a0e577d7f | [
"MIT"
] | null | null | null | Projekteuler/projecteuler_aufgabe003.py | kilian-funk/Python-Kurs | f5ef5a2fb2a875d2e80d77c1a6c3596a0e577d7f | [
"MIT"
] | null | null | null | Projekteuler/projecteuler_aufgabe003.py | kilian-funk/Python-Kurs | f5ef5a2fb2a875d2e80d77c1a6c3596a0e577d7f | [
"MIT"
] | null | null | null | """
Aufgabe 3 aus http://projecteuler.net
(Deutsche Übersetzung auf http://projekteuler.de)
Größter Primfaktor
Die Primfaktoren von 13195 sind 5, 7, 13 und 29.
Was ist der größte Primfaktor der Zahl 600851475143?
"""
zahl = 600851475143
faktor = # Los geht's ...
print("Groesster Primfaktor ist {}".format(faktor))
| 17.888889 | 52 | 0.732919 |
ee99e9a51876ebb4c54b5f4c32c0354747cc5ef3 | 20,529 | py | Python | raiden/waiting.py | ezdac/raiden | d7504996e6738b55d5a9dcf9a36ef66797f6f326 | [
"MIT"
] | 1 | 2020-10-19T15:00:42.000Z | 2020-10-19T15:00:42.000Z | raiden/waiting.py | ezdac/raiden | d7504996e6738b55d5a9dcf9a36ef66797f6f326 | [
"MIT"
] | null | null | null | raiden/waiting.py | ezdac/raiden | d7504996e6738b55d5a9dcf9a36ef66797f6f326 | [
"MIT"
] | null | null | null | import time
from enum import Enum
from typing import TYPE_CHECKING, List
import gevent
import structlog
from raiden.storage.restore import get_state_change_with_transfer_by_secrethash
from raiden.transfer import channel, views
from raiden.transfer.events import EventPaymentReceivedSuccess
from raiden.transfer.identifiers import CanonicalIdentifier
from raiden.transfer.mediated_transfer.events import EventUnlockClaimFailed
from raiden.transfer.mediated_transfer.state_change import ActionInitMediator, ActionInitTarget
from raiden.transfer.state import (
CHANNEL_AFTER_CLOSE_STATES,
ChannelState,
NettingChannelEndState,
NetworkState,
)
from raiden.transfer.state_change import (
ContractReceiveChannelWithdraw,
ContractReceiveSecretReveal,
)
from raiden.utils.formatting import to_checksum_address
from raiden.utils.typing import (
Address,
Any,
BlockNumber,
Callable,
ChannelID,
PaymentAmount,
PaymentID,
SecretHash,
Sequence,
TokenAddress,
TokenAmount,
TokenNetworkRegistryAddress,
WithdrawAmount,
)
if TYPE_CHECKING:
from raiden.raiden_service import RaidenService # pylint: disable=unused-import
log = structlog.get_logger(__name__)
ALARM_TASK_ERROR_MSG = "Waiting relies on alarm task polling to update the node's internal state."
TRANSPORT_ERROR_MSG = "Waiting for protocol messages requires a running transport."
def wait_until(func: Callable, wait_for: float = None, sleep_for: float = 0.5) -> Any:
"""Test for a function and wait for it to return a truth value or to timeout.
Returns the value or None if a timeout is given and the function didn't return
inside time timeout
Args:
func: a function to be evaluated, use lambda if parameters are required
wait_for: the maximum time to wait, or None for an infinite loop
sleep_for: how much to gevent.sleep between calls
Returns:
func(): result of func, if truth value, or None"""
res = func()
if res:
return res
if wait_for:
deadline = time.time() + wait_for
while not res and time.time() <= deadline:
gevent.sleep(sleep_for)
res = func()
else:
while not res:
gevent.sleep(sleep_for)
res = func()
return res
def wait_for_block(
raiden: "RaidenService", block_number: BlockNumber, retry_timeout: float
) -> None: # pragma: no unittest
current = raiden.get_block_number()
log_details = {
"node": to_checksum_address(raiden.address),
"target_block_number": block_number,
}
while current < block_number:
assert raiden, ALARM_TASK_ERROR_MSG
assert raiden.alarm, ALARM_TASK_ERROR_MSG
log.debug("wait_for_block", current_block_number=current, **log_details)
gevent.sleep(retry_timeout)
current = raiden.get_block_number()
def wait_for_newchannel(
raiden: "RaidenService",
token_network_registry_address: TokenNetworkRegistryAddress,
token_address: TokenAddress,
partner_address: Address,
retry_timeout: float,
) -> None: # pragma: no unittest
"""Wait until the channel with partner_address is registered.
Note:
This does not time out, use gevent.Timeout.
"""
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
token_network_registry_address,
token_address,
partner_address,
)
log_details = {
"node": to_checksum_address(raiden.address),
"token_network_registry_address": to_checksum_address(token_network_registry_address),
"token_address": to_checksum_address(token_address),
"partner_address": to_checksum_address(partner_address),
}
while channel_state is None:
assert raiden, ALARM_TASK_ERROR_MSG
assert raiden.alarm, ALARM_TASK_ERROR_MSG
log.debug("wait_for_newchannel", **log_details)
gevent.sleep(retry_timeout)
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
token_network_registry_address,
token_address,
partner_address,
)
def wait_for_participant_deposit(
raiden: "RaidenService",
token_network_registry_address: TokenNetworkRegistryAddress,
token_address: TokenAddress,
partner_address: Address,
target_address: Address,
target_balance: TokenAmount,
retry_timeout: float,
) -> None: # pragma: no unittest
"""Wait until a given channels balance exceeds the target balance.
Note:
This does not time out, use gevent.Timeout.
"""
if target_address == raiden.address:
balance = lambda channel_state: channel_state.our_state.contract_balance
else:
balance = lambda channel_state: channel_state.partner_state.contract_balance
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
token_network_registry_address,
token_address,
partner_address,
)
if not channel_state:
raise ValueError("no channel could be found between provided partner and target addresses")
current_balance = balance(channel_state)
log_details = {
"node": to_checksum_address(raiden.address),
"token_network_registry_address": to_checksum_address(token_network_registry_address),
"token_address": to_checksum_address(token_address),
"partner_address": to_checksum_address(partner_address),
"target_address": to_checksum_address(target_address),
"target_balance": target_balance,
}
while current_balance < target_balance:
assert raiden, ALARM_TASK_ERROR_MSG
assert raiden.alarm, ALARM_TASK_ERROR_MSG
log.debug("wait_for_participant_deposit", current_balance=current_balance, **log_details)
gevent.sleep(retry_timeout)
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
token_network_registry_address,
token_address,
partner_address,
)
current_balance = balance(channel_state)
def wait_single_channel_deposit(
app_deposit: "RaidenService",
app_partner: "RaidenService",
registry_address: TokenNetworkRegistryAddress,
token_address: TokenAddress,
total_deposit: TokenAmount,
retry_timeout: float,
) -> None:
""" Wait until a deposit of `total_deposit` for app_deposit is seen by both apps"""
wait_for_participant_deposit(
raiden=app_deposit,
token_network_registry_address=registry_address,
token_address=token_address,
partner_address=app_partner.address,
target_address=app_deposit.address,
target_balance=total_deposit,
retry_timeout=retry_timeout,
)
wait_for_participant_deposit(
raiden=app_partner,
token_network_registry_address=registry_address,
token_address=token_address,
partner_address=app_deposit.address,
target_address=app_deposit.address,
target_balance=total_deposit,
retry_timeout=retry_timeout,
)
def wait_both_channel_deposit(
app_deposit: "RaidenService",
app_partner: "RaidenService",
registry_address: TokenNetworkRegistryAddress,
token_address: TokenAddress,
total_deposit: TokenAmount,
retry_timeout: float,
) -> None:
""" Wait until a deposit of `total_deposit` for both apps is seen by both apps"""
wait_single_channel_deposit(
app_deposit=app_deposit,
app_partner=app_partner,
registry_address=registry_address,
token_address=token_address,
total_deposit=total_deposit,
retry_timeout=retry_timeout,
)
wait_single_channel_deposit(
app_deposit=app_partner,
app_partner=app_deposit,
registry_address=registry_address,
token_address=token_address,
total_deposit=total_deposit,
retry_timeout=retry_timeout,
)
def wait_for_payment_balance(
raiden: "RaidenService",
token_network_registry_address: TokenNetworkRegistryAddress,
token_address: TokenAddress,
partner_address: Address,
target_address: Address,
target_balance: TokenAmount,
retry_timeout: float,
) -> None: # pragma: no unittest
"""Wait until a given channel's balance exceeds the target balance.
Note:
This does not time out, use gevent.Timeout.
"""
def get_balance(end_state: NettingChannelEndState) -> TokenAmount:
if end_state.balance_proof:
return end_state.balance_proof.transferred_amount
else:
return TokenAmount(0)
if target_address == raiden.address:
balance = lambda channel_state: get_balance(channel_state.partner_state)
elif target_address == partner_address:
balance = lambda channel_state: get_balance(channel_state.our_state)
else:
raise ValueError("target_address must be one of the channel participants")
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
token_network_registry_address,
token_address,
partner_address,
)
current_balance = balance(channel_state)
log_details = {
"token_network_registry_address": to_checksum_address(token_network_registry_address),
"token_address": to_checksum_address(token_address),
"partner_address": to_checksum_address(partner_address),
"target_address": to_checksum_address(target_address),
"target_balance": target_balance,
}
while current_balance < target_balance:
assert raiden, ALARM_TASK_ERROR_MSG
assert raiden.alarm, ALARM_TASK_ERROR_MSG
log.critical("wait_for_payment_balance", current_balance=current_balance, **log_details)
gevent.sleep(retry_timeout)
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
token_network_registry_address,
token_address,
partner_address,
)
current_balance = balance(channel_state)
def wait_for_channel_in_states(
raiden: "RaidenService",
token_network_registry_address: TokenNetworkRegistryAddress,
token_address: TokenAddress,
channel_ids: List[ChannelID],
retry_timeout: float,
target_states: Sequence[ChannelState],
) -> None:
"""Wait until all channels are in `target_states`.
Raises:
ValueError: If the token_address is not registered in the
token_network_registry.
Note:
This does not time out, use gevent.Timeout.
"""
chain_state = views.state_from_raiden(raiden)
token_network = views.get_token_network_by_token_address(
chain_state=chain_state,
token_network_registry_address=token_network_registry_address,
token_address=token_address,
)
if token_network is None:
raise ValueError(
f"The token {to_checksum_address(token_address)} is not registered on "
f"the network {to_checksum_address(token_network_registry_address)}."
)
token_network_address = token_network.address
list_cannonical_ids = [
CanonicalIdentifier(
chain_identifier=chain_state.chain_id,
token_network_address=token_network_address,
channel_identifier=channel_identifier,
)
for channel_identifier in channel_ids
]
log_details = {
"token_network_registry_address": to_checksum_address(token_network_registry_address),
"token_address": to_checksum_address(token_address),
"list_cannonical_ids": list_cannonical_ids,
"target_states": target_states,
}
while list_cannonical_ids:
assert raiden, ALARM_TASK_ERROR_MSG
assert raiden.alarm, ALARM_TASK_ERROR_MSG
canonical_id = list_cannonical_ids[-1]
chain_state = views.state_from_raiden(raiden)
channel_state = views.get_channelstate_by_canonical_identifier(
chain_state=chain_state, canonical_identifier=canonical_id
)
channel_is_settled = (
channel_state is None or channel.get_status(channel_state) in target_states
)
if channel_is_settled:
list_cannonical_ids.pop()
else:
log.debug("wait_for_channel_in_states", **log_details)
gevent.sleep(retry_timeout)
def wait_for_close(
raiden: "RaidenService",
token_network_registry_address: TokenNetworkRegistryAddress,
token_address: TokenAddress,
channel_ids: List[ChannelID],
retry_timeout: float,
) -> None: # pragma: no unittest
"""Wait until all channels are closed.
Note:
This does not time out, use gevent.Timeout.
"""
return wait_for_channel_in_states(
raiden=raiden,
token_network_registry_address=token_network_registry_address,
token_address=token_address,
channel_ids=channel_ids,
retry_timeout=retry_timeout,
target_states=CHANNEL_AFTER_CLOSE_STATES,
)
def wait_for_token_network(
raiden: "RaidenService",
token_network_registry_address: TokenNetworkRegistryAddress,
token_address: TokenAddress,
retry_timeout: float,
) -> None: # pragma: no unittest
"""Wait until the token network is visible to the RaidenService.
Note:
This does not time out, use gevent.Timeout.
"""
token_network = views.get_token_network_by_token_address(
views.state_from_raiden(raiden), token_network_registry_address, token_address
)
log_details = {
"token_network_registry_address": to_checksum_address(token_network_registry_address),
"token_address": to_checksum_address(token_address),
}
while token_network is None:
assert raiden, ALARM_TASK_ERROR_MSG
assert raiden.alarm, ALARM_TASK_ERROR_MSG
log.debug("wait_for_token_network", **log_details)
gevent.sleep(retry_timeout)
token_network = views.get_token_network_by_token_address(
views.state_from_raiden(raiden), token_network_registry_address, token_address
)
def wait_for_settle(
raiden: "RaidenService",
token_network_registry_address: TokenNetworkRegistryAddress,
token_address: TokenAddress,
channel_ids: List[ChannelID],
retry_timeout: float,
) -> None: # pragma: no unittest
"""Wait until all channels are settled.
Note:
This does not time out, use gevent.Timeout.
"""
return wait_for_channel_in_states(
raiden=raiden,
token_network_registry_address=token_network_registry_address,
token_address=token_address,
channel_ids=channel_ids,
retry_timeout=retry_timeout,
target_states=(ChannelState.STATE_SETTLED,),
)
def wait_for_network_state(
raiden: "RaidenService",
node_address: Address,
network_state: NetworkState,
retry_timeout: float,
) -> None: # pragma: no unittest
"""Wait until `node_address` becomes healthy.
Note:
This does not time out, use gevent.Timeout.
"""
network_statuses = views.get_networkstatuses(views.state_from_raiden(raiden))
current = network_statuses.get(node_address)
log_details = {
"node_address": to_checksum_address(node_address),
"target_network_state": network_state,
}
while current != network_state:
assert raiden, TRANSPORT_ERROR_MSG
assert raiden.transport, TRANSPORT_ERROR_MSG
log.debug("wait_for_network_state", current_network_state=current, **log_details)
gevent.sleep(retry_timeout)
network_statuses = views.get_networkstatuses(views.state_from_raiden(raiden))
current = network_statuses.get(node_address)
def wait_for_healthy(
raiden: "RaidenService", node_address: Address, retry_timeout: float
) -> None: # pragma: no unittest
"""Wait until `node_address` becomes healthy.
Note:
This does not time out, use gevent.Timeout.
"""
wait_for_network_state(raiden, node_address, NetworkState.REACHABLE, retry_timeout)
class TransferWaitResult(Enum):
SECRET_REGISTERED_ONCHAIN = "secret registered onchain"
UNLOCKED = "unlocked"
UNLOCK_FAILED = "unlock_failed"
def wait_for_received_transfer_result(
raiden: "RaidenService",
payment_identifier: PaymentID,
amount: PaymentAmount,
retry_timeout: float,
secrethash: SecretHash,
) -> TransferWaitResult: # pragma: no unittest
"""Wait for the result of a transfer with the specified identifier
and/or secrethash. Possible results are onchain secret registration,
successful unlock and failed unlock. For a successful unlock, the
amount is also checked.
Note:
This does not time out, use gevent.Timeout.
"""
log_details = {"payment_identifier": payment_identifier, "amount": amount}
assert raiden, TRANSPORT_ERROR_MSG
assert raiden.wal, TRANSPORT_ERROR_MSG
assert raiden.transport, TRANSPORT_ERROR_MSG
stream = raiden.wal.storage.get_state_changes_stream(retry_timeout=retry_timeout)
result = None
while result is None:
state_events = raiden.wal.storage.get_events()
for event in state_events:
unlocked = (
isinstance(event, EventPaymentReceivedSuccess)
and event.identifier == payment_identifier
and PaymentAmount(event.amount) == amount
)
if unlocked:
result = TransferWaitResult.UNLOCKED
break
claim_failed = (
isinstance(event, EventUnlockClaimFailed)
and event.identifier == payment_identifier
and event.secrethash == secrethash
)
if claim_failed:
result = TransferWaitResult.UNLOCK_FAILED
break
state_changes = next(stream)
for state_change in state_changes:
registered_onchain = (
isinstance(state_change, ContractReceiveSecretReveal)
and state_change.secrethash == secrethash
)
if registered_onchain:
state_change_record = get_state_change_with_transfer_by_secrethash(
raiden.wal.storage, secrethash
)
assert state_change_record is not None, "Could not find state change for screthash"
msg = "Expected ActionInitMediator/ActionInitTarget not found in state changes."
expected_types = (ActionInitMediator, ActionInitTarget)
assert isinstance(state_change_record.data, expected_types), msg
transfer = None
if isinstance(state_change_record.data, ActionInitMediator):
transfer = state_change_record.data.from_transfer
if isinstance(state_change_record.data, ActionInitTarget):
transfer = state_change_record.data.transfer
if transfer is not None and raiden.get_block_number() <= transfer.lock.expiration:
return TransferWaitResult.SECRET_REGISTERED_ONCHAIN
log.debug("wait_for_transfer_result", **log_details)
gevent.sleep(retry_timeout)
return result # type: ignore
def wait_for_withdraw_complete(
raiden: "RaidenService",
canonical_identifier: CanonicalIdentifier,
total_withdraw: WithdrawAmount,
retry_timeout: float,
) -> None:
"""Wait until a withdraw with a specific identifier and amount
is seen in the WAL.
Note:
This does not time out, use gevent.Timeout.
"""
log_details = {
"canonical_identifier": canonical_identifier,
"target_total_withdraw": total_withdraw,
}
assert raiden, TRANSPORT_ERROR_MSG
assert raiden.wal, TRANSPORT_ERROR_MSG
assert raiden.transport, TRANSPORT_ERROR_MSG
stream = raiden.wal.storage.get_state_changes_stream(retry_timeout=retry_timeout)
while True:
state_changes = next(stream)
for state_change in state_changes:
found = (
isinstance(state_change, ContractReceiveChannelWithdraw)
and state_change.total_withdraw == total_withdraw
and state_change.canonical_identifier == canonical_identifier
)
if found:
return
log.debug("wait_for_withdraw_complete", **log_details)
gevent.sleep(retry_timeout)
| 34.101329 | 99 | 0.700813 |
1d73837cfba6bc4e5e39d1fa7da1861630c38139 | 5,607 | py | Python | mdrsl/data_handling/one_hot_encoding/encoding_book_keeping.py | joschout/Multi-Directional-Rule-Set-Learning | ef0620b115f4e0fd7fba3e752d238a8020c1ca6b | [
"Apache-2.0"
] | 3 | 2020-08-03T19:25:44.000Z | 2021-06-27T22:25:55.000Z | mdrsl/data_handling/one_hot_encoding/encoding_book_keeping.py | joschout/Multi-Directional-Rule-Set-Learning | ef0620b115f4e0fd7fba3e752d238a8020c1ca6b | [
"Apache-2.0"
] | null | null | null | mdrsl/data_handling/one_hot_encoding/encoding_book_keeping.py | joschout/Multi-Directional-Rule-Set-Learning | ef0620b115f4e0fd7fba3e752d238a8020c1ca6b | [
"Apache-2.0"
] | 2 | 2020-08-07T22:54:28.000Z | 2021-02-18T06:11:01.000Z | from typing import Optional, Dict, List, KeysView
Attr = str
class EncodingBookKeeper:
"""
Keeps track of a one hot encoding,
i.e. which original columns map to which set of one-hot-encoded columns,
and vice versa.
"""
def __init__(self, ohe_prefix_separator: str):
self.ohe_prefix_separator = ohe_prefix_separator
self.__original_to_ohe_attr_map: Optional[
Dict[Attr, List[Attr]]
] = None
self.__ohe_attr_to_original_map: Optional[
Dict[Attr, Attr]
] = None
@staticmethod
def build_encoding_book_keeper_from_ohe_columns(ohe_columns,
ohe_prefix_separator: str) -> 'EncodingBookKeeper':
encoding_book_keeper = EncodingBookKeeper(ohe_prefix_separator=ohe_prefix_separator)
encoding_book_keeper.parse_and_store_one_hot_encoded_columns(ohe_columns=ohe_columns)
return encoding_book_keeper
def __str__(self):
string_representation = f"original_to_ohe:\n"
for original_attribute, encodings in self.__original_to_ohe_attr_map.items():
string_representation += f"\t{original_attribute}: {encodings}\n"
# string_representation += f"ohe_to_original:\n"
# for encoded_attribute, original_attribute in self.__ohe_attr_to_original_map.items():
# string_representation += f"\t{encoded_attribute}: {original_attribute}\n"
return string_representation
def set_original_to_ohe_attr_map(self, original_to_ohe_attr_map: Dict[Attr, List[Attr]]) -> None:
"""
Use this method to initialize an empty EncodingBookKeeper with the given mapping.
"""
self.__original_to_ohe_attr_map = original_to_ohe_attr_map
self.__ohe_attr_to_original_map = {}
for original_attr, ohe_attributes in original_to_ohe_attr_map.items():
for ohe_attr in ohe_attributes:
self.__ohe_attr_to_original_map[ohe_attr] = original_attr
def add_encodings(self, original_to_encoding_map: Dict[Attr, List[Attr]]) -> None:
"""
Use this method if you want to add extra columns to an already existing mapping.
"""
if self.__original_to_ohe_attr_map is None:
self.set_original_to_ohe_attr_map(original_to_encoding_map)
else:
for original_attr, ohe_attributes in original_to_encoding_map.items():
if original_attr in self.get_original_columns():
raise Exception("EncodingBookKeeper already contains encodings for " + str(original_attr))
else:
self.__original_to_ohe_attr_map[original_attr] = ohe_attributes
for ohe_attr in ohe_attributes:
if ohe_attr in self.get_one_hot_encoded_columns():
raise Exception("EncodingBookKeeper already contains an encoding with name "
+ str(ohe_attr))
else:
self.__ohe_attr_to_original_map[ohe_attr] = original_attr
@staticmethod
def parse_one_hot_encoded_columns(ohe_columns, ohe_prefix_separator) -> Dict[Attr, List[Attr]]:
"""
Use this static method to parse a list of one-hot encoding columns
into a mapping of original columns to their one-hot encoding columns.
"""
original_to_ohe_columns: Dict[Attr, List[Attr]] = {}
for column in ohe_columns:
splitted_ohe_column_name = str(column).split(ohe_prefix_separator)
if len(splitted_ohe_column_name) == 1:
# don't split it
original_to_ohe_columns[column] = [column]
elif len(splitted_ohe_column_name) == 2:
original_column = splitted_ohe_column_name[0]
if original_to_ohe_columns.get(original_column, None) is None:
original_to_ohe_columns[original_column] = [column]
else:
original_to_ohe_columns[original_column].append(column)
else:
raise Exception("Handling split of " + str(column) + " using separator "
+ ohe_prefix_separator + " failed; got " + str(len(splitted_ohe_column_name))
+ " piece(s)."
)
return original_to_ohe_columns
def parse_and_store_one_hot_encoded_columns(self, ohe_columns) -> None:
"""
Use this method to initialize an empty EncodingBookKeeper by paringing the given one-encoding columns.
"""
self.set_original_to_ohe_attr_map(
self.parse_one_hot_encoded_columns(ohe_columns, self.ohe_prefix_separator))
def get_original_columns(self) -> KeysView[Attr]:
"""
Get all original columns.
"""
return self.__original_to_ohe_attr_map.keys()
def get_one_hot_encoded_columns(self) -> KeysView[Attr]:
"""
Get all one-hot encoding columns.
"""
return self.__ohe_attr_to_original_map.keys()
def get_encodings(self, original_attr: Attr) -> List[Attr]:
"""
Get the one-hot encoded attributes corresponding to the given original attribute.
"""
return self.__original_to_ohe_attr_map[original_attr]
def get_original(self, encoded_attr: Attr) -> Attr:
"""
Get the original attribute corresponding to the given one-hot encoded attribute.
"""
return self.__ohe_attr_to_original_map[encoded_attr]
| 44.856 | 110 | 0.643838 |
389d17dfa7f337fbe2393027556082977192b4e3 | 74,048 | py | Python | batch/batch/front_end/front_end.py | saponas/hail | bafea6b18247a4279d6ef11015e8e9f3c2b5ecea | [
"MIT"
] | null | null | null | batch/batch/front_end/front_end.py | saponas/hail | bafea6b18247a4279d6ef11015e8e9f3c2b5ecea | [
"MIT"
] | null | null | null | batch/batch/front_end/front_end.py | saponas/hail | bafea6b18247a4279d6ef11015e8e9f3c2b5ecea | [
"MIT"
] | null | null | null | from numbers import Number
import os
import concurrent
import logging
import json
import random
import datetime
import collections
from functools import wraps
import asyncio
import aiohttp
import signal
from aiohttp import web
import aiohttp_session
import pymysql
import google.oauth2.service_account
import google.api_core.exceptions
import humanize
from prometheus_async.aio.web import server_stats # type: ignore
from hailtop.utils import (
time_msecs,
time_msecs_str,
humanize_timedelta_msecs,
request_retry_transient_errors,
run_if_changed,
retry_long_running,
LoggingTimer,
cost_str,
dump_all_stacktraces,
)
from hailtop.batch_client.parse import parse_cpu_in_mcpu, parse_memory_in_bytes, parse_storage_in_bytes
from hailtop.config import get_deploy_config
from hailtop.tls import internal_server_ssl_context
from hailtop.httpx import client_session
from hailtop.hail_logging import AccessLogger
from hailtop import aiotools, dictfix
from gear import (
Database,
setup_aiohttp_session,
rest_authenticated_users_only,
web_authenticated_users_only,
web_authenticated_developers_only,
check_csrf_token,
transaction,
monitor_endpoint,
)
from web_common import setup_aiohttp_jinja2, setup_common_static_routes, render_template, set_message
# import uvloop
from ..utils import (
coalesce,
query_billing_projects,
is_valid_cores_mcpu,
cost_from_msec_mcpu,
cores_mcpu_to_memory_bytes,
batch_only,
)
from ..batch import batch_record_to_dict, job_record_to_dict, cancel_batch_in_db
from ..exceptions import (
BatchUserError,
NonExistentBillingProjectError,
ClosedBillingProjectError,
InvalidBillingLimitError,
BatchOperationAlreadyCompletedError,
)
from ..inst_coll_config import InstanceCollectionConfigs
from ..log_store import LogStore
from ..database import CallError, check_call_procedure
from ..batch_configuration import BATCH_BUCKET_NAME, DEFAULT_NAMESPACE
from ..globals import HTTP_CLIENT_MAX_SIZE, BATCH_FORMAT_VERSION, memory_to_worker_type
from ..spec_writer import SpecWriter
from ..batch_format_version import BatchFormatVersion
from .validate import ValidationError, validate_batch, validate_and_clean_jobs
# uvloop.install()
log = logging.getLogger('batch.front_end')
routes = web.RouteTableDef()
deploy_config = get_deploy_config()
BATCH_JOB_DEFAULT_CPU = os.environ.get('HAIL_BATCH_JOB_DEFAULT_CPU', '1')
BATCH_JOB_DEFAULT_MEMORY = os.environ.get('HAIL_BATCH_JOB_DEFAULT_MEMORY', 'standard')
BATCH_JOB_DEFAULT_STORAGE = os.environ.get('HAIL_BATCH_JOB_DEFAULT_STORAGE', '0Gi')
BATCH_JOB_DEFAULT_PREEMPTIBLE = True
def rest_authenticated_developers_or_auth_only(fun):
@rest_authenticated_users_only
@wraps(fun)
async def wrapped(request, userdata, *args, **kwargs):
if userdata['is_developer'] == 1 or userdata['username'] == 'auth':
return await fun(request, userdata, *args, **kwargs)
raise web.HTTPUnauthorized()
return wrapped
async def _user_can_access(db: Database, batch_id: int, user: str):
record = await db.select_and_fetchone(
'''
SELECT id
FROM batches
LEFT JOIN billing_project_users ON batches.billing_project = billing_project_users.billing_project
WHERE id = %s AND billing_project_users.`user` = %s;
''',
(batch_id, user),
)
return record is not None
def rest_billing_project_users_only(fun):
@rest_authenticated_users_only
@wraps(fun)
async def wrapped(request, userdata, *args, **kwargs):
db = request.app['db']
batch_id = int(request.match_info['batch_id'])
user = userdata['username']
permitted_user = await _user_can_access(db, batch_id, user)
if not permitted_user:
raise web.HTTPNotFound()
return await fun(request, userdata, batch_id, *args, **kwargs)
return wrapped
def web_billing_project_users_only(redirect=True):
def wrap(fun):
@web_authenticated_users_only(redirect)
@wraps(fun)
async def wrapped(request, userdata, *args, **kwargs):
db = request.app['db']
batch_id = int(request.match_info['batch_id'])
user = userdata['username']
permitted_user = await _user_can_access(db, batch_id, user)
if not permitted_user:
raise web.HTTPNotFound()
return await fun(request, userdata, batch_id, *args, **kwargs)
return wrapped
return wrap
@routes.get('/healthcheck')
async def get_healthcheck(request): # pylint: disable=W0613
return web.Response()
async def _handle_ui_error(session, f, *args, **kwargs):
try:
await f(*args, **kwargs)
except KeyError as e:
set_message(session, str(e), 'error')
return True
except BatchOperationAlreadyCompletedError as e:
set_message(session, e.message, e.ui_error_type)
return True
except BatchUserError as e:
set_message(session, e.message, e.ui_error_type)
return True
else:
return False
async def _handle_api_error(f, *args, **kwargs):
try:
await f(*args, **kwargs)
except BatchOperationAlreadyCompletedError as e:
log.info(e.message)
return
except BatchUserError as e:
raise e.http_response()
async def _query_batch_jobs(request, batch_id):
state_query_values = {
'pending': ['Pending'],
'ready': ['Ready'],
'creating': ['Creating'],
'running': ['Running'],
'live': ['Ready', 'Creating', 'Running'],
'cancelled': ['Cancelled'],
'error': ['Error'],
'failed': ['Failed'],
'bad': ['Error', 'Failed'],
'success': ['Success'],
'done': ['Cancelled', 'Error', 'Failed', 'Success'],
}
db = request.app['db']
# batch has already been validated
where_conditions = ['(jobs.batch_id = %s)']
where_args = [batch_id]
last_job_id = request.query.get('last_job_id')
if last_job_id is not None:
last_job_id = int(last_job_id)
where_conditions.append('(jobs.job_id > %s)')
where_args.append(last_job_id)
q = request.query.get('q', '')
terms = q.split()
for t in terms:
if t[0] == '!':
negate = True
t = t[1:]
else:
negate = False
if '=' in t:
k, v = t.split('=', 1)
condition = '''
((jobs.batch_id, jobs.job_id) IN
(SELECT batch_id, job_id FROM job_attributes
WHERE `key` = %s AND `value` = %s))
'''
args = [k, v]
elif t.startswith('has:'):
k = t[4:]
condition = '''
((jobs.batch_id, jobs.job_id) IN
(SELECT batch_id, job_id FROM job_attributes
WHERE `key` = %s))
'''
args = [k]
elif t in state_query_values:
values = state_query_values[t]
condition = ' OR '.join(['(jobs.state = %s)' for v in values])
condition = f'({condition})'
args = values
else:
session = await aiohttp_session.get_session(request)
set_message(session, f'Invalid search term: {t}.', 'error')
return ([], None)
if negate:
condition = f'(NOT {condition})'
where_conditions.append(condition)
where_args.extend(args)
sql = f'''
SELECT jobs.*, batches.user, batches.billing_project, batches.format_version,
job_attributes.value AS name, SUM(`usage` * rate) AS cost
FROM jobs
INNER JOIN batches ON jobs.batch_id = batches.id
LEFT JOIN job_attributes
ON jobs.batch_id = job_attributes.batch_id AND
jobs.job_id = job_attributes.job_id AND
job_attributes.`key` = 'name'
LEFT JOIN aggregated_job_resources
ON jobs.batch_id = aggregated_job_resources.batch_id AND
jobs.job_id = aggregated_job_resources.job_id
LEFT JOIN resources
ON aggregated_job_resources.resource = resources.resource
WHERE {' AND '.join(where_conditions)}
GROUP BY jobs.batch_id, jobs.job_id
ORDER BY jobs.batch_id, jobs.job_id ASC
LIMIT 50;
'''
sql_args = where_args
jobs = [job_record_to_dict(record, record['name']) async for record in db.select_and_fetchall(sql, sql_args)]
if len(jobs) == 50:
last_job_id = jobs[-1]['job_id']
else:
last_job_id = None
return (jobs, last_job_id)
@routes.get('/api/v1alpha/batches/{batch_id}/jobs')
@monitor_endpoint
@rest_billing_project_users_only
async def get_jobs(request, userdata, batch_id): # pylint: disable=unused-argument
db = request.app['db']
record = await db.select_and_fetchone(
'''
SELECT * FROM batches
WHERE id = %s AND NOT deleted;
''',
(batch_id,),
)
if not record:
raise web.HTTPNotFound()
jobs, last_job_id = await _query_batch_jobs(request, batch_id)
resp = {'jobs': jobs}
if last_job_id is not None:
resp['last_job_id'] = last_job_id
return web.json_response(resp)
async def _get_job_log_from_record(app, batch_id, job_id, record):
state = record['state']
ip_address = record['ip_address']
if state == 'Running':
async with aiohttp.ClientSession(raise_for_status=True, timeout=aiohttp.ClientTimeout(total=5)) as session:
try:
url = f'http://{ip_address}:5000' f'/api/v1alpha/batches/{batch_id}/jobs/{job_id}/log'
resp = await request_retry_transient_errors(session, 'GET', url)
return await resp.json()
except aiohttp.ClientResponseError as e:
if e.status == 404:
return None
raise
if state in ('Error', 'Failed', 'Success'):
log_store: LogStore = app['log_store']
batch_format_version = BatchFormatVersion(record['format_version'])
async def _read_log_from_gcs(task):
try:
data = await log_store.read_log_file(batch_format_version, batch_id, job_id, record['attempt_id'], task)
except google.api_core.exceptions.NotFound:
id = (batch_id, job_id)
log.exception(f'missing log file for {id} and task {task}')
data = 'ERROR: could not read log file'
return task, data
spec = json.loads(record['spec'])
tasks = []
has_input_files = batch_format_version.get_spec_has_input_files(spec)
if has_input_files:
tasks.append('input')
tasks.append('main')
has_output_files = batch_format_version.get_spec_has_output_files(spec)
if has_output_files:
tasks.append('output')
return dict(await asyncio.gather(*[_read_log_from_gcs(task) for task in tasks]))
return None
async def _get_job_log(app, batch_id, job_id):
db: Database = app['db']
record = await db.select_and_fetchone(
'''
SELECT jobs.state, jobs.spec, ip_address, format_version, jobs.attempt_id
FROM jobs
INNER JOIN batches
ON jobs.batch_id = batches.id
LEFT JOIN attempts
ON jobs.batch_id = attempts.batch_id AND jobs.job_id = attempts.job_id AND jobs.attempt_id = attempts.attempt_id
LEFT JOIN instances
ON attempts.instance_name = instances.name
WHERE jobs.batch_id = %s AND NOT deleted AND jobs.job_id = %s;
''',
(batch_id, job_id),
)
if not record:
raise web.HTTPNotFound()
return await _get_job_log_from_record(app, batch_id, job_id, record)
async def _get_attributes(app, record):
db: Database = app['db']
batch_id = record['batch_id']
job_id = record['job_id']
format_version = BatchFormatVersion(record['format_version'])
if not format_version.has_full_spec_in_gcs():
spec = json.loads(record['spec'])
return spec.get('attributes')
records = db.select_and_fetchall(
'''
SELECT `key`, `value`
FROM job_attributes
WHERE batch_id = %s AND job_id = %s;
''',
(batch_id, job_id),
)
return {record['key']: record['value'] async for record in records}
async def _get_full_job_spec(app, record):
db: Database = app['db']
log_store: LogStore = app['log_store']
batch_id = record['batch_id']
job_id = record['job_id']
format_version = BatchFormatVersion(record['format_version'])
if not format_version.has_full_spec_in_gcs():
return json.loads(record['spec'])
token, start_job_id = await SpecWriter.get_token_start_id(db, batch_id, job_id)
try:
spec = await log_store.read_spec_file(batch_id, token, start_job_id, job_id)
return json.loads(spec)
except google.api_core.exceptions.NotFound:
id = (batch_id, job_id)
log.exception(f'missing spec file for {id}')
return None
async def _get_full_job_status(app, record):
log_store: LogStore = app['log_store']
batch_id = record['batch_id']
job_id = record['job_id']
attempt_id = record['attempt_id']
state = record['state']
format_version = BatchFormatVersion(record['format_version'])
if state in ('Pending', 'Creating', 'Ready', 'Cancelled'):
return None
if state in ('Error', 'Failed', 'Success'):
if not format_version.has_full_status_in_gcs():
return json.loads(record['status'])
try:
status = await log_store.read_status_file(batch_id, job_id, attempt_id)
return json.loads(status)
except google.api_core.exceptions.NotFound:
id = (batch_id, job_id)
log.exception(f'missing status file for {id}')
return None
assert state == 'Running'
assert record['status'] is None
ip_address = record['ip_address']
async with aiohttp.ClientSession(raise_for_status=True, timeout=aiohttp.ClientTimeout(total=5)) as session:
try:
url = f'http://{ip_address}:5000' f'/api/v1alpha/batches/{batch_id}/jobs/{job_id}/status'
resp = await request_retry_transient_errors(session, 'GET', url)
return await resp.json()
except aiohttp.ClientResponseError as e:
if e.status == 404:
return None
raise
@routes.get('/api/v1alpha/batches/{batch_id}/jobs/{job_id}/log')
@monitor_endpoint
@rest_billing_project_users_only
async def get_job_log(request, userdata, batch_id): # pylint: disable=unused-argument
job_id = int(request.match_info['job_id'])
job_log = await _get_job_log(request.app, batch_id, job_id)
return web.json_response(job_log)
async def _query_batches(request, user, q):
db = request.app['db']
where_conditions = [
'EXISTS (SELECT * FROM billing_project_users WHERE billing_project_users.`user` = %s AND billing_project_users.billing_project = batches.billing_project)',
'NOT deleted',
]
where_args = [user]
last_batch_id = request.query.get('last_batch_id')
if last_batch_id is not None:
last_batch_id = int(last_batch_id)
where_conditions.append('(id < %s)')
where_args.append(last_batch_id)
terms = q.split()
for t in terms:
if t[0] == '!':
negate = True
t = t[1:]
else:
negate = False
if '=' in t:
k, v = t.split('=', 1)
condition = '''
((batches.id) IN
(SELECT batch_id FROM batch_attributes
WHERE `key` = %s AND `value` = %s))
'''
args = [k, v]
elif t.startswith('has:'):
k = t[4:]
condition = '''
((batches.id) IN
(SELECT batch_id FROM batch_attributes
WHERE `key` = %s))
'''
args = [k]
elif t.startswith('user:'):
k = t[5:]
condition = '''
(batches.`user` = %s)
'''
args = [k]
elif t.startswith('billing_project:'):
k = t[16:]
condition = '''
(batches.`billing_project` = %s)
'''
args = [k]
elif t == 'open':
condition = "(`state` = 'open')"
args = []
elif t == 'closed':
condition = "(`state` != 'open')"
args = []
elif t == 'complete':
condition = "(`state` = 'complete')"
args = []
elif t == 'running':
condition = "(`state` = 'running')"
args = []
elif t == 'cancelled':
condition = '(cancelled)'
args = []
elif t == 'failure':
condition = '(n_failed > 0)'
args = []
elif t == 'success':
# need complete because there might be no jobs
condition = "(`state` = 'complete' AND n_succeeded = n_jobs)"
args = []
else:
session = await aiohttp_session.get_session(request)
set_message(session, f'Invalid search term: {t}.', 'error')
return ([], None)
if negate:
condition = f'(NOT {condition})'
where_conditions.append(condition)
where_args.extend(args)
sql = f'''
SELECT batches.*, SUM(`usage` * rate) AS cost
FROM batches
LEFT JOIN aggregated_batch_resources
ON batches.id = aggregated_batch_resources.batch_id
LEFT JOIN resources
ON aggregated_batch_resources.resource = resources.resource
WHERE {' AND '.join(where_conditions)}
GROUP BY batches.id
ORDER BY batches.id DESC
LIMIT 51;
'''
sql_args = where_args
batches = [batch_record_to_dict(batch) async for batch in db.select_and_fetchall(sql, sql_args)]
if len(batches) == 51:
batches.pop()
last_batch_id = batches[-1]['id']
else:
last_batch_id = None
return (batches, last_batch_id)
@routes.get('/api/v1alpha/batches')
@monitor_endpoint
@rest_authenticated_users_only
async def get_batches(request, userdata): # pylint: disable=unused-argument
user = userdata['username']
q = request.query.get('q', f'user:{user}')
batches, last_batch_id = await _query_batches(request, user, q)
body = {'batches': batches}
if last_batch_id is not None:
body['last_batch_id'] = last_batch_id
return web.json_response(body)
def check_service_account_permissions(user, sa):
if sa is None:
return
if user == 'ci':
if sa['name'] in ('ci-agent', 'admin') and DEFAULT_NAMESPACE in ('default', sa['namespace']):
return
elif user == 'test':
if sa['namespace'] == DEFAULT_NAMESPACE and sa['name'] == 'test-batch-sa':
return
raise web.HTTPBadRequest(reason=f'unauthorized service account {(sa["namespace"], sa["name"])} for user {user}')
@routes.post('/api/v1alpha/batches/{batch_id}/jobs/create')
@monitor_endpoint
@rest_authenticated_users_only
async def create_jobs(request, userdata):
app = request.app
db: Database = app['db']
log_store: LogStore = app['log_store']
batch_id = int(request.match_info['batch_id'])
user = userdata['username']
# restrict to what's necessary; in particular, drop the session
# which is sensitive
userdata = {
'username': user,
'gsa_key_secret_name': userdata['gsa_key_secret_name'],
'tokens_secret_name': userdata['tokens_secret_name'],
}
async with LoggingTimer(f'batch {batch_id} create jobs') as timer:
async with timer.step('fetch batch'):
record = await db.select_and_fetchone(
'''
SELECT `state`, format_version FROM batches
WHERE user = %s AND id = %s AND NOT deleted;
''',
(user, batch_id),
)
if not record:
raise web.HTTPNotFound()
if record['state'] != 'open':
raise web.HTTPBadRequest(reason=f'batch {batch_id} is not open')
batch_format_version = BatchFormatVersion(record['format_version'])
async with timer.step('get request json'):
job_specs = await request.json()
async with timer.step('validate job_specs'):
try:
validate_and_clean_jobs(job_specs)
except ValidationError as e:
raise web.HTTPBadRequest(reason=e.reason)
async with timer.step('build db args'):
spec_writer = SpecWriter(log_store, batch_id)
jobs_args = []
job_parents_args = []
job_attributes_args = []
inst_coll_resources = collections.defaultdict(
lambda: {
'n_jobs': 0,
'n_ready_jobs': 0,
'ready_cores_mcpu': 0,
'n_ready_cancellable_jobs': 0,
'ready_cancellable_cores_mcpu': 0,
}
)
prev_job_idx = None
start_job_id = None
for spec in job_specs:
job_id = spec['job_id']
parent_ids = spec.pop('parent_ids', [])
always_run = spec.pop('always_run', False)
if batch_format_version.has_full_spec_in_gcs():
attributes = spec.pop('attributes', None)
else:
attributes = spec.get('attributes')
id = (batch_id, job_id)
if start_job_id is None:
start_job_id = job_id
if batch_format_version.has_full_spec_in_gcs() and prev_job_idx:
if job_id != prev_job_idx + 1:
raise web.HTTPBadRequest(
reason=f'noncontiguous job ids found in the spec: {prev_job_idx} -> {job_id}'
)
prev_job_idx = job_id
resources = spec.get('resources')
if not resources:
resources = {}
spec['resources'] = resources
worker_type = None
machine_type = resources.get('machine_type')
preemptible = resources.get('preemptible', BATCH_JOB_DEFAULT_PREEMPTIBLE)
if machine_type and ('cpu' in resources or 'memory' in resources):
raise web.HTTPBadRequest(reason='cannot specify cpu and memory with machine_type')
if machine_type is None:
if 'cpu' not in resources:
resources['cpu'] = BATCH_JOB_DEFAULT_CPU
resources['req_cpu'] = resources['cpu']
del resources['cpu']
req_cores_mcpu = parse_cpu_in_mcpu(resources['req_cpu'])
if not is_valid_cores_mcpu(req_cores_mcpu):
raise web.HTTPBadRequest(
reason=f'bad resource request for job {id}: '
f'cpu must be a power of two with a min of 0.25; '
f'found {resources["req_cpu"]}.'
)
if 'memory' not in resources:
resources['memory'] = BATCH_JOB_DEFAULT_MEMORY
resources['req_memory'] = resources['memory']
del resources['memory']
req_memory = resources['req_memory']
if req_memory in memory_to_worker_type:
worker_type = memory_to_worker_type[req_memory]
req_memory_bytes = cores_mcpu_to_memory_bytes(req_cores_mcpu, worker_type)
else:
req_memory_bytes = parse_memory_in_bytes(req_memory)
else:
req_cores_mcpu = None
req_memory_bytes = None
if 'storage' not in resources:
resources['storage'] = BATCH_JOB_DEFAULT_STORAGE
resources['req_storage'] = resources['storage']
del resources['storage']
req_storage_bytes = parse_storage_in_bytes(resources['req_storage'])
if req_storage_bytes is None:
raise web.HTTPBadRequest(
reason=f'bad resource request for job {id}: '
f'storage must be convertable to bytes; '
f'found {resources["req_storage"]}'
)
inst_coll_configs: InstanceCollectionConfigs = app['inst_coll_configs']
result, exc = inst_coll_configs.select_inst_coll(
machine_type, preemptible, worker_type, req_cores_mcpu, req_memory_bytes, req_storage_bytes
)
if exc:
raise web.HTTPBadRequest(reason=exc.message)
if result is None:
raise web.HTTPBadRequest(
reason=f'resource requests for job {id} are unsatisfiable: '
f'cpu={resources["req_cpu"]}, '
f'memory={resources["req_memory"]}, '
f'storage={resources["req_storage"]}, '
f'preemptible={preemptible}, '
f'machine_type={machine_type}'
)
inst_coll_name, cores_mcpu, memory_bytes, storage_gib = result
resources['cores_mcpu'] = cores_mcpu
resources['memory_bytes'] = memory_bytes
resources['storage_gib'] = storage_gib
resources['preemptible'] = preemptible
secrets = spec.get('secrets')
if not secrets:
secrets = []
if len(secrets) != 0 and user != 'ci':
secrets = [(secret["namespace"], secret["name"]) for secret in secrets]
raise web.HTTPBadRequest(reason=f'unauthorized secret {secrets} for user {user}')
for secret in secrets:
if user != 'ci':
raise web.HTTPBadRequest(reason=f'unauthorized secret {(secret["namespace"], secret["name"])}')
spec['secrets'] = secrets
secrets.append(
{
'namespace': DEFAULT_NAMESPACE,
'name': userdata['gsa_key_secret_name'],
'mount_path': '/gsa-key',
'mount_in_copy': True,
}
)
env = spec.get('env')
if not env:
env = []
spec['env'] = env
assert isinstance(spec['env'], list)
if all(envvar['name'] != 'GOOGLE_APPLICATION_CREDENTIALS' for envvar in spec['env']):
spec['env'].append({'name': 'GOOGLE_APPLICATION_CREDENTIALS', 'value': '/gsa-key/key.json'})
if spec.get('mount_tokens', False):
secrets.append(
{
'namespace': DEFAULT_NAMESPACE,
'name': userdata['tokens_secret_name'],
'mount_path': '/user-tokens',
'mount_in_copy': False,
}
)
secrets.append(
{
'namespace': DEFAULT_NAMESPACE,
'name': 'gce-deploy-config',
'mount_path': '/deploy-config',
'mount_in_copy': False,
}
)
secrets.append(
{
'namespace': DEFAULT_NAMESPACE,
'name': 'ssl-config-batch-user-code',
'mount_path': '/ssl-config',
'mount_in_copy': False,
}
)
sa = spec.get('service_account')
check_service_account_permissions(user, sa)
icr = inst_coll_resources[inst_coll_name]
icr['n_jobs'] += 1
if len(parent_ids) == 0:
state = 'Ready'
icr['n_ready_jobs'] += 1
icr['ready_cores_mcpu'] += cores_mcpu
if not always_run:
icr['n_ready_cancellable_jobs'] += 1
icr['ready_cancellable_cores_mcpu'] += cores_mcpu
else:
state = 'Pending'
network = spec.get('network')
if user != 'ci' and not (network is None or network == 'public'):
raise web.HTTPBadRequest(reason=f'unauthorized network {network}')
spec_writer.add(json.dumps(spec))
db_spec = batch_format_version.db_spec(spec)
jobs_args.append(
(
batch_id,
job_id,
state,
json.dumps(db_spec),
always_run,
cores_mcpu,
len(parent_ids),
inst_coll_name,
)
)
for parent_id in parent_ids:
job_parents_args.append((batch_id, job_id, parent_id))
if attributes:
for k, v in attributes.items():
job_attributes_args.append((batch_id, job_id, k, v))
if batch_format_version.has_full_spec_in_gcs():
async with timer.step('write spec to gcs'):
await spec_writer.write()
rand_token = random.randint(0, app['n_tokens'] - 1)
async with timer.step('insert jobs'):
@transaction(db)
async def insert(tx):
try:
await tx.execute_many(
'''
INSERT INTO jobs (batch_id, job_id, state, spec, always_run, cores_mcpu, n_pending_parents, inst_coll)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s);
''',
jobs_args,
)
except pymysql.err.IntegrityError as err:
# 1062 ER_DUP_ENTRY https://dev.mysql.com/doc/refman/5.7/en/server-error-reference.html#error_er_dup_entry
if err.args[0] == 1062:
log.info(f'bunch containing job {(batch_id, jobs_args[0][1])} already inserted ({err})')
return
raise
try:
await tx.execute_many(
'''
INSERT INTO `job_parents` (batch_id, job_id, parent_id)
VALUES (%s, %s, %s);
''',
job_parents_args,
)
except pymysql.err.IntegrityError as err:
# 1062 ER_DUP_ENTRY https://dev.mysql.com/doc/refman/5.7/en/server-error-reference.html#error_er_dup_entry
if err.args[0] == 1062:
raise web.HTTPBadRequest(text=f'bunch contains job with duplicated parents ({err})')
raise
await tx.execute_many(
'''
INSERT INTO `job_attributes` (batch_id, job_id, `key`, `value`)
VALUES (%s, %s, %s, %s);
''',
job_attributes_args,
)
for inst_coll, resources in inst_coll_resources.items():
n_jobs = resources['n_jobs']
n_ready_jobs = resources['n_ready_jobs']
ready_cores_mcpu = resources['ready_cores_mcpu']
n_ready_cancellable_jobs = resources['n_ready_cancellable_jobs']
ready_cancellable_cores_mcpu = resources['ready_cancellable_cores_mcpu']
await tx.execute_update(
'''
INSERT INTO batches_inst_coll_staging (batch_id, inst_coll, token, n_jobs, n_ready_jobs, ready_cores_mcpu)
VALUES (%s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
n_jobs = n_jobs + %s,
n_ready_jobs = n_ready_jobs + %s,
ready_cores_mcpu = ready_cores_mcpu + %s;
''',
(
batch_id,
inst_coll,
rand_token,
n_jobs,
n_ready_jobs,
ready_cores_mcpu,
n_jobs,
n_ready_jobs,
ready_cores_mcpu,
),
)
await tx.execute_update(
'''
INSERT INTO batch_inst_coll_cancellable_resources (batch_id, inst_coll, token, n_ready_cancellable_jobs, ready_cancellable_cores_mcpu)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
n_ready_cancellable_jobs = n_ready_cancellable_jobs + %s,
ready_cancellable_cores_mcpu = ready_cancellable_cores_mcpu + %s;
''',
(
batch_id,
inst_coll,
rand_token,
n_ready_cancellable_jobs,
ready_cancellable_cores_mcpu,
n_ready_cancellable_jobs,
ready_cancellable_cores_mcpu,
),
)
if batch_format_version.has_full_spec_in_gcs():
await tx.execute_update(
'''
INSERT INTO batch_bunches (batch_id, token, start_job_id)
VALUES (%s, %s, %s);
''',
(batch_id, spec_writer.token, start_job_id),
)
try:
await insert() # pylint: disable=no-value-for-parameter
except aiohttp.web.HTTPException:
raise
except Exception as err:
raise ValueError(
f'encountered exception while inserting a bunch'
f'jobs_args={json.dumps(jobs_args)}'
f'job_parents_args={json.dumps(job_parents_args)}'
) from err
return web.Response()
@routes.post('/api/v1alpha/batches/create')
@monitor_endpoint
@rest_authenticated_users_only
async def create_batch(request, userdata):
app = request.app
db: Database = app['db']
batch_spec = await request.json()
try:
validate_batch(batch_spec)
except ValidationError as e:
raise web.HTTPBadRequest(reason=e.reason)
user = userdata['username']
# restrict to what's necessary; in particular, drop the session
# which is sensitive
userdata = {
'username': user,
'gsa_key_secret_name': userdata['gsa_key_secret_name'],
'tokens_secret_name': userdata['tokens_secret_name'],
}
billing_project = batch_spec['billing_project']
token = batch_spec['token']
attributes = batch_spec.get('attributes')
@transaction(db)
async def insert(tx):
billing_projects = await query_billing_projects(tx, user=user, billing_project=billing_project)
if len(billing_projects) != 1:
assert len(billing_projects) == 0
raise web.HTTPForbidden(reason=f'unknown billing project {billing_project}')
assert billing_projects[0]['status'] is not None
if billing_projects[0]['status'] in {'closed', 'deleted'}:
raise web.HTTPForbidden(reason=f'Billing project {billing_project} is closed or deleted.')
bp = billing_projects[0]
limit = bp['limit']
accrued_cost = bp['accrued_cost']
if limit is not None and accrued_cost >= limit:
raise web.HTTPForbidden(
reason=f'billing project {billing_project} has exceeded the budget; accrued={cost_str(accrued_cost)} limit={cost_str(limit)}'
)
maybe_batch = await tx.execute_and_fetchone(
'''
SELECT * FROM batches
WHERE token = %s AND user = %s FOR UPDATE;
''',
(token, user),
)
if maybe_batch is not None:
return maybe_batch['id']
now = time_msecs()
id = await tx.execute_insertone(
'''
INSERT INTO batches (userdata, user, billing_project, attributes, callback, n_jobs, time_created, token, state, format_version, cancel_after_n_failures)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
''',
(
json.dumps(userdata),
user,
billing_project,
json.dumps(attributes),
batch_spec.get('callback'),
batch_spec['n_jobs'],
now,
token,
'open',
BATCH_FORMAT_VERSION,
batch_spec.get('cancel_after_n_failures'),
),
)
if attributes:
await tx.execute_many(
'''
INSERT INTO `batch_attributes` (batch_id, `key`, `value`)
VALUES (%s, %s, %s)
''',
[(id, k, v) for k, v in attributes.items()],
)
return id
id = await insert() # pylint: disable=no-value-for-parameter
return web.json_response({'id': id})
async def _get_batch(app, batch_id):
db: Database = app['db']
record = await db.select_and_fetchone(
'''
SELECT batches.*, SUM(`usage` * rate) AS cost FROM batches
LEFT JOIN aggregated_batch_resources
ON batches.id = aggregated_batch_resources.batch_id
LEFT JOIN resources
ON aggregated_batch_resources.resource = resources.resource
WHERE id = %s AND NOT deleted
GROUP BY batches.id;
''',
(batch_id),
)
if not record:
raise web.HTTPNotFound()
return batch_record_to_dict(record)
async def _cancel_batch(app, batch_id):
await cancel_batch_in_db(app['db'], batch_id)
app['cancel_batch_state_changed'].set()
return web.Response()
async def _delete_batch(app, batch_id):
db: Database = app['db']
record = await db.select_and_fetchone(
'''
SELECT `state` FROM batches
WHERE id = %s AND NOT deleted;
''',
(batch_id,),
)
if not record:
raise web.HTTPNotFound()
await db.just_execute('CALL cancel_batch(%s);', (batch_id,))
await db.execute_update('UPDATE batches SET deleted = 1 WHERE id = %s;', (batch_id,))
if record['state'] == 'running':
app['delete_batch_state_changed'].set()
@routes.get('/api/v1alpha/batches/{batch_id}')
@monitor_endpoint
@rest_billing_project_users_only
async def get_batch(request, userdata, batch_id): # pylint: disable=unused-argument
return web.json_response(await _get_batch(request.app, batch_id))
@routes.patch('/api/v1alpha/batches/{batch_id}/cancel')
@monitor_endpoint
@rest_billing_project_users_only
async def cancel_batch(request, userdata, batch_id): # pylint: disable=unused-argument
await _handle_api_error(_cancel_batch, request.app, batch_id)
return web.Response()
@routes.patch('/api/v1alpha/batches/{batch_id}/close')
@monitor_endpoint
@rest_authenticated_users_only
async def close_batch(request, userdata):
batch_id = int(request.match_info['batch_id'])
user = userdata['username']
app = request.app
db: Database = app['db']
record = await db.select_and_fetchone(
'''
SELECT 1 FROM batches
WHERE user = %s AND id = %s AND NOT deleted;
''',
(user, batch_id),
)
if not record:
raise web.HTTPNotFound()
try:
now = time_msecs()
await check_call_procedure(db, 'CALL close_batch(%s, %s);', (batch_id, now))
except CallError as e:
# 2: wrong number of jobs
if e.rv['rc'] == 2:
expected_n_jobs = e.rv['expected_n_jobs']
actual_n_jobs = e.rv['actual_n_jobs']
raise web.HTTPBadRequest(reason=f'wrong number of jobs: expected {expected_n_jobs}, actual {actual_n_jobs}')
raise
async with client_session() as session:
await request_retry_transient_errors(
session,
'PATCH',
deploy_config.url('batch-driver', f'/api/v1alpha/batches/{user}/{batch_id}/close'),
headers=app['batch_headers'],
)
return web.Response()
@routes.delete('/api/v1alpha/batches/{batch_id}')
@monitor_endpoint
@rest_billing_project_users_only
async def delete_batch(request, userdata, batch_id): # pylint: disable=unused-argument
await _delete_batch(request.app, batch_id)
return web.Response()
@routes.get('/batches/{batch_id}')
@monitor_endpoint
@web_billing_project_users_only()
async def ui_batch(request, userdata, batch_id):
app = request.app
batch = await _get_batch(app, batch_id)
jobs, last_job_id = await _query_batch_jobs(request, batch_id)
for j in jobs:
j['duration'] = humanize_timedelta_msecs(j['duration'])
j['cost'] = cost_str(j['cost'])
batch['jobs'] = jobs
batch['cost'] = cost_str(batch['cost'])
page_context = {'batch': batch, 'q': request.query.get('q'), 'last_job_id': last_job_id}
return await render_template('batch', request, userdata, 'batch.html', page_context)
@routes.post('/batches/{batch_id}/cancel')
@monitor_endpoint
@check_csrf_token
@web_billing_project_users_only(redirect=False)
async def ui_cancel_batch(request, userdata, batch_id): # pylint: disable=unused-argument
post = await request.post()
q = post.get('q')
params = {}
if q is not None:
params['q'] = q
session = await aiohttp_session.get_session(request)
errored = await _handle_ui_error(session, _cancel_batch, request.app, batch_id)
if not errored:
set_message(session, f'Batch {batch_id} cancelled.', 'info')
location = request.app.router['batches'].url_for().with_query(params)
raise web.HTTPFound(location=location)
@routes.post('/batches/{batch_id}/delete')
@monitor_endpoint
@check_csrf_token
@web_billing_project_users_only(redirect=False)
async def ui_delete_batch(request, userdata, batch_id): # pylint: disable=unused-argument
post = await request.post()
q = post.get('q')
params = {}
if q is not None:
params['q'] = q
await _delete_batch(request.app, batch_id)
session = await aiohttp_session.get_session(request)
set_message(session, f'Batch {batch_id} deleted.', 'info')
location = request.app.router['batches'].url_for().with_query(params)
raise web.HTTPFound(location=location)
@routes.get('/batches', name='batches')
@monitor_endpoint
@web_authenticated_users_only()
async def ui_batches(request, userdata):
user = userdata['username']
q = request.query.get('q', f'user:{user}')
batches, last_batch_id = await _query_batches(request, user, q)
for batch in batches:
batch['cost'] = cost_str(batch['cost'])
page_context = {'batches': batches, 'q': q, 'last_batch_id': last_batch_id}
return await render_template('batch', request, userdata, 'batches.html', page_context)
async def _get_job(app, batch_id, job_id):
db: Database = app['db']
record = await db.select_and_fetchone(
'''
SELECT jobs.*, user, billing_project, ip_address, format_version, SUM(`usage` * rate) AS cost
FROM jobs
INNER JOIN batches
ON jobs.batch_id = batches.id
LEFT JOIN attempts
ON jobs.batch_id = attempts.batch_id AND jobs.job_id = attempts.job_id AND jobs.attempt_id = attempts.attempt_id
LEFT JOIN instances
ON attempts.instance_name = instances.name
LEFT JOIN aggregated_job_resources
ON jobs.batch_id = aggregated_job_resources.batch_id AND
jobs.job_id = aggregated_job_resources.job_id
LEFT JOIN resources
ON aggregated_job_resources.resource = resources.resource
WHERE jobs.batch_id = %s AND NOT deleted AND jobs.job_id = %s
GROUP BY jobs.batch_id, jobs.job_id;
''',
(batch_id, job_id),
)
if not record:
raise web.HTTPNotFound()
full_status, full_spec, attributes = await asyncio.gather(
_get_full_job_status(app, record), _get_full_job_spec(app, record), _get_attributes(app, record)
)
job = job_record_to_dict(record, attributes.get('name'))
job['status'] = full_status
job['spec'] = full_spec
if attributes:
job['attributes'] = attributes
return job
async def _get_attempts(app, batch_id, job_id):
db: Database = app['db']
attempts = db.select_and_fetchall(
'''
SELECT attempts.*
FROM jobs
INNER JOIN batches ON jobs.batch_id = batches.id
LEFT JOIN attempts ON jobs.batch_id = attempts.batch_id and jobs.job_id = attempts.job_id
WHERE jobs.batch_id = %s AND NOT deleted AND jobs.job_id = %s;
''',
(batch_id, job_id),
)
attempts = [attempt async for attempt in attempts]
if len(attempts) == 0:
raise web.HTTPNotFound()
if len(attempts) == 1 and attempts[0]['attempt_id'] is None:
return None
attempts.sort(key=lambda x: x['start_time'])
for attempt in attempts:
start_time = attempt['start_time']
if start_time is not None:
attempt['start_time'] = time_msecs_str(start_time)
else:
del attempt['start_time']
end_time = attempt['end_time']
if end_time is not None:
attempt['end_time'] = time_msecs_str(end_time)
else:
del attempt['end_time']
if start_time is not None:
# elapsed time if attempt is still running
if end_time is None:
end_time = time_msecs()
duration_msecs = max(end_time - start_time, 0)
attempt['duration'] = humanize_timedelta_msecs(duration_msecs)
return attempts
@routes.get('/api/v1alpha/batches/{batch_id}/jobs/{job_id}/attempts')
@monitor_endpoint
@rest_billing_project_users_only
async def get_attempts(request, userdata, batch_id): # pylint: disable=unused-argument
job_id = int(request.match_info['job_id'])
attempts = await _get_attempts(request.app, batch_id, job_id)
return web.json_response(attempts)
@routes.get('/api/v1alpha/batches/{batch_id}/jobs/{job_id}')
@monitor_endpoint
@rest_billing_project_users_only
async def get_job(request, userdata, batch_id): # pylint: disable=unused-argument
job_id = int(request.match_info['job_id'])
status = await _get_job(request.app, batch_id, job_id)
return web.json_response(status)
@routes.get('/batches/{batch_id}/jobs/{job_id}')
@monitor_endpoint
@web_billing_project_users_only()
async def ui_get_job(request, userdata, batch_id):
app = request.app
job_id = int(request.match_info['job_id'])
job, attempts, job_log = await asyncio.gather(
_get_job(app, batch_id, job_id), _get_attempts(app, batch_id, job_id), _get_job_log(app, batch_id, job_id)
)
job['duration'] = humanize_timedelta_msecs(job['duration'])
job['cost'] = cost_str(job['cost'])
job_status = job['status']
container_status_spec = dictfix.NoneOr(
{
'name': str,
'timing': {
'pulling': dictfix.NoneOr({'duration': dictfix.NoneOr(Number)}),
'running': dictfix.NoneOr({'duration': dictfix.NoneOr(Number)}),
},
'short_error': dictfix.NoneOr(str),
'container_status': {'out_of_memory': dictfix.NoneOr(bool)},
'state': str,
}
)
job_status_spec = {
'container_statuses': {
'input': container_status_spec,
'main': container_status_spec,
'output': container_status_spec,
}
}
job_status = dictfix.dictfix(job_status, job_status_spec)
container_statuses = job_status['container_statuses']
step_statuses = [container_statuses['input'], container_statuses['main'], container_statuses['output']]
for status in step_statuses:
# backwards compatibility
if status and status['short_error'] is None and status['container_status']['out_of_memory']:
status['short_error'] = 'out of memory'
job_specification = job['spec']
if job_specification:
if 'process' in job_specification:
process_specification = job_specification['process']
process_type = process_specification['type']
assert process_specification['type'] in {'docker', 'jvm'}
job_specification['image'] = process_specification['image'] if process_type == 'docker' else '[jvm]'
job_specification['command'] = process_specification['command']
job_specification = dictfix.dictfix(
job_specification, dictfix.NoneOr({'image': str, 'command': list, 'resources': dict(), 'env': list})
)
resources = job_specification['resources']
if 'memory_bytes' in resources:
resources['actual_memory'] = humanize.naturalsize(resources['memory_bytes'], binary=True)
del resources['memory_bytes']
if 'storage_gib' in resources:
resources['actual_storage'] = humanize.naturalsize(resources['storage_gib'] * 1024 ** 3, binary=True)
del resources['storage_gib']
if 'cores_mcpu' in resources:
resources['actual_cpu'] = resources['cores_mcpu'] / 1000
del resources['cores_mcpu']
page_context = {
'batch_id': batch_id,
'job_id': job_id,
'job': job,
'job_log': job_log,
'attempts': attempts,
'step_statuses': step_statuses,
'job_specification': job_specification,
'job_status_str': json.dumps(job, indent=2),
}
return await render_template('batch', request, userdata, 'job.html', page_context)
@routes.get('/billing_limits')
@monitor_endpoint
@web_authenticated_users_only()
async def ui_get_billing_limits(request, userdata):
app = request.app
db: Database = app['db']
if not userdata['is_developer']:
user = userdata['username']
else:
user = None
billing_projects = await query_billing_projects(db, user=user)
page_context = {'billing_projects': billing_projects, 'is_developer': userdata['is_developer']}
return await render_template('batch', request, userdata, 'billing_limits.html', page_context)
def _parse_billing_limit(limit):
if limit == 'None' or limit is None:
limit = None
else:
try:
limit = float(limit)
assert limit >= 0
except Exception as e:
raise InvalidBillingLimitError(limit) from e
return limit
async def _edit_billing_limit(db, billing_project, limit):
limit = _parse_billing_limit(limit)
@transaction(db)
async def insert(tx):
row = await tx.execute_and_fetchone(
'''
SELECT billing_projects.name as billing_project,
billing_projects.`status` as `status`
FROM billing_projects
WHERE billing_projects.name = %s AND billing_projects.`status` != 'deleted'
FOR UPDATE;
''',
(billing_project,),
)
if row is None:
raise NonExistentBillingProjectError(billing_project)
if row['status'] == 'closed':
raise ClosedBillingProjectError(billing_project)
await tx.execute_update(
'''
UPDATE billing_projects SET `limit` = %s WHERE name = %s;
''',
(limit, billing_project),
)
await insert() # pylint: disable=no-value-for-parameter
@routes.post('/api/v1alpha/billing_limits/{billing_project}/edit')
@monitor_endpoint
@rest_authenticated_developers_or_auth_only
async def post_edit_billing_limits(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
data = await request.json()
limit = data['limit']
await _handle_api_error(_edit_billing_limit, db, billing_project, limit)
return web.json_response({'billing_project': billing_project, 'limit': limit})
@routes.post('/billing_limits/{billing_project}/edit')
@monitor_endpoint
@check_csrf_token
@web_authenticated_developers_only(redirect=False)
async def post_edit_billing_limits_ui(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
post = await request.post()
limit = post['limit']
session = await aiohttp_session.get_session(request)
errored = await _handle_ui_error(session, _edit_billing_limit, db, billing_project, limit)
if not errored:
set_message(session, f'Modified limit {limit} for billing project {billing_project}.', 'info')
return web.HTTPFound(deploy_config.external_url('batch', '/billing_limits'))
async def _query_billing(request):
db: Database = request.app['db']
date_format = '%m/%d/%Y'
default_start = datetime.datetime.now().replace(day=1)
default_start = datetime.datetime.strftime(default_start, date_format)
default_end = datetime.datetime.now()
default_end = datetime.datetime.strftime(default_end, date_format)
async def parse_error(msg):
session = await aiohttp_session.get_session(request)
set_message(session, msg, 'error')
return ([], default_start, default_end)
start_query = request.query.get('start', default_start)
try:
start = datetime.datetime.strptime(start_query, date_format)
start = start.timestamp() * 1000
except ValueError:
return await parse_error(f"Invalid value for start '{start_query}'; must be in the format of MM/DD/YYYY.")
end_query = request.query.get('end', default_end)
try:
end = datetime.datetime.strptime(end_query, date_format)
end = (end + datetime.timedelta(days=1)).timestamp() * 1000
except ValueError:
return await parse_error(f"Invalid value for end '{end_query}'; must be in the format of MM/DD/YYYY.")
if start > end:
return await parse_error('Invalid search; start must be earlier than end.')
sql = '''
SELECT
billing_project,
`user`,
CAST(SUM(IF(format_version < 3, batches.msec_mcpu, 0)) AS SIGNED) as msec_mcpu,
SUM(IF(format_version >= 3, `usage` * rate, NULL)) as cost
FROM batches
LEFT JOIN aggregated_batch_resources
ON aggregated_batch_resources.batch_id = batches.id
LEFT JOIN resources
ON resources.resource = aggregated_batch_resources.resource
LEFT JOIN billing_projects
ON billing_projects.name = batches.billing_project
WHERE `time_completed` >= %s AND
`time_completed` <= %s AND
billing_projects.`status` != 'deleted'
GROUP BY billing_project, `user`;
'''
sql_args = (start, end)
def billing_record_to_dict(record):
cost_msec_mcpu = cost_from_msec_mcpu(record['msec_mcpu'])
cost_resources = record['cost']
record['cost'] = coalesce(cost_msec_mcpu, 0) + coalesce(cost_resources, 0)
del record['msec_mcpu']
return record
billing = [billing_record_to_dict(record) async for record in db.select_and_fetchall(sql, sql_args)]
return (billing, start_query, end_query)
@routes.get('/billing')
@monitor_endpoint
@web_authenticated_developers_only()
async def ui_get_billing(request, userdata):
billing, start, end = await _query_billing(request)
billing_by_user = {}
billing_by_project = {}
for record in billing:
billing_project = record['billing_project']
user = record['user']
cost = record['cost']
billing_by_user[user] = billing_by_user.get(user, 0) + cost
billing_by_project[billing_project] = billing_by_project.get(billing_project, 0) + cost
billing_by_project = [
{'billing_project': billing_project, 'cost': cost_str(cost)}
for billing_project, cost in billing_by_project.items()
]
billing_by_project.sort(key=lambda record: record['billing_project'])
billing_by_user = [{'user': user, 'cost': cost_str(cost)} for user, cost in billing_by_user.items()]
billing_by_user.sort(key=lambda record: record['user'])
billing_by_project_user = [
{'billing_project': record['billing_project'], 'user': record['user'], 'cost': cost_str(record['cost'])}
for record in billing
]
billing_by_project_user.sort(key=lambda record: (record['billing_project'], record['user']))
page_context = {
'billing_by_project': billing_by_project,
'billing_by_user': billing_by_user,
'billing_by_project_user': billing_by_project_user,
'start': start,
'end': end,
}
return await render_template('batch', request, userdata, 'billing.html', page_context)
@routes.get('/billing_projects')
@monitor_endpoint
@web_authenticated_developers_only()
async def ui_get_billing_projects(request, userdata):
db: Database = request.app['db']
billing_projects = await query_billing_projects(db)
page_context = {
'billing_projects': [{**p, 'size': len(p['users'])} for p in billing_projects if p['status'] == 'open'],
'closed_projects': [p for p in billing_projects if p['status'] == 'closed'],
}
return await render_template('batch', request, userdata, 'billing_projects.html', page_context)
@routes.get('/api/v1alpha/billing_projects')
@monitor_endpoint
@rest_authenticated_users_only
async def get_billing_projects(request, userdata):
db: Database = request.app['db']
if not userdata['is_developer'] and userdata['username'] != 'auth':
user = userdata['username']
else:
user = None
billing_projects = await query_billing_projects(db, user=user)
return web.json_response(data=billing_projects)
@routes.get('/api/v1alpha/billing_projects/{billing_project}')
@monitor_endpoint
@rest_authenticated_users_only
async def get_billing_project(request, userdata):
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
if not userdata['is_developer'] and userdata['username'] != 'auth':
user = userdata['username']
else:
user = None
billing_projects = await query_billing_projects(db, user=user, billing_project=billing_project)
if not billing_projects:
raise web.HTTPForbidden(reason=f'unknown billing project {billing_project}')
assert len(billing_projects) == 1
return web.json_response(data=billing_projects[0])
async def _remove_user_from_billing_project(db, billing_project, user):
@transaction(db)
async def delete(tx):
row = await tx.execute_and_fetchone(
'''
SELECT billing_projects.name as billing_project,
billing_projects.`status` as `status`,
user FROM billing_projects
LEFT JOIN (SELECT * FROM billing_project_users
WHERE billing_project = %s AND user = %s FOR UPDATE) AS t
ON billing_projects.name = t.billing_project
WHERE billing_projects.name = %s;
''',
(billing_project, user, billing_project),
)
if not row:
raise NonExistentBillingProjectError(billing_project)
assert row['billing_project'] == billing_project
if row['status'] in {'closed', 'deleted'}:
raise BatchUserError(
f'Billing project {billing_project} has been closed or deleted and cannot be modified.', 'error'
)
if row['user'] is None:
raise BatchOperationAlreadyCompletedError(
f'User {user} is not in billing project {billing_project}.', 'info'
)
await tx.just_execute(
'''
DELETE FROM billing_project_users
WHERE billing_project = %s AND user = %s;
''',
(billing_project, user),
)
await delete() # pylint: disable=no-value-for-parameter
@routes.post('/billing_projects/{billing_project}/users/{user}/remove')
@monitor_endpoint
@check_csrf_token
@web_authenticated_developers_only(redirect=False)
async def post_billing_projects_remove_user(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
user = request.match_info['user']
session = await aiohttp_session.get_session(request)
errored = await _handle_ui_error(session, _remove_user_from_billing_project, db, billing_project, user)
if not errored:
set_message(session, f'Removed user {user} from billing project {billing_project}.', 'info')
return web.HTTPFound(deploy_config.external_url('batch', '/billing_projects'))
@routes.post('/api/v1alpha/billing_projects/{billing_project}/users/{user}/remove')
@monitor_endpoint
@rest_authenticated_developers_or_auth_only
async def api_get_billing_projects_remove_user(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
user = request.match_info['user']
await _handle_api_error(_remove_user_from_billing_project, db, billing_project, user)
return web.json_response({'billing_project': billing_project, 'user': user})
async def _add_user_to_billing_project(db, billing_project, user):
@transaction(db)
async def insert(tx):
row = await tx.execute_and_fetchone(
'''
SELECT billing_projects.name as billing_project,
billing_projects.`status` as `status`,
user
FROM billing_projects
LEFT JOIN (SELECT * FROM billing_project_users
WHERE billing_project = %s AND user = %s FOR UPDATE) AS t
ON billing_projects.name = t.billing_project
WHERE billing_projects.name = %s AND billing_projects.`status` != 'deleted' LOCK IN SHARE MODE;
''',
(billing_project, user, billing_project),
)
if row is None:
raise NonExistentBillingProjectError(billing_project)
if row['status'] == 'closed':
raise ClosedBillingProjectError(billing_project)
if row['user'] is not None:
raise BatchOperationAlreadyCompletedError(
f'User {user} is already member of billing project {billing_project}.', 'info'
)
await tx.execute_insertone(
'''
INSERT INTO billing_project_users(billing_project, user)
VALUES (%s, %s);
''',
(billing_project, user),
)
await insert() # pylint: disable=no-value-for-parameter
@routes.post('/billing_projects/{billing_project}/users/add')
@monitor_endpoint
@check_csrf_token
@web_authenticated_developers_only(redirect=False)
async def post_billing_projects_add_user(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
post = await request.post()
user = post['user']
billing_project = request.match_info['billing_project']
session = await aiohttp_session.get_session(request)
errored = await _handle_ui_error(session, _add_user_to_billing_project, db, billing_project, user)
if not errored:
set_message(session, f'Added user {user} to billing project {billing_project}.', 'info')
return web.HTTPFound(deploy_config.external_url('batch', '/billing_projects'))
@routes.post('/api/v1alpha/billing_projects/{billing_project}/users/{user}/add')
@monitor_endpoint
@rest_authenticated_developers_or_auth_only
async def api_billing_projects_add_user(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
user = request.match_info['user']
billing_project = request.match_info['billing_project']
await _handle_api_error(_add_user_to_billing_project, db, billing_project, user)
return web.json_response({'billing_project': billing_project, 'user': user})
async def _create_billing_project(db, billing_project):
@transaction(db)
async def insert(tx):
row = await tx.execute_and_fetchone(
'''
SELECT `status` FROM billing_projects
WHERE name = %s
FOR UPDATE;
''',
(billing_project),
)
if row is not None:
raise BatchOperationAlreadyCompletedError(f'Billing project {billing_project} already exists.', 'info')
await tx.execute_insertone(
'''
INSERT INTO billing_projects(name)
VALUES (%s);
''',
(billing_project,),
)
await insert() # pylint: disable=no-value-for-parameter
@routes.post('/billing_projects/create')
@monitor_endpoint
@check_csrf_token
@web_authenticated_developers_only(redirect=False)
async def post_create_billing_projects(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
post = await request.post()
billing_project = post['billing_project']
session = await aiohttp_session.get_session(request)
errored = await _handle_ui_error(session, _create_billing_project, db, billing_project)
if not errored:
set_message(session, f'Added billing project {billing_project}.', 'info')
return web.HTTPFound(deploy_config.external_url('batch', '/billing_projects'))
@routes.post('/api/v1alpha/billing_projects/{billing_project}/create')
@monitor_endpoint
@rest_authenticated_developers_or_auth_only
async def api_get_create_billing_projects(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
await _handle_api_error(_create_billing_project, db, billing_project)
return web.json_response(billing_project)
async def _close_billing_project(db, billing_project):
@transaction(db)
async def close_project(tx):
row = await tx.execute_and_fetchone(
'''
SELECT name, `status`, batches.id as batch_id
FROM billing_projects
LEFT JOIN batches
ON billing_projects.name = batches.billing_project
AND billing_projects.`status` != 'deleted'
AND batches.time_completed IS NULL
AND NOT batches.deleted
WHERE name = %s
LIMIT 1
FOR UPDATE;
''',
(billing_project,),
)
if not row:
raise NonExistentBillingProjectError(billing_project)
assert row['name'] == billing_project
if row['status'] == 'closed':
raise BatchOperationAlreadyCompletedError(
f'Billing project {billing_project} is already closed or deleted.', 'info'
)
if row['batch_id'] is not None:
raise BatchUserError(f'Billing project {billing_project} has open or running batches.', 'error')
await tx.execute_update("UPDATE billing_projects SET `status` = 'closed' WHERE name = %s;", (billing_project,))
await close_project() # pylint: disable=no-value-for-parameter
@routes.post('/billing_projects/{billing_project}/close')
@monitor_endpoint
@check_csrf_token
@web_authenticated_developers_only(redirect=False)
async def post_close_billing_projects(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
session = await aiohttp_session.get_session(request)
errored = await _handle_ui_error(session, _close_billing_project, db, billing_project)
if not errored:
set_message(session, f'Closed billing project {billing_project}.', 'info')
return web.HTTPFound(deploy_config.external_url('batch', '/billing_projects'))
@routes.post('/api/v1alpha/billing_projects/{billing_project}/close')
@monitor_endpoint
@rest_authenticated_developers_or_auth_only
async def api_close_billing_projects(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
await _handle_api_error(_close_billing_project, db, billing_project)
return web.json_response(billing_project)
async def _reopen_billing_project(db, billing_project):
@transaction(db)
async def open_project(tx):
row = await tx.execute_and_fetchone(
"SELECT name, `status` FROM billing_projects WHERE name = %s FOR UPDATE;", (billing_project,)
)
if not row:
raise NonExistentBillingProjectError(billing_project)
assert row['name'] == billing_project
if row['status'] == 'deleted':
raise BatchUserError(f'Billing project {billing_project} has been deleted and cannot be reopened.', 'error')
if row['status'] == 'open':
raise BatchOperationAlreadyCompletedError(f'Billing project {billing_project} is already open.', 'info')
await tx.execute_update("UPDATE billing_projects SET `status` = 'open' WHERE name = %s;", (billing_project,))
await open_project() # pylint: disable=no-value-for-parameter
@routes.post('/billing_projects/{billing_project}/reopen')
@monitor_endpoint
@check_csrf_token
@web_authenticated_developers_only(redirect=False)
async def post_reopen_billing_projects(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
session = await aiohttp_session.get_session(request)
errored = await _handle_ui_error(session, _reopen_billing_project, db, billing_project)
if not errored:
set_message(session, f'Re-opened billing project {billing_project}.', 'info')
return web.HTTPFound(deploy_config.external_url('batch', '/billing_projects'))
@routes.post('/api/v1alpha/billing_projects/{billing_project}/reopen')
@monitor_endpoint
@rest_authenticated_developers_or_auth_only
async def api_reopen_billing_projects(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
await _handle_api_error(_reopen_billing_project, db, billing_project)
return web.json_response(billing_project)
async def _delete_billing_project(db, billing_project):
@transaction(db)
async def delete_project(tx):
row = await tx.execute_and_fetchone(
'SELECT name, `status` FROM billing_projects WHERE name = %s FOR UPDATE;', (billing_project,)
)
if not row:
raise NonExistentBillingProjectError(billing_project)
assert row['name'] == billing_project
if row['status'] == 'deleted':
raise BatchOperationAlreadyCompletedError(f'Billing project {billing_project} is already deleted.', 'info')
if row['status'] == 'open':
raise BatchUserError(f'Billing project {billing_project} is open and cannot be deleted.', 'error')
await tx.execute_update("UPDATE billing_projects SET `status` = 'deleted' WHERE name = %s;", (billing_project,))
await delete_project() # pylint: disable=no-value-for-parameter
@routes.post('/api/v1alpha/billing_projects/{billing_project}/delete')
@monitor_endpoint
@rest_authenticated_developers_or_auth_only
async def api_delete_billing_projects(request, userdata): # pylint: disable=unused-argument
db: Database = request.app['db']
billing_project = request.match_info['billing_project']
await _handle_api_error(_delete_billing_project, db, billing_project)
return web.json_response(billing_project)
@routes.patch('/api/v1alpha/inst_colls/refresh')
@batch_only
async def refresh_inst_colls(request):
inst_coll_configs: InstanceCollectionConfigs = request.app['inst_coll_configs']
await inst_coll_configs.refresh()
return web.Response()
@routes.get('')
@routes.get('/')
@web_authenticated_users_only()
async def index(request, userdata): # pylint: disable=unused-argument
location = request.app.router['batches'].url_for()
raise web.HTTPFound(location=location)
async def cancel_batch_loop_body(app):
async with client_session() as session:
await request_retry_transient_errors(
session,
'POST',
deploy_config.url('batch-driver', '/api/v1alpha/batches/cancel'),
headers=app['batch_headers'],
)
should_wait = True
return should_wait
async def delete_batch_loop_body(app):
async with client_session() as session:
await request_retry_transient_errors(
session,
'POST',
deploy_config.url('batch-driver', '/api/v1alpha/batches/delete'),
headers=app['batch_headers'],
)
should_wait = True
return should_wait
async def on_startup(app):
app['task_manager'] = aiotools.BackgroundTaskManager()
pool = concurrent.futures.ThreadPoolExecutor()
app['blocking_pool'] = pool
db = Database()
await db.async_init()
app['db'] = db
row = await db.select_and_fetchone(
'''
SELECT instance_id, internal_token, n_tokens FROM globals;
'''
)
app['n_tokens'] = row['n_tokens']
instance_id = row['instance_id']
log.info(f'instance_id {instance_id}')
app['instance_id'] = instance_id
app['internal_token'] = row['internal_token']
app['batch_headers'] = {'Authorization': f'Bearer {row["internal_token"]}'}
credentials = google.oauth2.service_account.Credentials.from_service_account_file('/gsa-key/key.json')
app['log_store'] = LogStore(BATCH_BUCKET_NAME, instance_id, pool, credentials=credentials)
inst_coll_configs = InstanceCollectionConfigs(app)
app['inst_coll_configs'] = inst_coll_configs
await inst_coll_configs.async_init()
cancel_batch_state_changed = asyncio.Event()
app['cancel_batch_state_changed'] = cancel_batch_state_changed
app['task_manager'].ensure_future(
retry_long_running('cancel_batch_loop', run_if_changed, cancel_batch_state_changed, cancel_batch_loop_body, app)
)
delete_batch_state_changed = asyncio.Event()
app['delete_batch_state_changed'] = delete_batch_state_changed
app['task_manager'].ensure_future(
retry_long_running('delete_batch_loop', run_if_changed, delete_batch_state_changed, delete_batch_loop_body, app)
)
async def on_cleanup(app):
try:
app['blocking_pool'].shutdown()
finally:
app['task_manager'].shutdown()
def run():
app = web.Application(client_max_size=HTTP_CLIENT_MAX_SIZE)
setup_aiohttp_session(app)
setup_aiohttp_jinja2(app, 'batch.front_end')
setup_common_static_routes(routes)
app.add_routes(routes)
app.router.add_get("/metrics", server_stats)
app.on_startup.append(on_startup)
app.on_cleanup.append(on_cleanup)
asyncio.get_event_loop().add_signal_handler(signal.SIGUSR1, dump_all_stacktraces)
web.run_app(
deploy_config.prefix_application(app, 'batch', client_max_size=HTTP_CLIENT_MAX_SIZE),
host='0.0.0.0',
port=5000,
access_log_class=AccessLogger,
ssl_context=internal_server_ssl_context(),
)
| 35.160494 | 163 | 0.639437 |
fe8e4a4b09d8fd988b6575c1cba9b4844587af87 | 2,864 | py | Python | yt_astro_analysis/halo_analysis/halo_catalog/halo_filters.py | brittonsmith/yt_astro_analysis | f5d255a89dc1e882866cbfabcc627c3af3ee6d62 | [
"BSD-3-Clause-Clear"
] | null | null | null | yt_astro_analysis/halo_analysis/halo_catalog/halo_filters.py | brittonsmith/yt_astro_analysis | f5d255a89dc1e882866cbfabcc627c3af3ee6d62 | [
"BSD-3-Clause-Clear"
] | null | null | null | yt_astro_analysis/halo_analysis/halo_catalog/halo_filters.py | brittonsmith/yt_astro_analysis | f5d255a89dc1e882866cbfabcc627c3af3ee6d62 | [
"BSD-3-Clause-Clear"
] | null | null | null | """
HaloCatalog filters
"""
import numpy as np
from yt.utilities.on_demand_imports import \
_scipy as scipy
from yt_astro_analysis.halo_analysis.halo_catalog.analysis_operators import \
add_filter
def quantity_value(halo, field, operator, value, units):
r"""
Filter based on a value in the halo quantities dictionary.
Parameters
----------
halo : Halo object
The Halo object to be provided by the HaloCatalog.
field : string
The field used for the evaluation.
operator : string
The comparison operator to be used ("<", "<=", "==", ">=", ">", etc.)
value : numneric
The value to be compared against.
units : string
Units of the value to be compared.
"""
if field not in halo.quantities:
raise RuntimeError("Halo object does not contain %s quantity." % field)
h_value = halo.quantities[field].in_units(units).to_ndarray()
return eval("%s %s %s" % (h_value, operator, value))
add_filter("quantity_value", quantity_value)
def not_subhalo(halo, field_type="halos"):
"""
Only return true if this halo is not a subhalo.
This is used for halo finders such as Rockstar that output parent
and subhalos together.
"""
if not hasattr(halo.halo_catalog, "parent_dict"):
halo.halo_catalog.parent_dict = \
_create_parent_dict(halo.halo_catalog.data_source, ptype=field_type)
return halo.halo_catalog.parent_dict[int(halo.quantities["particle_identifier"])] == -1
add_filter("not_subhalo", not_subhalo)
def _create_parent_dict(data_source, ptype="halos"):
"""
Create a dictionary of halo parents to allow for filtering of subhalos.
For a pair of halos whose distance is smaller than the radius of at least
one of the halos, the parent is defined as the halo with the larger radius.
Parent halos (halos with no parents of their own) have parent index values of -1.
"""
pos = np.rollaxis(
np.array([data_source[ptype, "particle_position_x"].in_units("Mpc"),
data_source[ptype, "particle_position_y"].in_units("Mpc"),
data_source[ptype, "particle_position_z"].in_units("Mpc")]), 1)
rad = data_source[ptype, "virial_radius"].in_units("Mpc").to_ndarray()
ids = data_source[ptype, "particle_identifier"].to_ndarray().astype("int")
parents = -1 * np.ones_like(ids, dtype="int")
boxsize = data_source.ds.domain_width.in_units('Mpc')
my_tree = scipy.spatial.cKDTree(pos, boxsize=boxsize)
for i in range(ids.size):
neighbors = np.array(
my_tree.query_ball_point(pos[i], rad[i], p=2))
if neighbors.size > 1:
parents[neighbors] = ids[neighbors[np.argmax(rad[neighbors])]]
parents[ids == parents] = -1
parent_dict = dict(zip(ids, parents))
return parent_dict
| 34.095238 | 91 | 0.670391 |
321284219c9f0ae73164597a45404aa5235b0205 | 646 | py | Python | Algorithms/radixten.py | akselsd/VisualSort | 26b5505219227c20ac1ca834bc9ec89c989af457 | [
"MIT"
] | null | null | null | Algorithms/radixten.py | akselsd/VisualSort | 26b5505219227c20ac1ca834bc9ec89c989af457 | [
"MIT"
] | null | null | null | Algorithms/radixten.py | akselsd/VisualSort | 26b5505219227c20ac1ca834bc9ec89c989af457 | [
"MIT"
] | null | null | null | def radix_sort_base_ten(numlist,handler):
n = len(numlist.numbers)
max_digit = len(str(n))
for base in range(max_digit):
buckets = [[] for x in range(10)]
for index, value in enumerate(numlist.numbers):
handler.update([index])
base_value = (value // (10**base)) % 10
buckets[base_value].append(value)
new_numbers = []
numlist.numbers = []
for bucket in buckets:
new_numbers.extend(bucket)
for new_index in range(n):
numlist.numbers.append(new_numbers[new_index])
handler.update([new_index])
handler.update() | 32.3 | 58 | 0.589783 |
fee6696480cc8f410c45a046379a186aec179dc8 | 13,256 | py | Python | run_if_finetuning.py | aporporato/electra | 247e1d507cf6bcaf9cc6080101f6593f8b3d92f7 | [
"Apache-2.0"
] | null | null | null | run_if_finetuning.py | aporporato/electra | 247e1d507cf6bcaf9cc6080101f6593f8b3d92f7 | [
"Apache-2.0"
] | null | null | null | run_if_finetuning.py | aporporato/electra | 247e1d507cf6bcaf9cc6080101f6593f8b3d92f7 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Fine-tunes an ELECTRA model on a downstream task."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import collections
import json
import tensorflow.compat.v1 as tf
import configure_if_finetuning
from finetune import preprocessing_if
from finetune import task_if_builder
from model import modeling
from model import optimization
from util import training_utils
from util import utils
class FinetuningModel(object):
"""Finetuning model with support for multi-task training."""
def __init__(self, config: configure_if_finetuning.FinetuningIFConfig, tasks,
is_training, features, num_train_steps):
# Create a shared transformer encoder
bert_config = training_utils.get_bert_config(config)
self.bert_config = bert_config
if config.debug:
bert_config.num_hidden_layers = 3
bert_config.hidden_size = 144
bert_config.intermediate_size = 144 * 4
bert_config.num_attention_heads = 4
assert config.max_seq_length <= bert_config.max_position_embeddings
bert_model = modeling.BertModel(
bert_config=bert_config,
is_training=is_training,
input_ids=features["input_ids"],
input_mask=features["input_mask"],
token_type_ids=features["segment_ids"],
use_one_hot_embeddings=config.use_tpu,
embedding_size=config.embedding_size)
percent_done = (tf.cast(tf.train.get_or_create_global_step(), tf.float32) /
tf.cast(num_train_steps, tf.float32))
# Add specific tasks
self.outputs = {"task_id": features["task_id"]}
losses = []
for task in tasks:
with tf.variable_scope("task_specific/" + task.name):
task_losses, task_outputs = task.get_prediction_module(
bert_model, features, is_training, percent_done)
losses.append(task_losses)
self.outputs[task.name] = task_outputs
self.loss = tf.reduce_sum(
tf.stack(losses, -1) *
tf.one_hot(features["task_id"], len(config.task_names)))
def model_fn_builder(config: configure_if_finetuning.FinetuningIFConfig, tasks,
num_train_steps, pretraining_config=None):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params):
"""The `model_fn` for TPUEstimator."""
utils.log("Building model...")
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
model = FinetuningModel(
config, tasks, is_training, features, num_train_steps)
# Load pre-trained weights from checkpoint
init_checkpoint = config.init_checkpoint
if pretraining_config is not None:
init_checkpoint = tf.train.latest_checkpoint(pretraining_config.model_dir)
utils.log("Using checkpoint", init_checkpoint)
tvars = tf.trainable_variables()
scaffold_fn = None
if init_checkpoint:
assignment_map, _ = modeling.get_assignment_map_from_checkpoint(
tvars, init_checkpoint)
if config.use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
# Build model for training or prediction
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
model.loss, config.learning_rate, num_train_steps,
weight_decay_rate=config.weight_decay_rate,
use_tpu=config.use_tpu,
warmup_proportion=config.warmup_proportion,
layerwise_lr_decay_power=config.layerwise_lr_decay,
n_transformer_layers=model.bert_config.num_hidden_layers
)
output_spec = tf.estimator.tpu.TPUEstimatorSpec(
mode=mode,
loss=model.loss,
train_op=train_op,
scaffold_fn=scaffold_fn,
training_hooks=[training_utils.ETAHook(
{} if config.use_tpu else dict(loss=model.loss),
num_train_steps, config.iterations_per_loop, config.use_tpu, 10)])
else:
assert mode == tf.estimator.ModeKeys.PREDICT
output_spec = tf.estimator.tpu.TPUEstimatorSpec(
mode=mode,
predictions=utils.flatten_dict(model.outputs),
scaffold_fn=scaffold_fn)
utils.log("Building complete")
return output_spec
return model_fn
class ModelRunner(object):
"""Fine-tunes a model on a supervised task."""
def __init__(self, config: configure_if_finetuning.FinetuningIFConfig, tasks,
pretraining_config=None):
self._config = config
self._tasks = tasks
self._preprocessor = preprocessing_if.Preprocessor(config, self._tasks)
is_per_host = tf.estimator.tpu.InputPipelineConfig.PER_HOST_V2
tpu_cluster_resolver = None
if config.use_tpu and config.tpu_name:
tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(
config.tpu_name, zone=config.tpu_zone, project=config.gcp_project)
tpu_config = tf.estimator.tpu.TPUConfig(
iterations_per_loop=config.iterations_per_loop,
num_shards=config.num_tpu_cores,
per_host_input_for_training=is_per_host,
tpu_job_name=config.tpu_job_name)
run_config = tf.estimator.tpu.RunConfig(
cluster=tpu_cluster_resolver,
model_dir=config.model_dir,
save_checkpoints_steps=config.save_checkpoints_steps,
save_checkpoints_secs=None,
tpu_config=tpu_config)
if self._config.do_train:
(self._train_input_fn,
self.train_steps) = self._preprocessor.prepare_train()
else:
self._train_input_fn, self.train_steps = None, 0
model_fn = model_fn_builder(
config=config,
tasks=self._tasks,
num_train_steps=self.train_steps,
pretraining_config=pretraining_config)
self._estimator = tf.estimator.tpu.TPUEstimator(
use_tpu=config.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=config.train_batch_size,
eval_batch_size=config.eval_batch_size,
predict_batch_size=config.predict_batch_size)
def train(self):
utils.log("Training for {} steps".format(self.train_steps))
self._estimator.train(
input_fn=self._train_input_fn, max_steps=self.train_steps)
def evaluate(self):
return {task.name: self.evaluate_task(task) for task in self._tasks}
def evaluate_task(self, task, split="dev", return_results=True):
"""Evaluate the current model."""
utils.log("Evaluating", task.name)
eval_input_fn, _ = self._preprocessor.prepare_predict([task], split)
results = self._estimator.predict(input_fn=eval_input_fn,
yield_single_examples=True)
scorer = task.get_scorer()
for r in results:
if r["task_id"] != len(self._tasks): # ignore padding examples
r = utils.nest_dict(r, self._config.task_names)
scorer.update(r[task.name])
if return_results:
utils.log(task.name + ": " + scorer.results_str())
utils.log()
return dict(scorer.get_results())
else:
return scorer
def write_classification_outputs(self, tasks, trial, split):
"""Write classification predictions to disk."""
utils.log("Writing out predictions for", tasks, split)
predict_input_fn, _ = self._preprocessor.prepare_predict(tasks, split)
results = self._estimator.predict(input_fn=predict_input_fn,
yield_single_examples=True)
# task name -> eid -> model-logits
logits = collections.defaultdict(dict)
for r in results:
if r["task_id"] != len(self._tasks):
r = utils.nest_dict(r, self._config.task_names)
task_name = self._config.task_names[r["task_id"]]
logits[task_name][r[task_name]["eid"]] = (
r[task_name]["logits"] if "logits" in r[task_name]
else r[task_name]["predictions"])
for task_name in logits:
utils.log("Pickling predictions for {} {} examples ({})".format(
len(logits[task_name]), task_name, split))
if trial <= self._config.n_writes_test:
utils.write_pickle(logits[task_name], self._config.test_predictions(
task_name, split, trial))
def write_results(config: configure_if_finetuning.FinetuningIFConfig, results):
"""Write evaluation metrics to disk."""
utils.log("Writing results to", config.results_txt)
utils.mkdir(config.results_txt.rsplit("/", 1)[0])
utils.write_pickle(results, config.results_pkl)
with tf.io.gfile.GFile(config.results_txt, "w") as f:
results_str = ""
for trial_results in results:
for task_name, task_results in trial_results.items():
if task_name == "time" or task_name == "global_step":
continue
results_str += task_name + ": " + " - ".join(
["{}: {:.2f}".format(k, v)
for k, v in task_results.items()]) + "\n"
f.write(results_str)
utils.write_pickle(results, config.results_pkl)
def run_finetuning(config: configure_if_finetuning.FinetuningIFConfig):
"""Run finetuning."""
# Setup for training
results = []
trial = 1
heading_info = "model={}, trial {}/{}".format(
config.model_name, trial, config.num_trials)
heading = lambda msg: utils.heading(msg + ": " + heading_info)
heading("Config")
utils.log_config(config)
generic_model_dir = config.model_dir
tasks = task_if_builder.get_tasks(config)
# Train and evaluate num_trials models with different random seeds
while config.num_trials < 0 or trial <= config.num_trials:
config.model_dir = generic_model_dir + "_" + str(trial)
if config.do_train:
utils.rmkdir(config.model_dir)
model_runner = ModelRunner(config, tasks)
if config.do_train:
heading("Start training")
model_runner.train()
utils.log()
if config.do_eval:
heading("Run dev set evaluation")
results.append(model_runner.evaluate())
write_results(config, results)
if config.write_test_outputs and trial <= config.n_writes_test:
heading("Running on the test set and writing the predictions")
for task in tasks:
# Currently only writing preds for GLUE and SQuAD 2.0 is supported
if task.name in ["fn", "npc", "vn", "wn"]:
for split in task.get_test_splits():
model_runner.write_classification_outputs([task], trial, split)
else:
utils.log("Skipping task", task.name,
"- writing predictions is not supported for this task")
if trial != config.num_trials and (not config.keep_all_models):
utils.rmrf(config.model_dir)
trial += 1
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--data-dir", required=True,
help="Location of data files (model weights, etc).")
parser.add_argument("--model-name", required=True,
help="The name of the model being fine-tuned.")
parser.add_argument("--hparams", default="{}",
help="JSON dict of model hyperparameters.")
args = parser.parse_args()
if args.hparams.endswith(".json"):
hparams = utils.load_json(args.hparams)
else:
hparams = json.loads(args.hparams)
tf.logging.set_verbosity(tf.logging.ERROR)
run_finetuning(configure_if_finetuning.FinetuningIFConfig(
args.model_name, args.data_dir, **hparams))
if __name__ == "__main__":
main()
| 42.216561 | 91 | 0.634203 |
9746ccd97229349c3a95a03599877d30caa6a9b6 | 1,205 | py | Python | src/gdrive_transfer/testing.py | benkrikler/gdrive_transfer | 2ad608590c9ddb64a88e3825bbee30f9d78edf73 | [
"MIT"
] | null | null | null | src/gdrive_transfer/testing.py | benkrikler/gdrive_transfer | 2ad608590c9ddb64a88e3825bbee30f9d78edf73 | [
"MIT"
] | null | null | null | src/gdrive_transfer/testing.py | benkrikler/gdrive_transfer | 2ad608590c9ddb64a88e3825bbee30f9d78edf73 | [
"MIT"
] | null | null | null | from .drive import create, create_shortcut, ls
from .auth import get_credentials
import googleapiclient
from googleapiclient.discovery import build
def create_test_structure_1(dest_id):
cred = get_credentials()
with build('drive', 'v3', credentials=cred) as service:
extra = {"gdrive_transfer_test-data": "This is a test"}
top = create("Top level test directory", "folder", dest_id, extra=extra, service=service)["id"]
one = create("Directory one", "folder", top, extra=extra, service=service)["id"]
two = create("Directory Two", "folder", top, extra=extra, service=service)["id"]
three = create("Directory three", "folder", two, extra=extra, service=service)["id"]
four = create("Directory four", "folder", three, extra=extra, service=service)["id"]
create("Doc a", "doc", top, extra=extra, service=service)
doc_b = create("Doc b", "doc", one, extra=extra, service=service)
create("Sheet c", "spreadsheet", two, extra=extra, service=service)
create("Sheet d", "spreadsheet", three, extra=extra, service=service)
create_shortcut(doc_b, two, extra=extra, service=service)
ls(top)
return top
| 50.208333 | 103 | 0.670539 |
9ff94b005099a57109f7b62955a7cea9f5f9ce4c | 1,077 | py | Python | sin_Taylor_series_diffeq.py | chapman-phys227-2016s/hw-3-malfa100 | df1343476e7b40c728f7b9027162369d8d559c13 | [
"MIT"
] | null | null | null | sin_Taylor_series_diffeq.py | chapman-phys227-2016s/hw-3-malfa100 | df1343476e7b40c728f7b9027162369d8d559c13 | [
"MIT"
] | null | null | null | sin_Taylor_series_diffeq.py | chapman-phys227-2016s/hw-3-malfa100 | df1343476e7b40c728f7b9027162369d8d559c13 | [
"MIT"
] | null | null | null | """
File: sin_Taylor_series_diffeq.py
Copyright (c) 2016 Andrew Malfavon
Excerise A.14
License: MIT
Computes a Taylor polynomial approximation for sinx and shows the accuracy in a table
"""
import numpy as np
#computes the approximation based on the exercises in the book
def sin_Taylor(x, n):
i = 1
an_prev = x
sn_prev = 0.0
while i <= n + 1:
sn = sn_prev + an_prev
an = (-x**2 * an_prev) / (((2 * i) + 1) * (2 * i))
sn_prev = sn
an_prev = an
i += 1
return abs(an), sn
#test for small x=0.0001 and n = 2, sin(x) is zero to the third decimal
def test_sin_Taylor():
assert round(sin_Taylor(0.0001, 2)[1], 3) == 0.0
#create a table to display the approximations for various n and x
def table():
print '%15s %15s %20s %8s' % ('x Values:', 'n Values:', 'Aproximations:', 'Exact:')
x_list = [0.01, np.pi/2, np.pi, 3*np.pi/2]
n_list = [2, 5, 10, 100]
for x in x_list:
for n in n_list:
table = sin_Taylor(x, n)
print '%15f %15f %15f %15f' % (x, n, table[1], np.sin(x)) | 29.916667 | 87 | 0.5961 |
43d93817420151d6272455f7b1e9fc08ddfb0aeb | 2,002 | py | Python | examples/pipeline.py | jgoldford/ASR | 10897401faa5e4dcdf03cc18f8b1b826b5b4a066 | [
"MIT"
] | null | null | null | examples/pipeline.py | jgoldford/ASR | 10897401faa5e4dcdf03cc18f8b1b826b5b4a066 | [
"MIT"
] | null | null | null | examples/pipeline.py | jgoldford/ASR | 10897401faa5e4dcdf03cc18f8b1b826b5b4a066 | [
"MIT"
] | null | null | null |
# PIPELINE For the construction for ancesteral sequences based on the tutorial provided by Rubin Studer:
# https://evosite3d.blogspot.com/2014/09/tutorial-on-ancestral-sequence.html
# Dependence all on path and aliased ()
# mafft - multiple sequence alignment
# phyml - large tree building using maximum likelihood
# codeml - (i.e. PAML) ancesteral state reconstruction
__author__ = "Joshua E Goldford"
__date__ = 'Feb. 4th 2017'
import subprocess
import os
from helpers import fasta2phylip,rst2fasta,PAMLparams
# the file ID is the prefix used before the .fasta identifier in the file name
FileID = 'K00384_renamed_trimmed';
if not os.path.exists(os.getcwd() + '/' + FileID +'.fasta'):
print('error: fasta file not found')
exit();
# 1. Multiple sequence alignment using MAFFT
cmd = 'mafft-linsi %(fid)s.fasta > %(fid)s_MSA.fasta' % {'fid': FileID};
subprocess.call(cmd,shell=True);
# 2. Convert Fasta to Phylip
inFile = '%(fid)s_MSA.fasta' % {'fid': FileID};
outFile = '%(fid)s_MSA.phylip' % {'fid': FileID};
# only work woth phylip format for sequences
seqsFile = outFile;
# call helper function
fasta2phylip(inFile,outFile);
# 3. Call phyml (Alias is not working for some reason)
cmd = '/Library/PhyML-3.1/PhyML-3.1_macOS-MountainLion -i %(fid)s -d aa -m JTT -c 4 -a e -b 0' % {'fid': seqsFile};
subprocess.call(cmd,shell=True);
# move file to TreeName
treeFile = FileID+'.tree';
cmd = 'mv %(seqs)s_phyml_tree.txt %(tree)s' % {'seqs': seqsFile,'tree': treeFile};
subprocess.call(cmd,shell=True);
PAMLoutputFile = FileID+'.mlc';
# 4 construct PAML parameters
params = PAMLparams(seqsFile,treeFile,PAMLoutputFile);
# note that you can simply change values by chainging values of attributes (e.g. params.verbose = 0)
text_file = open("control_file.ctl", "w")
text_file.write("%s" % params.toText())
text_file.close()
# 5 call PAML
cmd = 'codeml control_file.ctl';
subprocess.call(cmd,shell=True);
# 6 convert PAML outut to Fasta File
rst2fasta('rst','ancesteral_sequences.fasta');
| 31.777778 | 115 | 0.728771 |
68d1b5cf8bfecdfbd4d8e3407097de087e639d67 | 12,750 | py | Python | widget/bean/plot_dataset_props.py | CASL/VERAview | 89b18f239ca5228185b80d5392068981d7733d3b | [
"BSD-3-Clause"
] | 7 | 2017-04-21T05:35:16.000Z | 2022-02-28T20:14:42.000Z | widget/bean/plot_dataset_props.py | CASL/VERAview | 89b18f239ca5228185b80d5392068981d7733d3b | [
"BSD-3-Clause"
] | 2 | 2019-02-27T15:25:34.000Z | 2021-05-26T17:01:59.000Z | widget/bean/plot_dataset_props.py | CASL/VERAview | 89b18f239ca5228185b80d5392068981d7733d3b | [
"BSD-3-Clause"
] | 3 | 2019-07-09T08:31:34.000Z | 2022-03-08T03:18:48.000Z | #!/usr/bin/env python
# $Id$
#------------------------------------------------------------------------
# NAME: plot_dataset_props.py -
# HISTORY: -
# 2018-09-12 leerw@ornl.gov -
# Added draw order field.
# 2017-07-21 leerw@ornl.gov -
# Fixing _OnCharHook for Linux.
# 2017-03-31 leerw@ornl.gov -
# Added EVT_CHAR_HOOK.
# 2017-03-24 leerw@ornl.gov -
# Explicit assign of each dataset to an axis.
# 2016-12-12 leerw@ornl.gov -
# Updated with DataSetName keys.
# 2016-05-27 leerw@ornl.gov -
# Accomodate left/right axis pairs as well as bottom/top.
# Enforcing axis selections.
# 2016-05-19 leerw@ornl.gov -
#------------------------------------------------------------------------
import functools, json, math, os, six, sys
import pdb #pdb.set_trace()
try:
# import wx, wx.lib.newevent
import wx
import wx.lib.agw.ultimatelistctrl as ulc
except Exception:
raise ImportError( 'The wxPython module is required for this component' )
from data.datamodel import DataSetName
#------------------------------------------------------------------------
# CLASS: PlotDataSetPropsBean -
#------------------------------------------------------------------------
class PlotDataSetPropsBean( ulc.UltimateListCtrl ):
"""List containing columns for the dataset name, top axis check,
bottom axis check, and scale value text control.
"""
# -- Object Methods
# --
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsBean.__init__() -
#----------------------------------------------------------------------
def __init__(
self, container,
wid = -1, ds_props = None,
axis1 = 'Bottom',
axis2 = 'Top'
):
"""
Args:
container (wx.Window): parent object
wid (int): element id, defaults to -1 or wx.ID_ANY
ds_props (dict): keyed by qds_name, settings with which to
initialize this bean
axis1 (str): primary axis name
axis2 (str): secondary axis name
"""
super( PlotDataSetPropsBean, self ).__init__(
container, wid,
agwStyle = wx.LC_REPORT | wx.LC_VRULES | wx.LC_SINGLE_SEL |
ulc.ULC_HAS_VARIABLE_ROW_HEIGHT
)
self.fAxis1 = axis1
self.fAxis2 = axis2
#wx.LIST_AUTOSIZE only works the first time
#wx.LIST_AUTOSIZE_FILL(-3)
self.InsertColumn( 0, 'Dataset', width = 200 )
self.InsertColumn( 1, axis1 + ' Axis' )
self.InsertColumn( 2, axis2 + ' Axis' )
self.InsertColumn( 3, 'Scale', width = 128 )
self.InsertColumn( 4, 'Draw Order', width = 64 )
self.fEvenColor = wx.Colour( 240, 240, 255 )
self.fOddColor = wx.Colour( 240, 255, 240 )
if ds_props and isinstance( ds_props, dict ):
self.SetProps( ds_props )
#end __init__
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsBean.GetProps() -
#----------------------------------------------------------------------
def GetProps( self ):
"""Builds the dictionary of dataset properties from current control
values.
@return dict of dataset properties keyed by name with keys:
axis: axis name or ''
draworder: 1-based draw order sequence
scale: scale value
"""
no_axis_names = []
have_axes = [ False, False ]
props = {}
for row in range( self.GetItemCount() ):
name = self.GetItem( row, 0 ).GetText()
if self.GetItemWindow( row, 1 ).GetValue():
axis = self.fAxis1.lower()
have_axes[ 0 ] = True
elif self.GetItemWindow( row, 2 ).GetValue():
axis = self.fAxis2.lower()
have_axes[ 1 ] = True
else:
axis = ''
no_axis_names.append( name )
scale_str = self.GetItemWindow( row, 3 ).GetValue()
try:
scale = float( scale_str )
except ValueError:
scale = 1.0
order_str = self.GetItemWindow( row, 4 ).GetValue()
try:
order = int( order_str )
except ValueError:
order = 999999
props[ DataSetName( name ) ] = \
dict( axis = axis, draworder = order, scale = scale )
#end for
if not have_axes[ 0 ] and len( no_axis_names ) > 0:
props[ DataSetName( no_axis_names[ 0 ] ) ][ 'axis' ] = self.fAxis1.lower()
del no_axis_names[ 0 ]
if not have_axes[ 1 ] and len( no_axis_names ) > 0:
props[ DataSetName( no_axis_names[ 0 ] ) ][ 'axis' ] = self.fAxis2.lower()
return props
#end GetProps
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsBean._OnCheck() -
#----------------------------------------------------------------------
def _OnCheck( self, row, col, ev ):
"""
"""
if ev.IsChecked():
other_axis_col = 1 if col == 2 else 2
self.GetItemWindow( row, other_axis_col ).SetValue( False )
# for i in range( self.GetItemCount() ):
# if i != row:
# self.GetItemWindow( i, col ).SetValue( False )
#end for
#end if
#end _OnCheck
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsBean._OnFocusKill() -
#----------------------------------------------------------------------
def _OnFocusKill( self, ev ):
"""
"""
ev.Skip()
edit = ev.GetEventObject()
try:
scale = float( edit.GetValue() )
except ValueError:
edit.SetValue( '1.0' )
#end _OnFocusKill
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsBean._OnFocusSet() -
#----------------------------------------------------------------------
def _OnFocusSet( self, ev ):
"""
"""
ev.Skip()
edit = ev.GetEventObject()
edit.SelectAll()
#end _OnFocusSet
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsBean.SetProps() -
#----------------------------------------------------------------------
def SetProps( self, props_in ):
"""
@param props_in dict of dataset properties keyed by name with keys:
axis: axis name or ''
scale: scale factor
"""
if props_in:
self._UpdateControls( props_in )
#end if
#end SetProps
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsBean._UpdateControls() -
#----------------------------------------------------------------------
def _UpdateControls( self, props ):
"""
"""
self.DeleteAllItems()
if props:
ndx = 0
#for qds_name, rec in sorted( props.iteritems() ):
for qds_name, rec in \
sorted( props.items(), PlotDataSetPropsBean.CompareRecs ):
rec[ 'draworder' ] = ndx + 1
if rec.get( 'visible', False ):
name = qds_name.name
self.InsertStringItem( ndx, name )
# -- First Axis
check = wx.CheckBox( self, wx.ID_ANY )
check.SetValue( rec[ 'axis' ] == self.fAxis1.lower() )
check.Bind(
wx.EVT_CHECKBOX,
functools.partial( self._OnCheck, ndx, 1 )
)
self.SetItemWindow( ndx, 1, check, expand = True )
# -- Second Axis
check = wx.CheckBox( self, wx.ID_ANY )
check.SetValue( rec[ 'axis' ] == self.fAxis2.lower() )
check.Bind(
wx.EVT_CHECKBOX,
functools.partial( self._OnCheck, ndx, 2 )
)
self.SetItemWindow( ndx, 2, check, expand = True )
# -- Scale
value_str = '%.6g' % rec.get( 'scale', 1.0 )
edit = wx.TextCtrl( self, wx.ID_ANY, value = value_str )
edit.Bind( wx.EVT_KILL_FOCUS, self._OnFocusKill )
edit.Bind( wx.EVT_SET_FOCUS, self._OnFocusSet )
self.SetItemWindow( ndx, 3, edit, expand = True )
# -- Draw Order
edit = wx.TextCtrl( self, wx.ID_ANY, value = str( ndx + 1 ) )
edit.Bind( wx.EVT_KILL_FOCUS, self._OnFocusKill )
edit.Bind( wx.EVT_SET_FOCUS, self._OnFocusSet )
self.SetItemWindow( ndx, 4, edit, expand = True )
self.SetItemBackgroundColour(
ndx,
self.fEvenColor if ndx % 2 == 0 else self.fOddColor
)
ndx += 1
#end if rec.get( 'visible', False )
#end for qds_name, rec in sorted( props.iteritems() )
#end if props
#end _UpdateControls
# -- Static Methods
# --
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsBean.CompareRecs() -
#----------------------------------------------------------------------
@staticmethod
def CompareRecs( one, two ):
"""
"""
order_one = one[ 1 ].get( 'draworder', 999999 )
order_two = two[ 1 ].get( 'draworder', 999999 )
result = \
-1 if order_one < order_two else \
1 if order_one > order_two else \
0
if result == 0:
result = \
-1 if one[ 0 ] < two[ 0 ] else \
1 if one[ 0 ] > two[ 0 ] else \
0
return result
#end CompareRecs
#end PlotDataSetPropsBean
#------------------------------------------------------------------------
# CLASS: PlotDataSetPropsDialog -
#------------------------------------------------------------------------
class PlotDataSetPropsDialog( wx.Dialog ):
"""
"""
# -- Object Methods
# --
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsDialog.__init__() -
#----------------------------------------------------------------------
def __init__( self, *args, **kwargs ):
"""
"""
style = kwargs.get( 'style', wx.DEFAULT_DIALOG_STYLE )
style |= wx.RESIZE_BORDER
kwargs[ 'style' ] = style
if 'axis1' in kwargs:
axis1 = kwargs[ 'axis1' ]
del kwargs[ 'axis1' ]
else:
axis1 = 'Bottom'
if 'axis2' in kwargs:
axis2 = kwargs[ 'axis2' ]
del kwargs[ 'axis2' ]
else:
axis2 = 'Top'
super( PlotDataSetPropsDialog, self ).__init__( *args, **kwargs )
self.fBean = None
self.fProps = None
self._InitUI( axis1, axis2 )
#end __init__
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsDialog.GetProps() -
#----------------------------------------------------------------------
def GetProps( self ):
return self.fProps
#end GetProps
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsDialog._InitUI() -
#----------------------------------------------------------------------
def _InitUI( self, axis1, axis2 ):
self.fBean = PlotDataSetPropsBean( self, -1, axis1 = axis1, axis2 = axis2 )
button_sizer = wx.BoxSizer( wx.HORIZONTAL )
ok_button = wx.Button( self, label = '&OK' )
ok_button.Bind( wx.EVT_BUTTON, self._OnButton )
cancel_button = wx.Button( self, label = 'Cancel' )
cancel_button.Bind( wx.EVT_BUTTON, self._OnButton )
button_sizer.AddStretchSpacer()
button_sizer.Add( ok_button, 0, wx.ALL | wx.EXPAND, 6 );
button_sizer.AddSpacer( 10 )
button_sizer.Add( cancel_button, 0, wx.ALL | wx.EXPAND, 6 );
button_sizer.AddStretchSpacer()
sizer = wx.BoxSizer( wx.VERTICAL )
self.SetSizer( sizer )
sizer.Add(
self.fBean, 1,
wx.ALL | wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_TOP,
6
)
sizer.Add( button_sizer, 0, wx.ALL | wx.EXPAND, 6 )
self.Bind( wx.EVT_CHAR_HOOK, self._OnCharHook )
self.SetSize( wx.Size( 640, 400 ) )
self.SetTitle( 'Dataset Plot Properties' )
#sizer.Layout()
#self.Fit()
#self.Center()
#end _InitUI
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsDialog._OnButton() -
#----------------------------------------------------------------------
def _OnButton( self, ev ):
ev.Skip()
# -- ** EndModel() not passing result to caller via ShowModal() **
obj = ev.GetEventObject()
if obj.GetLabel() == 'Cancel':
retcode = 0
else:
retcode = 1
self.fProps = self.fBean.GetProps()
self.EndModal( retcode )
#end _OnButton
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsDialog._OnCharHook() -
#----------------------------------------------------------------------
def _OnCharHook( self, ev ):
code = ev.GetKeyCode()
if code == wx.WXK_RETURN:
self.fProps = self.fBean.GetProps()
self.EndModal( wx.ID_OK )
elif code == wx.WXK_ESCAPE:
self.EndModal( wx.ID_CANCEL )
else:
ev.DoAllowNextEvent()
ev.Skip()
#end _OnCharHook
#----------------------------------------------------------------------
# METHOD: PlotDataSetPropsDialog.ShowModal() -
#----------------------------------------------------------------------
def ShowModal( self, ds_props ):
self.fProps = {}
self.fBean.SetProps( ds_props if ds_props else {} )
return super( PlotDataSetPropsDialog, self ).ShowModal()
#end ShowModal
#end PlotDataSetPropsDialog
| 29.72028 | 80 | 0.502588 |
2e3d0f992c6bad6513fa1ab5362590242b370749 | 10,897 | py | Python | scripts/autodiff_logreg.py | VaibhaviMishra04/pyprobml | 53208f571561acd25e8608ac5d1eb5e2610f6cc0 | [
"MIT"
] | 2 | 2021-04-10T18:12:19.000Z | 2021-05-11T12:07:40.000Z | scripts/autodiff_logreg.py | Rebeca98/pyprobml | 2a4b9a267f64720cbba35dfa41af3e995ea006ca | [
"MIT"
] | 1 | 2021-04-22T15:46:27.000Z | 2021-04-22T15:46:27.000Z | scripts/autodiff_logreg.py | Rebeca98/pyprobml | 2a4b9a267f64720cbba35dfa41af3e995ea006ca | [
"MIT"
] | 1 | 2021-06-21T01:18:07.000Z | 2021-06-21T01:18:07.000Z | #!/usr/bin/python
"""
Demonstrate automatic differentiaiton on binary logistic regression
using JAX, Torch and TF
"""
import warnings
import tensorflow as tf
from absl import app, flags
warnings.filterwarnings("ignore", category=DeprecationWarning)
FLAGS = flags.FLAGS
# Define a command-line argument using the Abseil library:
# https://abseil.io/docs/python/guides/flags
flags.DEFINE_boolean('jax', True, 'Whether to use JAX.')
flags.DEFINE_boolean('tf', True, 'Whether to use Tensorflow 2.')
flags.DEFINE_boolean('pytorch', True, 'Whether to use PyTorch.')
flags.DEFINE_boolean('verbose', True, 'Whether to print lots of output.')
import numpy as np
#from scipy.misc import logsumexp
from scipy.special import logsumexp
import numpy as np # original numpy
np.set_printoptions(precision=3)
import jax
import jax.numpy as jnp
import numpy as np
from jax.scipy.special import logsumexp
from jax import grad, hessian, jacfwd, jacrev, jit, vmap
from jax.experimental import optimizers
from jax.experimental import stax
print("jax version {}".format(jax.__version__))
from jax.lib import xla_bridge
print("jax backend {}".format(xla_bridge.get_backend().platform))
import os
os.environ["XLA_FLAGS"]="--xla_gpu_cuda_data_dir=/home/murphyk/miniconda3/lib"
import torch
import torchvision
print("torch version {}".format(torch.__version__))
if torch.cuda.is_available():
print(torch.cuda.get_device_name(0))
print("current device {}".format(torch.cuda.current_device()))
else:
print("Torch cannot find GPU")
def set_torch_seed(seed):
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")
#torch.backends.cudnn.benchmark = True
import tensorflow as tf
from tensorflow import keras
print("tf version {}".format(tf.__version__))
if tf.test.is_gpu_available():
print(tf.test.gpu_device_name())
else:
print("TF cannot find GPU")
tf.compat.v1.enable_eager_execution()
# We make some wrappers around random number generation
# so it works even if we switch from numpy to JAX
def set_seed(seed):
return np.random.seed(seed)
def randn(args):
return np.random.randn(*args)
def randperm(args):
return np.random.permutation(args)
def BCE_with_logits(logits, targets):
'''Binary cross entropy loss'''
N = logits.shape[0]
logits = logits.reshape(N,1)
logits_plus = jnp.hstack([np.zeros((N,1)), logits]) # e^0=1
logits_minus = jnp.hstack([np.zeros((N,1)), -logits])
logp1 = -logsumexp(logits_minus, axis=1)
logp0 = -logsumexp(logits_plus, axis=1)
logprobs = logp1 * targets + logp0 * (1-targets)
return -np.sum(logprobs)/N
def sigmoid(x): return 0.5 * (np.tanh(x / 2.) + 1)
def predict_logit(weights, inputs):
return jnp.dot(inputs, weights) # Already vectorized
def predict_prob(weights, inputs):
return sigmoid(predict_logit(weights, inputs))
def NLL(weights, batch):
X, y = batch
logits = predict_logit(weights, X)
return BCE_with_logits(logits, y)
def NLL_grad(weights, batch):
X, y = batch
N = X.shape[0]
mu = predict_prob(weights, X)
g = jnp.sum(np.dot(np.diag(mu - y), X), axis=0)/N
return g
def setup_sklearn():
import sklearn.datasets
from sklearn.model_selection import train_test_split
iris = sklearn.datasets.load_iris()
X = iris["data"]
y = (iris["target"] == 2).astype(np.int) # 1 if Iris-Virginica, else 0'
N, D = X.shape # 150, 4
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.33, random_state=42)
from sklearn.linear_model import LogisticRegression
# We set C to a large number to turn off regularization.
# We don't fit the bias term to simplify the comparison below.
log_reg = LogisticRegression(solver="lbfgs", C=1e5, fit_intercept=False)
log_reg.fit(X_train, y_train)
w_mle_sklearn = jnp.ravel(log_reg.coef_)
set_seed(0)
w = w_mle_sklearn
return w, X_test, y_test
def compute_gradients_manually(w, X_test, y_test):
y_pred = predict_prob(w, X_test)
loss = NLL(w, (X_test, y_test))
grad_np = NLL_grad(w, (X_test, y_test))
print("params {}".format(w))
#print("pred {}".format(y_pred))
print("loss {}".format(loss))
print("grad {}".format(grad_np))
return grad_np
def compute_gradients_jax(w, X_test, y_test):
print("Starting JAX demo")
grad_jax = jax.grad(NLL)(w, (X_test, y_test))
print("grad {}".format(grad_jax))
return grad_jax
def compute_gradients_stax(w, X_test, y_test):
print("Starting STAX demo")
N, D = X_test.shape
def const_init(params):
def init(rng_key, shape):
return params
return init
#net_init, net_apply = stax.serial(stax.Dense(1), stax.elementwise(sigmoid))
dense_layer = stax.Dense(1, W_init=const_init(np.reshape(w, (D,1))),
b_init=const_init(np.array([0.0])))
net_init, net_apply = stax.serial(dense_layer)
rng = jax.random.PRNGKey(0)
in_shape = (-1,D)
out_shape, net_params = net_init(rng, in_shape)
def NLL_model(net_params, net_apply, batch):
X, y = batch
logits = net_apply(net_params, X)
return BCE_with_logits(logits, y)
y_pred2 = net_apply(net_params, X_test)
loss2 = NLL_model(net_params, net_apply, (X_test, y_test))
grad_jax2 = grad(NLL_model)(net_params, net_apply, (X_test, y_test))
grad_jax3 = grad_jax2[0][0] # layer 0, block 0 (weights not bias)
grad_jax4 = grad_jax3[:,0] # column vector
print("params {}".format(net_params))
#print("pred {}".format(y_pred2))
print("loss {}".format(loss2))
print("grad {}".format(grad_jax2))
return grad_jax4
def compute_gradients_torch(w, X_test, y_test):
print("Starting torch demo")
N, D = X_test.shape
w_torch = torch.Tensor(np.reshape(w, [D, 1])).to(device)
w_torch.requires_grad_()
x_test_tensor = torch.Tensor(X_test).to(device)
y_test_tensor = torch.Tensor(y_test).to(device)
y_pred = torch.sigmoid(torch.matmul(x_test_tensor, w_torch))[:,0]
criterion = torch.nn.BCELoss(reduction='mean')
loss_torch = criterion(y_pred, y_test_tensor)
loss_torch.backward()
grad_torch = w_torch.grad[:,0].numpy()
print("params {}".format(w_torch))
#print("pred {}".format(y_pred))
print("loss {}".format(loss_torch))
print("grad {}".format(grad_torch))
return grad_torch
def compute_gradients_torch_nn(w, X_test, y_test):
print("Starting torch demo: NN version")
N, D = X_test.shape
x_test_tensor = torch.Tensor(X_test).to(device)
y_test_tensor = torch.Tensor(y_test).to(device)
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear = torch.nn.Linear(D, 1, bias=False)
def forward(self, x):
y_pred = torch.sigmoid(self.linear(x))
return y_pred
model = Model()
# Manually set parameters to desired values
print(model.state_dict())
from collections import OrderedDict
w1 = torch.Tensor(np.reshape(w, [1, D])).to(device) # row vector
new_state_dict = OrderedDict({'linear.weight': w1})
model.load_state_dict(new_state_dict, strict=False)
#print(model.state_dict())
model.to(device) # make sure new params are on same device as data
criterion = torch.nn.BCELoss(reduction='mean')
y_pred2 = model(x_test_tensor)[:,0]
loss_torch2 = criterion(y_pred2, y_test_tensor)
loss_torch2.backward()
params_torch2 = list(model.parameters())
grad_torch2 = params_torch2[0].grad[0].numpy()
print("params {}".format(w1))
#print("pred {}".format(y_pred))
print("loss {}".format(loss_torch2))
print("grad {}".format(grad_torch2))
return grad_torch2
def compute_gradients_tf(w, X_test, y_test):
print("Starting TF demo")
N, D = X_test.shape
w_tf = tf.Variable(np.reshape(w, (D,1)))
x_test_tf = tf.convert_to_tensor(X_test, dtype=np.float64)
y_test_tf = tf.convert_to_tensor(np.reshape(y_test, (-1,1)), dtype=np.float64)
with tf.GradientTape() as tape:
logits = tf.linalg.matmul(x_test_tf, w_tf)
y_pred = tf.math.sigmoid(logits)
loss_batch = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_test_tf, logits=logits)
loss_tf = tf.reduce_mean(loss_batch, axis=0)
grad_tf = tape.gradient(loss_tf, [w_tf])
grad_tf = grad_tf[0][:,0].numpy()
print("params {}".format(w_tf))
#print("pred {}".format(y_pred))
print("loss {}".format(loss_tf))
print("grad {}".format(grad_tf))
return grad_tf
def compute_gradients_keras(w, X_test, y_test):
# This no longer runs
N, D = X_test.shape
print("Starting TF demo: keras version")
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(1, input_shape=(D,), activation=None, use_bias=False)
])
#model.compile(optimizer='sgd', loss=tf.nn.sigmoid_cross_entropy_with_logits)
model.build()
w_tf2 = tf.convert_to_tensor(np.reshape(w, (D,1)))
model.set_weights([w_tf2])
y_test_tf2 = tf.convert_to_tensor(np.reshape(y_test, (-1,1)), dtype=np.float32)
with tf.GradientTape() as tape:
logits_temp = model.predict(x_test_tf) # forwards pass only
logits2 = model(x_test_tf, training=True) # OO version enables backprop
loss_batch2 = tf.nn.sigmoid_cross_entropy_with_logits(y_test_tf2, logits2)
loss_tf2 = tf.reduce_mean(loss_batch2, axis=0)
grad_tf2 = tape.gradient(loss_tf2, model.trainable_variables)
grad_tf2 = grad_tf2[0][:,0].numpy()
print("params {}".format(w_tf2))
print("loss {}".format(loss_tf2))
print("grad {}".format(grad_tf2))
return grad_tf2
def main(_):
if FLAGS.verbose:
print('We will compute gradients for binary logistic regression')
w, X_test, y_test = setup_sklearn()
grad_np = compute_gradients_manually(w, X_test, y_test)
if FLAGS.jax:
grad_jax = compute_gradients_jax(w, X_test, y_test)
assert jnp.allclose(grad_np, grad_jax)
grad_stax = compute_gradients_stax(w, X_test, y_test)
assert jnp.allclose(grad_np, grad_stax)
if FLAGS.pytorch:
grad_torch = compute_gradients_torch(w, X_test, y_test)
assert jnp.allclose(grad_np, grad_torch)
grad_torch_nn = compute_gradients_torch_nn(w, X_test, y_test)
assert jnp.allclose(grad_np, grad_torch_nn)
if FLAGS.tf:
grad_tf = compute_gradients_tf(w, X_test, y_test)
assert jnp.allclose(grad_np, grad_tf)
#grad_tf = compute_gradients_keras(w)
if __name__ == '__main__':
app.run(main)
| 33.42638 | 93 | 0.674865 |
bff485b9f1b164b7ba59e43b509d66147fb353b3 | 8,279 | py | Python | mapproxy/test/system/test_util_conf.py | kaiCu/mapproxy | 9b28f9ca1286e686b8f2188dd52ce56b607427a7 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | mapproxy/test/system/test_util_conf.py | kaiCu/mapproxy | 9b28f9ca1286e686b8f2188dd52ce56b607427a7 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | mapproxy/test/system/test_util_conf.py | kaiCu/mapproxy | 9b28f9ca1286e686b8f2188dd52ce56b607427a7 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # -:- encoding: utf-8 -:-
# This file is part of the MapProxy project.
# Copyright (C) 2013 Omniscale <http://omniscale.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import with_statement
import os
import shutil
import tempfile
import yaml
from mapproxy.script.conf.app import config_command
from mapproxy.test.helper import capture
from nose.tools import eq_
def filename(name):
return os.path.join(
os.path.dirname(__file__),
'fixture',
name,
)
class TestMapProxyConfCmd(object):
def setup(self):
self.dir = tempfile.mkdtemp()
def teardown(self):
if os.path.exists(self.dir):
shutil.rmtree(self.dir)
def tmp_filename(self, name):
return os.path.join(
self.dir,
name,
)
def test_cmd_no_args(self):
with capture() as (stdout, stderr):
assert config_command(['mapproxy-conf']) == 2
assert '--capabilities required' in stderr.getvalue()
def test_stdout_output(self):
with capture(bytes=True) as (stdout, stderr):
assert config_command(['mapproxy-conf', '--capabilities', filename('util-conf-wms-111-cap.xml')]) == 0
assert stdout.getvalue().startswith(b'# MapProxy configuration')
def test_test_cap_output_no_base(self):
with capture(bytes=True) as (stdout, stderr):
assert config_command(['mapproxy-conf',
'--capabilities', filename('util-conf-wms-111-cap.xml'),
'--output', self.tmp_filename('mapproxy.yaml'),
]) == 0
with open(self.tmp_filename('mapproxy.yaml'), 'rb') as f:
conf = yaml.load(f)
assert 'grids' not in conf
eq_(conf['sources'], {
'osm_roads_wms': {
'supported_srs': ['CRS:84', 'EPSG:25831', 'EPSG:25832', 'EPSG:25833', 'EPSG:31466', 'EPSG:31467', 'EPSG:31468', 'EPSG:3857', 'EPSG:4258', 'EPSG:4326', 'EPSG:900913'],
'req': {'layers': 'osm_roads', 'url': 'http://osm.omniscale.net/proxy/service?', 'transparent': True},
'type': 'wms',
'coverage': {'srs': 'EPSG:4326', 'bbox': [-180.0, -85.0511287798, 180.0, 85.0511287798]}
},
'osm_wms': {
'supported_srs': ['CRS:84', 'EPSG:25831', 'EPSG:25832', 'EPSG:25833', 'EPSG:31466', 'EPSG:31467', 'EPSG:31468', 'EPSG:3857', 'EPSG:4258', 'EPSG:4326', 'EPSG:900913'],
'req': {'layers': 'osm', 'url': 'http://osm.omniscale.net/proxy/service?', 'transparent': True},
'type': 'wms',
'coverage': {
'srs': 'EPSG:4326',
'bbox': [-180.0, -85.0511287798, 180.0, 85.0511287798],
},
},
})
eq_(conf['layers'], [{
'title': 'Omniscale OpenStreetMap WMS',
'layers': [
{
'name': 'osm',
'title': 'OpenStreetMap (complete map)',
'sources': ['osm_wms'],
},
{
'name': 'osm_roads',
'title': 'OpenStreetMap (streets only)',
'sources': ['osm_roads_wms'],
},
]
}])
eq_(len(conf['layers'][0]['layers']), 2)
def test_test_cap_output(self):
with capture(bytes=True) as (stdout, stderr):
assert config_command(['mapproxy-conf',
'--capabilities', filename('util-conf-wms-111-cap.xml'),
'--output', self.tmp_filename('mapproxy.yaml'),
'--base', filename('util-conf-base-grids.yaml'),
]) == 0
with open(self.tmp_filename('mapproxy.yaml'), 'rb') as f:
conf = yaml.load(f)
assert 'grids' not in conf
eq_(len(conf['sources']), 2)
eq_(conf['caches'], {
'osm_cache': {
'grids': ['webmercator', 'geodetic'],
'sources': ['osm_wms']
},
'osm_roads_cache': {
'grids': ['webmercator', 'geodetic'],
'sources': ['osm_roads_wms']
},
})
eq_(conf['layers'], [{
'title': 'Omniscale OpenStreetMap WMS',
'layers': [
{
'name': 'osm',
'title': 'OpenStreetMap (complete map)',
'sources': ['osm_cache'],
},
{
'name': 'osm_roads',
'title': 'OpenStreetMap (streets only)',
'sources': ['osm_roads_cache'],
},
]
}])
eq_(len(conf['layers'][0]['layers']), 2)
def test_overwrites(self):
with capture(bytes=True) as (stdout, stderr):
assert config_command(['mapproxy-conf',
'--capabilities', filename('util-conf-wms-111-cap.xml'),
'--output', self.tmp_filename('mapproxy.yaml'),
'--overwrite', filename('util-conf-overwrite.yaml'),
'--base', filename('util-conf-base-grids.yaml'),
]) == 0
with open(self.tmp_filename('mapproxy.yaml'), 'rb') as f:
conf = yaml.load(f)
assert 'grids' not in conf
eq_(len(conf['sources']), 2)
eq_(conf['sources'], {
'osm_roads_wms': {
'supported_srs': ['EPSG:3857'],
'req': {'layers': 'osm_roads', 'url': 'http://osm.omniscale.net/proxy/service?', 'transparent': True, 'param': 42},
'type': 'wms',
'coverage': {'srs': 'EPSG:4326', 'bbox': [0, 0, 90, 90]}
},
'osm_wms': {
'supported_srs': ['CRS:84', 'EPSG:25831', 'EPSG:25832', 'EPSG:25833', 'EPSG:31466', 'EPSG:31467', 'EPSG:31468', 'EPSG:3857', 'EPSG:4258', 'EPSG:4326', 'EPSG:900913'],
'req': {'layers': 'osm', 'url': 'http://osm.omniscale.net/proxy/service?', 'transparent': True, 'param': 42},
'type': 'wms',
'coverage': {
'srs': 'EPSG:4326',
'bbox': [-180.0, -85.0511287798, 180.0, 85.0511287798],
},
},
})
eq_(conf['caches'], {
'osm_cache': {
'grids': ['webmercator', 'geodetic'],
'sources': ['osm_wms'],
'cache': {
'type': 'sqlite'
},
},
'osm_roads_cache': {
'grids': ['webmercator'],
'sources': ['osm_roads_wms'],
'cache': {
'type': 'sqlite'
},
},
})
eq_(conf['layers'], [{
'title': 'Omniscale OpenStreetMap WMS',
'layers': [
{
'name': 'osm',
'title': 'OpenStreetMap (complete map)',
'sources': ['osm_cache'],
},
{
'name': 'osm_roads',
'title': 'OpenStreetMap (streets only)',
'sources': ['osm_roads_cache'],
},
]
}])
eq_(len(conf['layers'][0]['layers']), 2)
| 36.471366 | 186 | 0.460201 |
4198dcdb5b0a3ea4799160bba88094b1308ddf7d | 1,183 | py | Python | using-python-to-interact-with-the-operating-system/week-five/rearrange_test.py | veera-raju/google-it-automation-with-python | 19aaee57055c600b23a65392ca7471cdfca88500 | [
"MIT"
] | 164 | 2020-02-08T18:04:42.000Z | 2022-03-24T14:46:53.000Z | using-python-to-interact-with-the-operating-system/week-five/rearrange_test.py | Arunnoobmaster/google-it-automation-with-python | 19aaee57055c600b23a65392ca7471cdfca88500 | [
"MIT"
] | 12 | 2020-05-13T06:24:15.000Z | 2020-11-23T20:15:50.000Z | using-python-to-interact-with-the-operating-system/week-five/rearrange_test.py | Arunnoobmaster/google-it-automation-with-python | 19aaee57055c600b23a65392ca7471cdfca88500 | [
"MIT"
] | 195 | 2020-02-10T01:46:34.000Z | 2022-03-24T14:46:22.000Z | #!/usr/bin/env python3
# Writing Unit Tests in Python
# from keyword imports a function from a script in the python3 interpreter
# the function can be called without having to write the module name each time we want to call it
from rearrange import rearrange_name
# unittest module includes classes and methods for creating unit tests
import unittest
# Include the class that we want to inherit from in the parentheses
# TestRearrange class inherits from TestCase
class TestRearrange(unittest.TestCase):
def test_basic(self):
testcase = "Lovelace, Ada"
expected = "Ada Lovelace"
self.assertEqual(rearrange_name(testcase), expected)
# test for an edge case
def test_empty(self):
testcase = ""
expected = ""
self.assertEqual(rearrange_name(testcase), expected)
def test_double_name(self):
testcase = "Hopper, Grace M."
expected = "Grace M. Hopper"
self.assertEqual(rearrange_name(testcase), expected)
def test_one_name(self):
testcase = "Voltaire"
expected = "Voltaire"
self.assertEqual(rearrange_name(testcase), expected)
# Runs the test
unittest.main() | 33.8 | 97 | 0.704142 |
652223b710138d3365f7344a363457ddfc87cb28 | 8,323 | py | Python | examples/hotel_ads/add_hotel_ad.py | bjagadev17/google-ads-python | ee2c059498d5679a0d1d9011f3795324439fad7c | [
"Apache-2.0"
] | null | null | null | examples/hotel_ads/add_hotel_ad.py | bjagadev17/google-ads-python | ee2c059498d5679a0d1d9011f3795324439fad7c | [
"Apache-2.0"
] | null | null | null | examples/hotel_ads/add_hotel_ad.py | bjagadev17/google-ads-python | ee2c059498d5679a0d1d9011f3795324439fad7c | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example adds a hotel campaign, ad group, and ad group ad.
Prerequisite: You need to have access to the Hotel Ads Center, which can be
granted during integration with Google Hotels. The integration instructions can
be found at:
https://support.google.com/hotelprices/answer/6101897.
"""
import argparse
import sys
import uuid
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def main(
client, customer_id, hotel_center_account_id, cpc_bid_ceiling_micro_amount
):
budget_resource_name = _add_budget(client, customer_id)
campaign_resource_name = _add_hotel_campaign(
client,
customer_id,
budget_resource_name,
hotel_center_account_id,
cpc_bid_ceiling_micro_amount,
)
ad_group_resource_name = _add_hotel_ad_group(
client, customer_id, campaign_resource_name
)
_add_hotel_ad(client, customer_id, ad_group_resource_name)
def _add_budget(client, customer_id):
campaign_budget_service = client.get_service("CampaignBudgetService")
# Create a budget, which can be shared by multiple campaigns.
campaign_budget_operation = client.get_type("CampaignBudgetOperation")
campaign_budget = campaign_budget_operation.create
campaign_budget.name = f"Interplanetary Budget {uuid.uuid4()}"
campaign_budget.delivery_method = client.get_type(
"BudgetDeliveryMethodEnum"
).BudgetDeliveryMethod.STANDARD
campaign_budget.amount_micros = 500000
# Add budget.
campaign_budget_response = campaign_budget_service.mutate_campaign_budgets(
customer_id=customer_id, operations=[campaign_budget_operation]
)
budget_resource_name = campaign_budget_response.results[0].resource_name
print(f"Created budget with resource name '{budget_resource_name}'.")
return budget_resource_name
# [START add_hotel_ad_3]
def _add_hotel_ad(client, customer_id, ad_group_resource_name):
ad_group_ad_service = client.get_service("AdGroupAdService")
# Creates a new ad group ad and sets the hotel ad to it.
ad_group_ad_operation = client.get_type("AdGroupAdOperation")
ad_group_ad = ad_group_ad_operation.create
ad_group_ad.ad_group = ad_group_resource_name
# Set the ad group ad to enabled. Setting this to paused will cause an error
# for hotel campaigns. For hotels pausing should happen at either the ad group or
# campaign level.
ad_group_ad.status = client.get_type(
"AdGroupAdStatusEnum"
).AdGroupAdStatus.ENABLED
client.copy_from(ad_group_ad.ad.hotel_ad, client.get_type("HotelAdInfo"))
# Add the ad group ad.
ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads(
customer_id=customer_id, operations=[ad_group_ad_operation]
)
ad_group_ad_resource_name = ad_group_ad_response.results[0].resource_name
print(f"Created hotel ad with resource name '{ad_group_ad_resource_name}'.")
return ad_group_resource_name
# [END add_hotel_ad_3]
# [START add_hotel_ad_2]
def _add_hotel_ad_group(client, customer_id, campaign_resource_name):
ad_group_service = client.get_service("AdGroupService")
# Create ad group.
ad_group_operation = client.get_type("AdGroupOperation")
ad_group = ad_group_operation.create
ad_group.name = f"Earth to Mars cruise {uuid.uuid4()}"
ad_group.status = client.get_type("AdGroupStatusEnum").AdGroupStatus.ENABLED
ad_group.campaign = campaign_resource_name
# Sets the ad group type to HOTEL_ADS. This cannot be set to other types.
ad_group.type_ = client.get_type("AdGroupTypeEnum").AdGroupType.HOTEL_ADS
ad_group.cpc_bid_micros = 10000000
# Add the ad group.
ad_group_response = ad_group_service.mutate_ad_groups(
customer_id=customer_id, operations=[ad_group_operation]
)
ad_group_resource_name = ad_group_response.results[0].resource_name
print(
"Added a hotel ad group with resource name '{ad_group_resource_name}'."
)
return ad_group_resource_name
# [END add_hotel_ad_2]
# [START add_hotel_ad]
def _add_hotel_campaign(
client,
customer_id,
budget_resource_name,
hotel_center_account_id,
cpc_bid_ceiling_micro_amount,
):
campaign_service = client.get_service("CampaignService")
# [START add_hotel_ad_1]
# Create campaign.
campaign_operation = client.get_type("CampaignOperation")
campaign = campaign_operation.create
campaign.name = f"Interplanetary Cruise Campaign {uuid.uuid4()}"
# Configures settings related to hotel campaigns including advertising
# channel type and hotel setting info.
campaign.advertising_channel_type = client.get_type(
"AdvertisingChannelTypeEnum"
).AdvertisingChannelType.HOTEL
campaign.hotel_setting.hotel_center_id = hotel_center_account_id
# Recommendation: Set the campaign to PAUSED when creating it to prevent the
# ads from immediately serving. Set to ENABLED once you've added targeting
# and the ads are ready to serve.
campaign.status = client.get_type(
"CampaignStatusEnum"
).CampaignStatus.PAUSED
# Set the bidding strategy to PercentCpc. Only Manual CPC and Percent CPC
# can be used for hotel campaigns.
campaign.percent_cpc.cpc_bid_ceiling_micros = cpc_bid_ceiling_micro_amount
# Sets the budget.
campaign.campaign_budget = budget_resource_name
# Set the campaign network options. Only Google Search is allowed for hotel
# campaigns.
campaign.network_settings.target_google_search = True
# [END add_hotel_ad_1]
# Add the campaign.
campaign_response = campaign_service.mutate_campaigns(
customer_id=customer_id, operations=[campaign_operation]
)
campaign_resource_name = campaign_response.results[0].resource_name
print(
"Added a hotel campaign with resource name '{campaign_resource_name}'."
)
return campaign_resource_name
# [END add_hotel_ad]
if __name__ == "__main__":
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
googleads_client = GoogleAdsClient.load_from_storage(version="v7")
parser = argparse.ArgumentParser(
description=(
"Adds an expanded text ad to the specified ad group ID, "
"for the given customer ID."
)
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
"-c",
"--customer_id",
type=str,
required=True,
help="The Google Ads customer ID.",
)
parser.add_argument(
"-b",
"--cpc_bid_ceiling_micro_amount",
type=int,
required=True,
help=("The cpc bid ceiling micro amount for the hotel campaign."),
)
parser.add_argument(
"-a",
"--hotel_center_account_id",
type=int,
required=True,
help="The hotel center account ID.",
)
args = parser.parse_args()
try:
main(
googleads_client,
args.customer_id,
args.hotel_center_account_id,
args.cpc_bid_ceiling_micro_amount,
)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
| 34.110656 | 86 | 0.721855 |
e92cdbe8e29c8c0dcb05e73f8f175ffeacedbd31 | 3,957 | py | Python | T1A_informed_search/game.py | allanmoreira/inteligencia_artificial | ee29a881be7fdb9dd150d08dbf9bb9e49f09cb71 | [
"Apache-2.0"
] | null | null | null | T1A_informed_search/game.py | allanmoreira/inteligencia_artificial | ee29a881be7fdb9dd150d08dbf9bb9e49f09cb71 | [
"Apache-2.0"
] | 1 | 2017-08-03T15:53:01.000Z | 2017-08-03T15:55:02.000Z | T1A_informed_search/game.py | allanmoreira/inteligencia_artificial | ee29a881be7fdb9dd150d08dbf9bb9e49f09cb71 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Four spaces as indentation [no tabs]
import sys
import pygame
from pygame.locals import (QUIT, KEYDOWN, K_SPACE, K_ESCAPE)
from common import *
from player import *
# ==========================================
# Game
# ==========================================
class Game:
# ------------------------------------------
# Initialize
# ------------------------------------------
def __init__(self, map_name):
# Setup
self.map = read_map(map_name)
pygame.init()
screen = pygame.display.set_mode((TILE_WIDTH * self.map.width, TILE_HEIGHT * self.map.height))
pygame.display.set_caption("[T1a] A Link to the Path")
background = pygame.Surface(screen.get_size()).convert()
self.load_tileset(TILESET, 3, 1)
self.draw_map(background)
self.player = Player(self.map, self.load_image(PLAYER), 4, 8 / ZOOM)
# Loop
clock = pygame.time.Clock()
game_over = False
while not game_over:
screen.blit(background, (0, 0))
self.player.update(screen)
pygame.display.flip()
clock.tick(FPS)
for event in pygame.event.get():
if event.type == QUIT:
game_over = True
elif event.type == KEYDOWN:
if event.key == K_SPACE: # Reset this map
self.player.setup(self.map)
elif event.key == K_ESCAPE: # Load map
map_name = raw_input('Load map: ')
self.map = read_map(map_name)
if screen.get_size() != (TILE_WIDTH * self.map.width, TILE_HEIGHT * self.map.height):
del screen
del background
screen = pygame.display.set_mode((TILE_WIDTH * self.map.width, TILE_HEIGHT * self.map.height))
background = pygame.Surface(screen.get_size()).convert()
self.draw_map(background)
self.player.setup(self.map)
# ------------------------------------------
# Draw map
# ------------------------------------------
def draw_map(self, surface):
map_y = 0
for y in range(self.map.height):
map_x = 0
for x in range(self.map.width):
tile = self.map.data[y][x]
if tile == TILE_CLEAR or tile == TILE_CLOSED or tile == TILE_GOAL:
surface.blit(self.tileset[tile], (map_x, map_y))
else:
raise Exception("Unknown tile", tile, (map_x, map_y))
map_x += TILE_WIDTH
map_y += TILE_HEIGHT
# ------------------------------------------
# Load image
# ------------------------------------------
def load_image(self, filename):
img = pygame.image.load(os.path.join(PATH, "sprites", filename)).convert()
img.set_colorkey((0,128,128))
if ZOOM > 1:
return pygame.transform.scale(img, (img.get_width() * ZOOM, img.get_height() * ZOOM))
return img
# ------------------------------------------
# Load tileset
# ------------------------------------------
def load_tileset(self, filename, width, height):
image = self.load_image(filename)
self.tileset = []
tile_y = 0
for y in range(height):
tile_x = 0
for x in range(width):
self.tileset.append(image.subsurface((tile_x, tile_y, TILE_WIDTH, TILE_HEIGHT)))
tile_x += TILE_WIDTH
tile_y += TILE_HEIGHT
# ==========================================
# Main
# ==========================================
if __name__ == "__main__":
if len(sys.argv) == 2:
map_name = sys.argv[1]
else:
map_name = DEFAULT_MAP
print "Loading map: " + map_name
Game(map_name) | 37.330189 | 122 | 0.466262 |
53093944bc036c38e2e5d9b57b50bf3d0f8322b6 | 2,783 | py | Python | scripts/run_evaluation.py | huggingface/hf_benchmarks | 2a4367b003d4e363a7e3c6485c4a6bdbfd8f95f0 | [
"Apache-2.0"
] | null | null | null | scripts/run_evaluation.py | huggingface/hf_benchmarks | 2a4367b003d4e363a7e3c6485c4a6bdbfd8f95f0 | [
"Apache-2.0"
] | 1 | 2022-03-30T20:36:55.000Z | 2022-03-30T20:36:55.000Z | scripts/run_evaluation.py | huggingface/hf_benchmarks | 2a4367b003d4e363a7e3c6485c4a6bdbfd8f95f0 | [
"Apache-2.0"
] | null | null | null | import os
import re
import subprocess
from pathlib import Path
import pandas as pd
import requests
import typer
from dotenv import load_dotenv
from hf_benchmarks import extract_tags, get_benchmark_repos
if Path(".env").is_file():
load_dotenv(".env")
auth_token = os.getenv("HF_HUB_TOKEN")
app = typer.Typer()
@app.command()
def run(benchmark: str, evaluation_dataset: str, end_date: str, previous_days: int):
start_date = pd.to_datetime(end_date) - pd.Timedelta(days=previous_days)
typer.echo(f"Evaluating submissions on benchmark {benchmark} from {start_date} to {end_date}")
submissions = get_benchmark_repos(benchmark, use_auth_token=auth_token, start_date=start_date, end_date=end_date)
typer.echo(f"Found {len(submissions)} submissions to evaluate on benchmark {benchmark}")
header = {"Authorization": f"Bearer {auth_token}"}
for submission in submissions:
submission_dataset = submission["id"]
typer.echo(f"Evaluating submission {submission_dataset}")
response = requests.get(
f"http://huggingface.co/api/datasets/{submission_dataset}?full=true",
headers=header,
)
data = response.json()
# Extract submission name from YAML tags
tags = extract_tags(data)
# Extract submission timestamp and convert to Unix epoch in nanoseconds
timestamp = pd.to_datetime(data["lastModified"])
submission_timestamp = int(timestamp.timestamp() * 10**9)
# Use the user-generated submission name, Git commit SHA and timestamp to create submission ID
submission_id = tags["submission_name"] + "__" + data["sha"] + "__" + str(submission_timestamp)
process = subprocess.run(
[
"autonlp",
"benchmark",
"--eval_name",
f"{benchmark}",
"--dataset",
f"{evaluation_dataset}",
"--submission",
f"{submission_dataset}",
"--submission_id",
f"{submission_id}",
],
stdout=subprocess.PIPE,
)
if process.returncode == -1:
typer.echo(f"Error launching evaluation job for submission {submission_dataset} on {benchmark} benchmark!")
else:
try:
match_job_id = re.search(r"# (\d+)", process.stdout.decode("utf-8"))
job_id = match_job_id.group(1)
typer.echo(
f"Successfully launched evaluation job #{job_id} for submission {submission_dataset} on {benchmark} benchmark!"
)
except Exception as e:
typer.echo(f"Could not extract AutoNLP job ID due to error: {e}")
if __name__ == "__main__":
app()
| 37.608108 | 131 | 0.623787 |
294bd4ecd98bc334c4f74da76d975454d6d89ef2 | 13,053 | py | Python | sdk/python/pulumi_azure_nextgen/network/v20181001/inbound_nat_rule.py | pulumi/pulumi-azure-nextgen | 452736b0a1cf584c2d4c04666e017af6e9b2c15c | [
"Apache-2.0"
] | 31 | 2020-09-21T09:41:01.000Z | 2021-02-26T13:21:59.000Z | sdk/python/pulumi_azure_nextgen/network/v20181001/inbound_nat_rule.py | pulumi/pulumi-azure-nextgen | 452736b0a1cf584c2d4c04666e017af6e9b2c15c | [
"Apache-2.0"
] | 231 | 2020-09-21T09:38:45.000Z | 2021-03-01T11:16:03.000Z | sdk/python/pulumi_azure_nextgen/network/v20181001/inbound_nat_rule.py | pulumi/pulumi-azure-nextgen | 452736b0a1cf584c2d4c04666e017af6e9b2c15c | [
"Apache-2.0"
] | 4 | 2020-09-29T14:14:59.000Z | 2021-02-10T20:38:16.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
from ._enums import *
from ._inputs import *
__all__ = ['InboundNatRule']
class InboundNatRule(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
backend_port: Optional[pulumi.Input[int]] = None,
enable_floating_ip: Optional[pulumi.Input[bool]] = None,
enable_tcp_reset: Optional[pulumi.Input[bool]] = None,
etag: Optional[pulumi.Input[str]] = None,
frontend_ip_configuration: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None,
frontend_port: Optional[pulumi.Input[int]] = None,
id: Optional[pulumi.Input[str]] = None,
idle_timeout_in_minutes: Optional[pulumi.Input[int]] = None,
inbound_nat_rule_name: Optional[pulumi.Input[str]] = None,
load_balancer_name: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
protocol: Optional[pulumi.Input[Union[str, 'TransportProtocol']]] = None,
provisioning_state: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Inbound NAT rule of the load balancer.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[int] backend_port: The port used for the internal endpoint. Acceptable values range from 1 to 65535.
:param pulumi.Input[bool] enable_floating_ip: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint.
:param pulumi.Input[bool] enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP.
:param pulumi.Input[str] etag: A unique read-only string that changes whenever the resource is updated.
:param pulumi.Input[pulumi.InputType['SubResourceArgs']] frontend_ip_configuration: A reference to frontend IP addresses.
:param pulumi.Input[int] frontend_port: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534.
:param pulumi.Input[str] id: Resource ID.
:param pulumi.Input[int] idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP.
:param pulumi.Input[str] inbound_nat_rule_name: The name of the inbound nat rule.
:param pulumi.Input[str] load_balancer_name: The name of the load balancer.
:param pulumi.Input[str] name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource.
:param pulumi.Input[Union[str, 'TransportProtocol']] protocol: The transport protocol for the endpoint. Possible values are 'Udp' or 'Tcp' or 'All'.
:param pulumi.Input[str] provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['backend_port'] = backend_port
__props__['enable_floating_ip'] = enable_floating_ip
__props__['enable_tcp_reset'] = enable_tcp_reset
__props__['etag'] = etag
__props__['frontend_ip_configuration'] = frontend_ip_configuration
__props__['frontend_port'] = frontend_port
__props__['id'] = id
__props__['idle_timeout_in_minutes'] = idle_timeout_in_minutes
__props__['inbound_nat_rule_name'] = inbound_nat_rule_name
if load_balancer_name is None and not opts.urn:
raise TypeError("Missing required property 'load_balancer_name'")
__props__['load_balancer_name'] = load_balancer_name
__props__['name'] = name
__props__['protocol'] = protocol
__props__['provisioning_state'] = provisioning_state
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['backend_ip_configuration'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/latest:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20170601:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20170801:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20170901:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20171001:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20171101:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20180101:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20180201:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20180401:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20180601:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20180701:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20180801:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20181101:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20181201:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20190201:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20190401:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20190601:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20190701:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20190801:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20190901:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20191101:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20191201:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20200301:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20200401:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20200501:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20200601:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20200701:InboundNatRule"), pulumi.Alias(type_="azure-nextgen:network/v20200801:InboundNatRule")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(InboundNatRule, __self__).__init__(
'azure-nextgen:network/v20181001:InboundNatRule',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'InboundNatRule':
"""
Get an existing InboundNatRule resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
return InboundNatRule(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="backendIPConfiguration")
def backend_ip_configuration(self) -> pulumi.Output['outputs.NetworkInterfaceIPConfigurationResponse']:
"""
A reference to a private IP address defined on a network interface of a VM. Traffic sent to the frontend port of each of the frontend IP configurations is forwarded to the backend IP.
"""
return pulumi.get(self, "backend_ip_configuration")
@property
@pulumi.getter(name="backendPort")
def backend_port(self) -> pulumi.Output[Optional[int]]:
"""
The port used for the internal endpoint. Acceptable values range from 1 to 65535.
"""
return pulumi.get(self, "backend_port")
@property
@pulumi.getter(name="enableFloatingIP")
def enable_floating_ip(self) -> pulumi.Output[Optional[bool]]:
"""
Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint.
"""
return pulumi.get(self, "enable_floating_ip")
@property
@pulumi.getter(name="enableTcpReset")
def enable_tcp_reset(self) -> pulumi.Output[Optional[bool]]:
"""
Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP.
"""
return pulumi.get(self, "enable_tcp_reset")
@property
@pulumi.getter
def etag(self) -> pulumi.Output[Optional[str]]:
"""
A unique read-only string that changes whenever the resource is updated.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter(name="frontendIPConfiguration")
def frontend_ip_configuration(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]:
"""
A reference to frontend IP addresses.
"""
return pulumi.get(self, "frontend_ip_configuration")
@property
@pulumi.getter(name="frontendPort")
def frontend_port(self) -> pulumi.Output[Optional[int]]:
"""
The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534.
"""
return pulumi.get(self, "frontend_port")
@property
@pulumi.getter(name="idleTimeoutInMinutes")
def idle_timeout_in_minutes(self) -> pulumi.Output[Optional[int]]:
"""
The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP.
"""
return pulumi.get(self, "idle_timeout_in_minutes")
@property
@pulumi.getter
def name(self) -> pulumi.Output[Optional[str]]:
"""
Gets name of the resource that is unique within a resource group. This name can be used to access the resource.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def protocol(self) -> pulumi.Output[Optional[str]]:
"""
The transport protocol for the endpoint. Possible values are 'Udp' or 'Tcp' or 'All'.
"""
return pulumi.get(self, "protocol")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[Optional[str]]:
"""
Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
"""
return pulumi.get(self, "provisioning_state")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| 60.995327 | 2,070 | 0.698537 |
e7159fea3e4b612f0fd6a4c0a010a4eb7c398877 | 583 | py | Python | products/migrations/0002_auto_20190725_1623.py | destodasoftware/kately_api | 89e4e80a93ebf8e5d2f2981d108ce5efde75d0dd | [
"MIT"
] | null | null | null | products/migrations/0002_auto_20190725_1623.py | destodasoftware/kately_api | 89e4e80a93ebf8e5d2f2981d108ce5efde75d0dd | [
"MIT"
] | 10 | 2019-12-04T23:52:31.000Z | 2022-02-10T08:34:15.000Z | products/migrations/0002_auto_20190725_1623.py | destodasoftware/kately_api | 89e4e80a93ebf8e5d2f2981d108ce5efde75d0dd | [
"MIT"
] | null | null | null | # Generated by Django 2.2.3 on 2019-07-25 16:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='product',
name='minimum_stock',
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name='product',
name='stock',
field=models.PositiveIntegerField(default=0),
preserve_default=False,
),
]
| 23.32 | 57 | 0.57976 |
d0b1797b4850ff39c005cf88d69f6c0c318a9f5d | 25,191 | py | Python | pymatgen/analysis/ewald.py | dynikon/pymatgen | 6183f479e30a69bf5b94a0a7e21a3e810b40f02d | [
"MIT"
] | 6 | 2015-02-06T08:27:09.000Z | 2021-02-28T14:42:52.000Z | pymatgen/analysis/ewald.py | dynikon/pymatgen | 6183f479e30a69bf5b94a0a7e21a3e810b40f02d | [
"MIT"
] | null | null | null | pymatgen/analysis/ewald.py | dynikon/pymatgen | 6183f479e30a69bf5b94a0a7e21a3e810b40f02d | [
"MIT"
] | 3 | 2015-10-21T08:04:40.000Z | 2019-03-19T23:11:15.000Z | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides classes for calculating the ewald sum of a structure.
"""
from math import pi, sqrt, log
from datetime import datetime
from copy import deepcopy, copy
from warnings import warn
import bisect
import numpy as np
from scipy.special import erfc, comb
import scipy.constants as constants
__author__ = "Shyue Ping Ong, William Davidson Richard"
__copyright__ = "Copyright 2011, The Materials Project"
__credits__ = "Christopher Fischer"
__version__ = "1.0"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__status__ = "Production"
__date__ = "Aug 1 2012"
class EwaldSummation:
"""
Calculates the electrostatic energy of a periodic array of charges using
the Ewald technique.
Ref: http://www.ee.duke.edu/~ayt/ewaldpaper/ewaldpaper.html
This matrix can be used to do fast calculations of ewald sums after species
removal.
E = E_recip + E_real + E_point
Atomic units used in the code, then converted to eV.
"""
# Converts unit of q*q/r into eV
CONV_FACT = 1e10 * constants.e / (4 * pi * constants.epsilon_0)
def __init__(self, structure, real_space_cut=None, recip_space_cut=None,
eta=None, acc_factor=12.0, w=1 / sqrt(2), compute_forces=False):
"""
Initializes and calculates the Ewald sum. Default convergence
parameters have been specified, but you can override them if you wish.
Args:
structure (Structure): Input structure that must have proper
Specie on all sites, i.e. Element with oxidation state. Use
Structure.add_oxidation_state... for example.
real_space_cut (float): Real space cutoff radius dictating how
many terms are used in the real space sum. Defaults to None,
which means determine automagically using the formula given
in gulp 3.1 documentation.
recip_space_cut (float): Reciprocal space cutoff radius.
Defaults to None, which means determine automagically using
the formula given in gulp 3.1 documentation.
eta (float): The screening parameter. Defaults to None, which means
determine automatically.
acc_factor (float): No. of significant figures each sum is
converged to.
w (float): Weight parameter, w, has been included that represents
the relative computational expense of calculating a term in
real and reciprocal space. Default of 0.7 reproduces result
similar to GULP 4.2. This has little effect on the total
energy, but may influence speed of computation in large
systems. Note that this parameter is used only when the
cutoffs are set to None.
compute_forces (bool): Whether to compute forces. False by
default since it is usually not needed.
"""
self._s = structure
self._charged = abs(structure.charge) > 1e-8
self._vol = structure.volume
self._compute_forces = compute_forces
self._acc_factor = acc_factor
# set screening length
self._eta = eta if eta \
else (len(structure) * w / (self._vol ** 2)) ** (1 / 3) * pi
self._sqrt_eta = sqrt(self._eta)
# acc factor used to automatically determine the optimal real and
# reciprocal space cutoff radii
self._accf = sqrt(log(10 ** acc_factor))
self._rmax = real_space_cut if real_space_cut \
else self._accf / self._sqrt_eta
self._gmax = recip_space_cut if recip_space_cut \
else 2 * self._sqrt_eta * self._accf
# The next few lines pre-compute certain quantities and store them.
# Ewald summation is rather expensive, and these shortcuts are
# necessary to obtain several factors of improvement in speedup.
self._oxi_states = [compute_average_oxidation_state(site)
for site in structure]
self._coords = np.array(self._s.cart_coords)
# Now we call the relevant private methods to calculate the reciprocal
# and real space terms.
(self._recip, recip_forces) = self._calc_recip()
(self._real, self._point, real_point_forces) = \
self._calc_real_and_point()
if self._compute_forces:
self._forces = recip_forces + real_point_forces
# Compute the correction for a charged cell
self._charged_cell_energy = - EwaldSummation.CONV_FACT / 2 * np.pi / \
structure.volume / self._eta * structure.charge ** 2
def compute_partial_energy(self, removed_indices):
"""
Gives total ewald energy for certain sites being removed, i.e. zeroed
out.
"""
total_energy_matrix = self.total_energy_matrix.copy()
for i in removed_indices:
total_energy_matrix[i, :] = 0
total_energy_matrix[:, i] = 0
return sum(sum(total_energy_matrix))
def compute_sub_structure(self, sub_structure, tol=1e-3):
"""
Gives total ewald energy for an sub structure in the same
lattice. The sub_structure must be a subset of the original
structure, with possible different charges.
Args:
substructure (Structure): Substructure to compute Ewald sum for.
tol (float): Tolerance for site matching in fractional coordinates.
Returns:
Ewald sum of substructure.
"""
total_energy_matrix = self.total_energy_matrix.copy()
def find_match(site):
for test_site in sub_structure:
frac_diff = abs(np.array(site.frac_coords)
- np.array(test_site.frac_coords)) % 1
frac_diff = [abs(a) < tol or abs(a) > 1 - tol
for a in frac_diff]
if all(frac_diff):
return test_site
return None
matches = []
for i, site in enumerate(self._s):
matching_site = find_match(site)
if matching_site:
new_charge = compute_average_oxidation_state(matching_site)
old_charge = self._oxi_states[i]
scaling_factor = new_charge / old_charge
matches.append(matching_site)
else:
scaling_factor = 0
total_energy_matrix[i, :] *= scaling_factor
total_energy_matrix[:, i] *= scaling_factor
if len(matches) != len(sub_structure):
output = ["Missing sites."]
for site in sub_structure:
if site not in matches:
output.append("unmatched = {}".format(site))
raise ValueError("\n".join(output))
return sum(sum(total_energy_matrix))
@property
def reciprocal_space_energy(self):
"""
The reciprocal space energy.
"""
return sum(sum(self._recip))
@property
def reciprocal_space_energy_matrix(self):
"""
The reciprocal space energy matrix. Each matrix element (i, j)
corresponds to the interaction energy between site i and site j in
reciprocal space.
"""
return self._recip
@property
def real_space_energy(self):
"""
The real space space energy.
"""
return sum(sum(self._real))
@property
def real_space_energy_matrix(self):
"""
The real space energy matrix. Each matrix element (i, j) corresponds to
the interaction energy between site i and site j in real space.
"""
return self._real
@property
def point_energy(self):
"""
The point energy.
"""
return sum(self._point)
@property
def point_energy_matrix(self):
"""
The point space matrix. A diagonal matrix with the point terms for each
site in the diagonal elements.
"""
return self._point
@property
def total_energy(self):
"""
The total energy.
"""
return sum(sum(self._recip)) + sum(sum(self._real)) + sum(self._point) + self._charged_cell_energy
@property
def total_energy_matrix(self):
"""
The total energy matrix. Each matrix element (i, j) corresponds to the
total interaction energy between site i and site j.
Note that this does not include the charged-cell energy, which is only important
when the simulation cell is not charge balanced.
"""
totalenergy = self._recip + self._real
for i in range(len(self._point)):
totalenergy[i, i] += self._point[i]
return totalenergy
@property
def forces(self):
"""
The forces on each site as a Nx3 matrix. Each row corresponds to a
site.
"""
if not self._compute_forces:
raise AttributeError(
"Forces are available only if compute_forces is True!")
return self._forces
def get_site_energy(self, site_index):
"""Compute the energy for a single site in the structure
Args:
site_index (int): Index of site
ReturnS:
(float) - Energy of that site"""
if self._charged:
warn('Per atom energies for charged structures not supported in EwaldSummation')
return np.sum(self._recip[:, site_index]) + np.sum(self._real[:, site_index]) + self._point[site_index]
def _calc_recip(self):
"""
Perform the reciprocal space summation. Calculates the quantity
E_recip = 1/(2PiV) sum_{G < Gmax} exp(-(G.G/4/eta))/(G.G) S(G)S(-G)
where
S(G) = sum_{k=1,N} q_k exp(-i G.r_k)
S(G)S(-G) = |S(G)|**2
This method is heavily vectorized to utilize numpy's C backend for
speed.
"""
numsites = self._s.num_sites
prefactor = 2 * pi / self._vol
erecip = np.zeros((numsites, numsites), dtype=np.float)
forces = np.zeros((numsites, 3), dtype=np.float)
coords = self._coords
rcp_latt = self._s.lattice.reciprocal_lattice
recip_nn = rcp_latt.get_points_in_sphere([[0, 0, 0]], [0, 0, 0],
self._gmax)
frac_coords = [fcoords for (fcoords, dist, i, img) in recip_nn if dist != 0]
gs = rcp_latt.get_cartesian_coords(frac_coords)
g2s = np.sum(gs ** 2, 1)
expvals = np.exp(-g2s / (4 * self._eta))
grs = np.sum(gs[:, None] * coords[None, :], 2)
oxistates = np.array(self._oxi_states)
# create array where q_2[i,j] is qi * qj
qiqj = oxistates[None, :] * oxistates[:, None]
# calculate the structure factor
sreals = np.sum(oxistates[None, :] * np.cos(grs), 1)
simags = np.sum(oxistates[None, :] * np.sin(grs), 1)
for g, g2, gr, expval, sreal, simag in zip(gs, g2s, grs, expvals,
sreals, simags):
# Uses the identity sin(x)+cos(x) = 2**0.5 sin(x + pi/4)
m = (gr[None, :] + pi / 4) - gr[:, None]
np.sin(m, m)
m *= expval / g2
erecip += m
if self._compute_forces:
pref = 2 * expval / g2 * oxistates
factor = prefactor * pref * (
sreal * np.sin(gr) - simag * np.cos(gr))
forces += factor[:, None] * g[None, :]
forces *= EwaldSummation.CONV_FACT
erecip *= prefactor * EwaldSummation.CONV_FACT * qiqj * 2 ** 0.5
return erecip, forces
def _calc_real_and_point(self):
"""
Determines the self energy -(eta/pi)**(1/2) * sum_{i=1}^{N} q_i**2
"""
fcoords = self._s.frac_coords
forcepf = 2.0 * self._sqrt_eta / sqrt(pi)
coords = self._coords
numsites = self._s.num_sites
ereal = np.empty((numsites, numsites), dtype=np.float)
forces = np.zeros((numsites, 3), dtype=np.float)
qs = np.array(self._oxi_states)
epoint = - qs ** 2 * sqrt(self._eta / pi)
for i in range(numsites):
nfcoords, rij, js, _ = self._s.lattice.get_points_in_sphere(fcoords,
coords[i], self._rmax, zip_results=False)
# remove the rii term
inds = rij > 1e-8
js = js[inds]
rij = rij[inds]
nfcoords = nfcoords[inds]
qi = qs[i]
qj = qs[js]
erfcval = erfc(self._sqrt_eta * rij)
new_ereals = erfcval * qi * qj / rij
# insert new_ereals
for k in range(numsites):
ereal[k, i] = np.sum(new_ereals[js == k])
if self._compute_forces:
nccoords = self._s.lattice.get_cartesian_coords(nfcoords)
fijpf = qj / rij ** 3 * (erfcval + forcepf * rij *
np.exp(-self._eta * rij ** 2))
forces[i] += np.sum(np.expand_dims(fijpf, 1) *
(np.array([coords[i]]) - nccoords) *
qi * EwaldSummation.CONV_FACT, axis=0)
ereal *= 0.5 * EwaldSummation.CONV_FACT
epoint *= EwaldSummation.CONV_FACT
return ereal, epoint, forces
@property
def eta(self):
"""
Returns: eta value used in Ewald summation.
"""
return self._eta
def __str__(self):
if self._compute_forces:
output = ["Real = " + str(self.real_space_energy),
"Reciprocal = " + str(self.reciprocal_space_energy),
"Point = " + str(self.point_energy),
"Total = " + str(self.total_energy),
"Forces:\n" + str(self.forces)
]
else:
output = ["Real = " + str(self.real_space_energy),
"Reciprocal = " + str(self.reciprocal_space_energy),
"Point = " + str(self.point_energy),
"Total = " + str(self.total_energy),
"Forces were not computed"]
return "\n".join(output)
class EwaldMinimizer:
"""
This class determines the manipulations that will minimize an ewald matrix,
given a list of possible manipulations. This class does not perform the
manipulations on a structure, but will return the list of manipulations
that should be done on one to produce the minimal structure. It returns the
manipulations for the n lowest energy orderings. This class should be used
to perform fractional species substitution or fractional species removal to
produce a new structure. These manipulations create large numbers of
candidate structures, and this class can be used to pick out those with the
lowest ewald sum.
An alternative (possibly more intuitive) interface to this class is the
order disordered structure transformation.
Author - Will Richards
"""
ALGO_FAST = 0
ALGO_COMPLETE = 1
ALGO_BEST_FIRST = 2
"""
ALGO_TIME_LIMIT: Slowly increases the speed (with the cost of decreasing
accuracy) as the minimizer runs. Attempts to limit the run time to
approximately 30 minutes.
"""
ALGO_TIME_LIMIT = 3
def __init__(self, matrix, m_list, num_to_return=1, algo=ALGO_FAST):
"""
Args:
matrix: A matrix of the ewald sum interaction energies. This is stored
in the class as a diagonally symmetric array and so
self._matrix will not be the same as the input matrix.
m_list: list of manipulations. each item is of the form
(multiplication fraction, number_of_indices, indices, species)
These are sorted such that the first manipulation contains the
most permutations. this is actually evaluated last in the
recursion since I'm using pop.
num_to_return: The minimizer will find the number_returned lowest
energy structures. This is likely to return a number of duplicate
structures so it may be necessary to overestimate and then
remove the duplicates later. (duplicate checking in this
process is extremely expensive)
"""
# Setup and checking of inputs
self._matrix = copy(matrix)
# Make the matrix diagonally symmetric (so matrix[i,:] == matrix[:,j])
for i in range(len(self._matrix)):
for j in range(i, len(self._matrix)):
value = (self._matrix[i, j] + self._matrix[j, i]) / 2
self._matrix[i, j] = value
self._matrix[j, i] = value
# sort the m_list based on number of permutations
self._m_list = sorted(m_list, key=lambda x: comb(len(x[2]), x[1]),
reverse=True)
for mlist in self._m_list:
if mlist[0] > 1:
raise ValueError('multiplication fractions must be <= 1')
self._current_minimum = float('inf')
self._num_to_return = num_to_return
self._algo = algo
if algo == EwaldMinimizer.ALGO_COMPLETE:
raise NotImplementedError('Complete algo not yet implemented for '
'EwaldMinimizer')
self._output_lists = []
# Tag that the recurse function looks at at each level. If a method
# sets this to true it breaks the recursion and stops the search.
self._finished = False
self._start_time = datetime.utcnow()
self.minimize_matrix()
self._best_m_list = self._output_lists[0][1]
self._minimized_sum = self._output_lists[0][0]
def minimize_matrix(self):
"""
This method finds and returns the permutations that produce the lowest
ewald sum calls recursive function to iterate through permutations
"""
if self._algo == EwaldMinimizer.ALGO_FAST or \
self._algo == EwaldMinimizer.ALGO_BEST_FIRST:
return self._recurse(self._matrix, self._m_list,
set(range(len(self._matrix))))
def add_m_list(self, matrix_sum, m_list):
"""
This adds an m_list to the output_lists and updates the current
minimum if the list is full.
"""
if self._output_lists is None:
self._output_lists = [[matrix_sum, m_list]]
else:
bisect.insort(self._output_lists, [matrix_sum, m_list])
if self._algo == EwaldMinimizer.ALGO_BEST_FIRST and \
len(self._output_lists) == self._num_to_return:
self._finished = True
if len(self._output_lists) > self._num_to_return:
self._output_lists.pop()
if len(self._output_lists) == self._num_to_return:
self._current_minimum = self._output_lists[-1][0]
def best_case(self, matrix, m_list, indices_left):
"""
Computes a best case given a matrix and manipulation list.
Args:
matrix: the current matrix (with some permutations already
performed)
m_list: [(multiplication fraction, number_of_indices, indices,
species)] describing the manipulation
indices: Set of indices which haven't had a permutation
performed on them.
"""
m_indices = []
fraction_list = []
for m in m_list:
m_indices.extend(m[2])
fraction_list.extend([m[0]] * m[1])
indices = list(indices_left.intersection(m_indices))
interaction_matrix = matrix[indices, :][:, indices]
fractions = np.zeros(len(interaction_matrix)) + 1
fractions[:len(fraction_list)] = fraction_list
fractions = np.sort(fractions)
# Sum associated with each index (disregarding interactions between
# indices)
sums = 2 * np.sum(matrix[indices], axis=1)
sums = np.sort(sums)
# Interaction corrections. Can be reduced to (1-x)(1-y) for x,y in
# fractions each element in a column gets multiplied by (1-x), and then
# the sum of the columns gets multiplied by (1-y) since fractions are
# less than 1, there is no effect of one choice on the other
step1 = np.sort(interaction_matrix) * (1 - fractions)
step2 = np.sort(np.sum(step1, axis=1))
step3 = step2 * (1 - fractions)
interaction_correction = np.sum(step3)
if self._algo == self.ALGO_TIME_LIMIT:
elapsed_time = datetime.utcnow() - self._start_time
speedup_parameter = elapsed_time.total_seconds() / 1800
avg_int = np.sum(interaction_matrix, axis=None)
avg_frac = np.average(np.outer(1 - fractions, 1 - fractions))
average_correction = avg_int * avg_frac
interaction_correction = average_correction * speedup_parameter \
+ interaction_correction * (1 - speedup_parameter)
best_case = np.sum(matrix) + np.inner(sums[::-1], fractions - 1) + interaction_correction
return best_case
def get_next_index(self, matrix, manipulation, indices_left):
"""
Returns an index that should have the most negative effect on the
matrix sum
"""
f = manipulation[0]
indices = list(indices_left.intersection(manipulation[2]))
sums = np.sum(matrix[indices], axis=1)
if f < 1:
next_index = indices[sums.argmax(axis=0)]
else:
next_index = indices[sums.argmin(axis=0)]
return next_index
def _recurse(self, matrix, m_list, indices, output_m_list=[]):
"""
This method recursively finds the minimal permutations using a binary
tree search strategy.
Args:
matrix: The current matrix (with some permutations already
performed).
m_list: The list of permutations still to be performed
indices: Set of indices which haven't had a permutation
performed on them.
"""
# check to see if we've found all the solutions that we need
if self._finished:
return
# if we're done with the current manipulation, pop it off.
while m_list[-1][1] == 0:
m_list = copy(m_list)
m_list.pop()
# if there are no more manipulations left to do check the value
if not m_list:
matrix_sum = np.sum(matrix)
if matrix_sum < self._current_minimum:
self.add_m_list(matrix_sum, output_m_list)
return
# if we wont have enough indices left, return
if m_list[-1][1] > len(indices.intersection(m_list[-1][2])):
return
if len(m_list) == 1 or m_list[-1][1] > 1:
if self.best_case(matrix, m_list, indices) > self._current_minimum:
return
index = self.get_next_index(matrix, m_list[-1], indices)
m_list[-1][2].remove(index)
# Make the matrix and new m_list where we do the manipulation to the
# index that we just got
matrix2 = np.copy(matrix)
m_list2 = deepcopy(m_list)
output_m_list2 = copy(output_m_list)
matrix2[index, :] *= m_list[-1][0]
matrix2[:, index] *= m_list[-1][0]
output_m_list2.append([index, m_list[-1][3]])
indices2 = copy(indices)
indices2.remove(index)
m_list2[-1][1] -= 1
# recurse through both the modified and unmodified matrices
self._recurse(matrix2, m_list2, indices2, output_m_list2)
self._recurse(matrix, m_list, indices, output_m_list)
@property
def best_m_list(self):
"""
Returns: Best m_list found.
"""
return self._best_m_list
@property
def minimized_sum(self):
"""
Returns: Minimized sum
"""
return self._minimized_sum
@property
def output_lists(self):
"""
Returns: output lists.
"""
return self._output_lists
def compute_average_oxidation_state(site):
"""
Calculates the average oxidation state of a site
Args:
site: Site to compute average oxidation state
Returns:
Average oxidation state of site.
"""
try:
avg_oxi = sum([sp.oxi_state * occu
for sp, occu in site.species.items()
if sp is not None])
return avg_oxi
except AttributeError:
pass
try:
return site.charge
except AttributeError:
raise ValueError("Ewald summation can only be performed on structures "
"that are either oxidation state decorated or have "
"site charges.")
| 37.430906 | 113 | 0.592474 |
c7f944a2dd5f08fb2fbabc1f2937cada48894df6 | 2,721 | py | Python | pybo/pybochunk.py | mikkokotila/pybo | ae921861e3e8c18856f19c59fc4c7da8f2126c1c | [
"Apache-2.0"
] | null | null | null | pybo/pybochunk.py | mikkokotila/pybo | ae921861e3e8c18856f19c59fc4c7da8f2126c1c | [
"Apache-2.0"
] | null | null | null | pybo/pybochunk.py | mikkokotila/pybo | ae921861e3e8c18856f19c59fc4c7da8f2126c1c | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
from .bochunk import BoChunk
class PyBoChunk(BoChunk):
"""
Produces chunks of the following types: bo, non-bo, punct and syl chunks
Implements the following chunking pipeline:
chunk "input_str" into "bo"/"non-bo"
| chunk "bo" into "punct"/"bo"
| chunk "bo" into "sym"/"bo"
| chunk "bo" into "num"/"bo"
| chunk "bo" into syllables
| delete chunks containing spaces and transfer their content to the previous chunk
.. note:: Following Tibetan usage, it does not consider space as a punctuation mark.
Spaces get attached to the chunk preceding them.
"""
def __init__(self, string, ignore_chars=[]):
BoChunk.__init__(self, string, ignore_chars=ignore_chars)
def chunk(self, indices=True, gen=False):
chunks = self.chunk_bo_chars()
self.pipe_chunk(chunks, self.chunk_punct, to_chunk=self.BO_MARKER, yes=self.PUNCT_MARKER)
self.pipe_chunk(chunks, self.chunk_symbol, to_chunk=self.BO_MARKER, yes=self.SYMBOL_MARKER)
self.pipe_chunk(chunks, self.chunk_number, to_chunk=self.BO_MARKER, yes=self.NUMBER_MARKER)
self.pipe_chunk(chunks, self.syllabify, to_chunk=self.BO_MARKER, yes=self.SYL_MARKER)
self.__attach_space_chunks(chunks)
if not indices:
return self.get_chunked(chunks, gen=gen)
return chunks
def __attach_space_chunks(self, indices):
"""
Deletes space-only chunks and puts their content in the previous chunk
:param indices: output from a previous chunking method containing space-only chunks
:type indices: list of tuples containing each 3 ints
"""
for num, i in enumerate(indices):
if num - 1 >= 0 and self.__only_contains_spaces(i[1], i[1] + i[2]):
previous_chunk = indices[num - 1]
inc = 0
while not previous_chunk:
inc += 1
previous_chunk = indices[num - 1 - inc]
indices[num - 1 - inc] = (previous_chunk[0], previous_chunk[1], previous_chunk[2] + i[2])
indices[num] = False
c = 0
while c < len(indices):
if not indices[c]:
del indices[c]
else:
c += 1
def __only_contains_spaces(self, start, end):
"""
Tests whether the character group of all the chars in the range between start and end is SPACE.
"""
spaces_count = 0
i = start
while i < end:
if self.base_structure[i] == self.SPACE:
spaces_count += 1
i += 1
return spaces_count == end - start
| 38.871429 | 105 | 0.601617 |
bbc84c6e01a364c890e8a69b5ad4013093e64578 | 2,376 | py | Python | changes/models/plan.py | bowlofstew/changes | ebd393520e0fdb07c240a8d4e8747281b6186e28 | [
"Apache-2.0"
] | null | null | null | changes/models/plan.py | bowlofstew/changes | ebd393520e0fdb07c240a8d4e8747281b6186e28 | [
"Apache-2.0"
] | null | null | null | changes/models/plan.py | bowlofstew/changes | ebd393520e0fdb07c240a8d4e8747281b6186e28 | [
"Apache-2.0"
] | null | null | null | from uuid import uuid4
from datetime import datetime
from enum import Enum
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String
from sqlalchemy.orm import backref, relationship
from changes.config import db
from changes.db.types.enum import Enum as EnumType
from changes.db.types.guid import GUID
from changes.db.types.json import JSONEncodedDict
from changes.db.utils import model_repr
class PlanStatus(Enum):
inactive = 0
active = 1
def __str__(self):
return STATUS_LABELS[self]
STATUS_LABELS = {
PlanStatus.inactive: 'Inactive',
PlanStatus.active: 'Active',
}
class Plan(db.Model):
"""
What work should we do for our new revision? A project may have multiple
plans, e.g. whenever a diff comes in, test it on both mac and windows
(each being its own plan.) In theory, a plan consists of a sequence of
steps; in practice, a plan is just a wrapper around a single step.
"""
id = Column(GUID, primary_key=True, default=uuid4)
project_id = Column(GUID, ForeignKey('project.id', ondelete="CASCADE"), nullable=False)
label = Column(String(128), nullable=False)
date_created = Column(DateTime, default=datetime.utcnow, nullable=False)
date_modified = Column(DateTime, default=datetime.utcnow, nullable=False)
data = Column(JSONEncodedDict)
status = Column(EnumType(PlanStatus),
default=PlanStatus.inactive,
nullable=False, server_default='1')
# If not None, use snapshot from another plan. This allows us to share
# a single snapshot between multiple plans.
#
# This plan must be a plan from the same project (or else jobstep_details
# will fail) but this is not enforced by the database schema because we do
# not use a composite key.
snapshot_plan_id = Column(GUID, ForeignKey('plan.id', ondelete="SET NULL"), nullable=True)
avg_build_time = Column(Integer)
project = relationship('Project', backref=backref('plans'))
__repr__ = model_repr('label')
__tablename__ = 'plan'
def __init__(self, **kwargs):
super(Plan, self).__init__(**kwargs)
if self.id is None:
self.id = uuid4()
if self.date_created is None:
self.date_created = datetime.utcnow()
if self.date_modified is None:
self.date_modified = self.date_created
| 35.462687 | 94 | 0.698232 |
4482cc5f10ebe599865a6a7aee5b72d77cc6824b | 5,578 | py | Python | tests/models.py | wethegit/django-modelcluster | cb9e1da8cfaa4e8f1e6176473206bfaa6519e0cb | [
"BSD-3-Clause"
] | null | null | null | tests/models.py | wethegit/django-modelcluster | cb9e1da8cfaa4e8f1e6176473206bfaa6519e0cb | [
"BSD-3-Clause"
] | null | null | null | tests/models.py | wethegit/django-modelcluster | cb9e1da8cfaa4e8f1e6176473206bfaa6519e0cb | [
"BSD-3-Clause"
] | null | null | null | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.managers import TaggableManager
from taggit.models import TaggedItemBase
from modelcluster.fields import ParentalKey, ParentalManyToManyField
from modelcluster.models import ClusterableModel
@python_2_unicode_compatible
class Band(ClusterableModel):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
@python_2_unicode_compatible
class BandMember(models.Model):
band = ParentalKey('Band', related_name='members', on_delete=models.CASCADE)
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Meta:
unique_together = ['band', 'name']
@python_2_unicode_compatible
class Album(models.Model):
band = ParentalKey('Band', related_name='albums')
name = models.CharField(max_length=255)
release_date = models.DateField(null=True, blank=True)
sort_order = models.IntegerField(null=True, blank=True, editable=False)
sort_order_field = 'sort_order'
def __str__(self):
return self.name
class Meta:
ordering = ['sort_order']
class TaggedPlace(TaggedItemBase):
content_object = ParentalKey('Place', related_name='tagged_items', on_delete=models.CASCADE)
@python_2_unicode_compatible
class Place(ClusterableModel):
name = models.CharField(max_length=255)
tags = ClusterTaggableManager(through=TaggedPlace, blank=True)
def __str__(self):
return self.name
class Restaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
proprietor = models.ForeignKey('Chef', null=True, blank=True, on_delete=models.SET_NULL, related_name='restaurants')
class TaggedNonClusterPlace(TaggedItemBase):
content_object = models.ForeignKey('NonClusterPlace', related_name='tagged_items', on_delete=models.CASCADE)
@python_2_unicode_compatible
class NonClusterPlace(models.Model):
"""
For backwards compatibility we need ClusterModel to work with
plain TaggableManagers (as opposed to ClusterTaggableManager), albeit
without the in-memory relation behaviour
"""
name = models.CharField(max_length=255)
tags = TaggableManager(through=TaggedNonClusterPlace, blank=True)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Dish(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Wine(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Chef(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
@python_2_unicode_compatible
class MenuItem(models.Model):
restaurant = ParentalKey('Restaurant', related_name='menu_items', on_delete=models.CASCADE)
dish = models.ForeignKey('Dish', related_name='+', on_delete=models.CASCADE)
price = models.DecimalField(max_digits=6, decimal_places=2)
recommended_wine = models.ForeignKey('Wine', null=True, blank=True, on_delete=models.SET_NULL, related_name='+')
def __str__(self):
return "%s - %f" % (self.dish, self.price)
@python_2_unicode_compatible
class Review(models.Model):
place = ParentalKey('Place', related_name='reviews', on_delete=models.CASCADE)
author = models.CharField(max_length=255)
body = models.TextField()
def __str__(self):
return "%s on %s" % (self.author, self.place.name)
@python_2_unicode_compatible
class Log(ClusterableModel):
time = models.DateTimeField(blank=True, null=True)
data = models.CharField(max_length=255)
def __str__(self):
return "[%s] %s" % (self.time.isoformat(), self.data)
@python_2_unicode_compatible
class Document(ClusterableModel):
title = models.CharField(max_length=255)
file = models.FileField(upload_to='documents')
def __str__(self):
return self.title
@python_2_unicode_compatible
class NewsPaper(ClusterableModel):
title = models.CharField(max_length=255)
def __str__(self):
return self.title
class TaggedArticle(TaggedItemBase):
content_object = ParentalKey('Article', related_name='tagged_items', on_delete=models.CASCADE)
@python_2_unicode_compatible
class Article(ClusterableModel):
paper = ParentalKey(NewsPaper, blank=True, null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
authors = ParentalManyToManyField('Author', related_name='articles_by_author')
categories = ParentalManyToManyField('Category', related_name='articles_by_category')
tags = ClusterTaggableManager(through=TaggedArticle, blank=True)
def __str__(self):
return self.title
@python_2_unicode_compatible
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Meta:
ordering = ['name']
@python_2_unicode_compatible
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Gallery(ClusterableModel):
title = models.CharField(max_length=255)
def __str__(self):
return self.title
class GalleryImage(models.Model):
gallery = ParentalKey(Gallery, related_name='images', on_delete=models.CASCADE)
image = models.FileField()
| 27.477833 | 120 | 0.743277 |
4e5dc07ca03ef141198e7438d165bb77664ecfce | 1,810 | py | Python | aliyun-python-sdk-ccc/aliyunsdkccc/request/v20200701/AddNumbersToSkillGroupRequest.py | jorsonzen/aliyun-openapi-python-sdk | 0afbfa8e5f9e19455695aa799f7dcc1cd853d827 | [
"Apache-2.0"
] | 1,001 | 2015-07-24T01:32:41.000Z | 2022-03-25T01:28:18.000Z | aliyun-python-sdk-ccc/aliyunsdkccc/request/v20200701/AddNumbersToSkillGroupRequest.py | jorsonzen/aliyun-openapi-python-sdk | 0afbfa8e5f9e19455695aa799f7dcc1cd853d827 | [
"Apache-2.0"
] | 363 | 2015-10-20T03:15:00.000Z | 2022-03-08T12:26:19.000Z | aliyun-python-sdk-ccc/aliyunsdkccc/request/v20200701/AddNumbersToSkillGroupRequest.py | jorsonzen/aliyun-openapi-python-sdk | 0afbfa8e5f9e19455695aa799f7dcc1cd853d827 | [
"Apache-2.0"
] | 682 | 2015-09-22T07:19:02.000Z | 2022-03-22T09:51:46.000Z | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except 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 agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkccc.endpoint import endpoint_data
class AddNumbersToSkillGroupRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'CCC', '2020-07-01', 'AddNumbersToSkillGroup','CCC')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_NumberList(self):
return self.get_query_params().get('NumberList')
def set_NumberList(self,NumberList):
self.add_query_param('NumberList',NumberList)
def get_InstanceId(self):
return self.get_query_params().get('InstanceId')
def set_InstanceId(self,InstanceId):
self.add_query_param('InstanceId',InstanceId)
def get_SkillGroupId(self):
return self.get_query_params().get('SkillGroupId')
def set_SkillGroupId(self,SkillGroupId):
self.add_query_param('SkillGroupId',SkillGroupId) | 36.2 | 81 | 0.769061 |
cf0621c7b44847af82d2ee7341cd32432e883908 | 629 | py | Python | .idea/VirtualEnvironment/Lib/site-packages/hstest/common/utils.py | Vladpetr/NewsPortal | cd4127fbc09d9c8f5e65c8ae699856c6d380a320 | [
"Apache-2.0"
] | null | null | null | .idea/VirtualEnvironment/Lib/site-packages/hstest/common/utils.py | Vladpetr/NewsPortal | cd4127fbc09d9c8f5e65c8ae699856c6d380a320 | [
"Apache-2.0"
] | 5 | 2021-04-08T22:02:15.000Z | 2022-02-10T14:53:45.000Z | .idea/VirtualEnvironment/Lib/site-packages/hstest/common/utils.py | Vladpetr/NewsPortal | cd4127fbc09d9c8f5e65c8ae699856c6d380a320 | [
"Apache-2.0"
] | null | null | null | failed_msg_start = '#educational_plugin FAILED + '
failed_msg_continue = '#educational_plugin '
success_msg = '#educational_plugin test OK'
def failed(message: str):
""" Reports failure """
lines = message.splitlines()
print('\n' + failed_msg_start + lines[0])
for line in lines[1:]:
print(failed_msg_continue + line)
return -1, message
def passed():
""" Reports success """
print('\n' + success_msg)
return 0, 'test OK'
def clean_text(text: str) -> str:
return (
text.replace('\r\n', '\n')
.replace('\r', '\n')
.replace('\u00a0', '\u0020')
)
| 23.296296 | 50 | 0.594595 |
3e4d598bb50abac7c04346facfd03893bc076c5d | 322 | py | Python | calc_template/__init__.py | flying-sheep/calc_template | 17519d5e2e946af49f3252067352ef9063d08c0d | [
"BSD-3-Clause"
] | null | null | null | calc_template/__init__.py | flying-sheep/calc_template | 17519d5e2e946af49f3252067352ef9063d08c0d | [
"BSD-3-Clause"
] | null | null | null | calc_template/__init__.py | flying-sheep/calc_template | 17519d5e2e946af49f3252067352ef9063d08c0d | [
"BSD-3-Clause"
] | null | null | null | from . import paths, params
from .data import read_data, write_data
from .summary import write_summary
import scanpy.api as sc
def main():
adata = read_data(paths.exprs_in)
# Do stuff with the anndata object, e.g.
sc.pp.log1p(adata)
write_data(paths.exprs_transformed, adata)
write_summary(adata)
| 20.125 | 46 | 0.729814 |
4243f6936ab14a31799b9fbc361b6c1f1813e371 | 1,044 | py | Python | src/git_svn_monitor/core/logger.py | shin-hama/git-svn-monitor | acb793c2da63d6802efa8e0e6c99482f4fad0f80 | [
"MIT"
] | null | null | null | src/git_svn_monitor/core/logger.py | shin-hama/git-svn-monitor | acb793c2da63d6802efa8e0e6c99482f4fad0f80 | [
"MIT"
] | 36 | 2021-07-12T00:08:03.000Z | 2022-03-25T11:19:39.000Z | src/git_svn_monitor/core/logger.py | shin-hama/git-svn-monitor | acb793c2da63d6802efa8e0e6c99482f4fad0f80 | [
"MIT"
] | null | null | null | import logging
import logging.handlers
from git_svn_monitor.core.config import env_config, LOG_FILE
def setup_logger(name: str) -> None:
""" Setup logging config
Parameter
---------
name: str
The logger name, expected root package name.
ex) Call from __init__.py at the root of this package as `setup_logger(__name__)`.
"""
logger = logging.getLogger(name)
if env_config.debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
# set limits to 1MB
max_bytes = 1024*1024
if LOG_FILE.exists() is False:
LOG_FILE.parent.mkdir(parents=True)
LOG_FILE.touch()
fh = logging.handlers.RotatingFileHandler(
LOG_FILE, maxBytes=max_bytes, backupCount=5, encoding="utf-8"
)
sh = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(sh)
| 26.1 | 90 | 0.658046 |
77d4caa255747374bb9c5abb90dbbb7bfe1ff359 | 817 | py | Python | LAB1/multiagent/projectParams.py | LuciferDarkStar/USTC_2021_AI_Lab | d777a999f45372e90c067120af40730e8d041e54 | [
"MIT"
] | 43 | 2019-10-31T10:21:14.000Z | 2022-03-31T14:55:01.000Z | LAB1/multiagent/projectParams.py | LuciferDarkStar/USTC_2021_AI_Lab | d777a999f45372e90c067120af40730e8d041e54 | [
"MIT"
] | 19 | 2021-05-10T20:58:19.000Z | 2021-11-12T21:15:22.000Z | LAB1/multiagent/projectParams.py | LuciferDarkStar/USTC_2021_AI_Lab | d777a999f45372e90c067120af40730e8d041e54 | [
"MIT"
] | 27 | 2020-03-27T00:13:11.000Z | 2022-03-27T01:51:15.000Z | # projectParams.py
# ----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
STUDENT_CODE_DEFAULT = 'multiAgents.py'
PROJECT_TEST_CLASSES = 'multiagentTestClasses.py'
PROJECT_NAME = 'Project 2: Multiagent search'
BONUS_PIC = False
| 43 | 80 | 0.761322 |
c370d0a84942de228646255e8a1b5e355901524d | 4,556 | py | Python | configs/example/hmctest.py | mandaltj/gem5_chips | b9c0c602241ffda7851c1afb32fa01f295bb98fd | [
"BSD-3-Clause"
] | 30 | 2019-07-12T02:35:33.000Z | 2022-02-22T03:34:35.000Z | configs/example/hmctest.py | mandaltj/gem5_chips | b9c0c602241ffda7851c1afb32fa01f295bb98fd | [
"BSD-3-Clause"
] | 2 | 2019-03-22T14:23:38.000Z | 2019-03-22T15:45:35.000Z | configs/example/hmctest.py | mandaltj/gem5_chips | b9c0c602241ffda7851c1afb32fa01f295bb98fd | [
"BSD-3-Clause"
] | 12 | 2019-10-16T02:23:23.000Z | 2022-03-30T09:21:10.000Z | from __future__ import print_function
import sys
import argparse
import subprocess
from pprint import pprint
import m5
from m5.objects import *
from m5.util import *
addToPath('../')
from common import MemConfig
from common import HMC
def add_options(parser):
parser.add_argument("--external-memory-system", default=0, action="store",
type=int, help="External memory system")
# TLM related options, currently optional in configs/common/MemConfig.py
parser.add_argument("--tlm-memory", action="store_true", help="use\
external port for SystemC TLM co-simulation. Default:\
no")
# Elastic traces related options, currently optional in
# configs/common/MemConfig.py
parser.add_argument("--elastic-trace-en", action="store_true",
help="enable capture of data dependency and\
instruction fetch traces using elastic trace\
probe.\nDefault: no")
# Options related to traffic generation
parser.add_argument("--num-tgen", default=4, action="store", type=int,
choices=[4], help="number of traffic generators.\
Right now this script supports only 4.\nDefault: 4")
parser.add_argument("--tgen-cfg-file",
default="./configs/example/hmc_tgen.cfg",
type=str, help="Traffic generator(s) configuration\
file. Note: this script uses the same configuration\
file for all traffic generators")
# considering 4GB HMC device with following parameters
# hmc_device_size = '4GB'
# hmc_vault_size = '256MB'
# hmc_stack_size = 8
# hmc_bank_in_stack = 2
# hmc_bank_size = '16MB'
# hmc_bank_in_vault = 16
def build_system(options):
# create the system we are going to simulate
system = System()
# use timing mode for the interaction between master-slave ports
system.mem_mode = 'timing'
# set the clock fequency of the system
clk = '100GHz'
vd = VoltageDomain(voltage='1V')
system.clk_domain = SrcClockDomain(clock=clk, voltage_domain=vd)
# add traffic generators to the system
system.tgen = [TrafficGen(config_file=options.tgen_cfg_file) for i in
xrange(options.num_tgen)]
# Config memory system with given HMC arch
MemConfig.config_mem(options, system)
# Connect the traffic generatiors
if options.arch == "distributed":
for i in xrange(options.num_tgen):
system.tgen[i].port = system.membus.slave
# connect the system port even if it is not used in this example
system.system_port = system.membus.slave
if options.arch == "mixed":
for i in xrange(int(options.num_tgen/2)):
system.tgen[i].port = system.membus.slave
hh = system.hmc_host
if options.enable_global_monitor:
system.tgen[2].port = hh.lmonitor[2].slave
hh.lmonitor[2].master = hh.seriallink[2].slave
system.tgen[3].port = hh.lmonitor[3].slave
hh.lmonitor[3].master = hh.seriallink[3].slave
else:
system.tgen[2].port = hh.seriallink[2].slave
system.tgen[3].port = hh.seriallink[3].slave
# connect the system port even if it is not used in this example
system.system_port = system.membus.slave
if options.arch == "same":
hh = system.hmc_host
for i in xrange(options.num_links_controllers):
if options.enable_global_monitor:
system.tgen[i].port = hh.lmonitor[i].slave
else:
system.tgen[i].port = hh.seriallink[i].slave
# set up the root SimObject
root = Root(full_system=False, system=system)
return root
def main():
parser = argparse.ArgumentParser(description="Simple system using HMC as\
main memory")
HMC.add_options(parser)
add_options(parser)
options = parser.parse_args()
# build the system
root = build_system(options)
# instantiate all of the objects we've created so far
m5.instantiate()
print("Beginning simulation!")
event = m5.simulate(10000000000)
m5.stats.dump()
print('Exiting @ tick %i because %s (exit code is %i)' % (m5.curTick(),
event.getCause(),
event.getCode()))
print("Done")
if __name__ == "__m5_main__":
main()
| 39.275862 | 79 | 0.619403 |
33c898248f085482a51ddfe6737271eaadf555c4 | 13,656 | py | Python | models/comboptnet.py | martius-lab/CombOptNet | d563d31a95dce35a365d50b81f932c27531ae09b | [
"MIT"
] | 46 | 2021-05-08T21:04:56.000Z | 2022-03-10T11:37:23.000Z | models/comboptnet.py | martius-lab/CombOptNet | d563d31a95dce35a365d50b81f932c27531ae09b | [
"MIT"
] | null | null | null | models/comboptnet.py | martius-lab/CombOptNet | d563d31a95dce35a365d50b81f932c27531ae09b | [
"MIT"
] | 7 | 2021-05-08T23:33:16.000Z | 2021-12-30T16:15:22.000Z | import warnings
import gurobipy as gp
import jax.numpy as jnp
import numpy as np
import torch
from gurobipy import GRB, quicksum
from jax import grad
from utils.comboptnet_utils import compute_delta_y, check_point_feasibility, softmin, \
signed_euclidean_distance_constraint_point, tensor_to_jax
from utils.utils import ParallelProcessing
class CombOptNetModule(torch.nn.Module):
def __init__(self, variable_range, tau=None, clip_gradients_to_box=True, use_canonical_basis=False):
super().__init__()
"""
@param variable_range: dict(lb, ub), range of variables in the ILP
@param tau: a float/np.float32/torch.float32, the value of tau for computing the constraint gradient
@param clip_gradients_to_box: boolean flag, if true the gradients are projected into the feasible hypercube
@param use_canonical_basis: boolean flag, if true the canonical basis is used instead of delta basis
"""
self.solver_params = dict(tau=tau, variable_range=variable_range, clip_gradients_to_box=clip_gradients_to_box,
use_canonical_basis=use_canonical_basis, parallel_processing=ParallelProcessing())
self.solver = DifferentiableILPsolver
def forward(self, cost_vector, constraints):
"""
Forward pass of CombOptNet running a differentiable ILP solver
@param cost_vector: torch.Tensor of shape (bs, num_variables) with batch of ILP cost vectors
@param constraints: torch.Tensor of shape (bs, num_const, num_variables + 1) or (num_const, num_variables + 1)
with (potentially batch of) ILP constraints
@return: torch.Tensor of shape (bs, num_variables) with integer values capturing the solution of the ILP
"""
if len(constraints.shape) == 2:
bs = cost_vector.shape[0]
constraints = torch.stack(bs * [constraints])
y, infeasibility_indicator = self.solver.apply(cost_vector, constraints, self.solver_params)
return y
class DifferentiableILPsolver(torch.autograd.Function):
"""
Differentiable ILP solver as a torch.Function
"""
@staticmethod
def forward(ctx, cost_vector, constraints, params):
"""
Implementation of the forward pass of a batched (potentially parallelized) ILP solver.
@param ctx: context for backpropagation
@param cost_vector: torch.Tensor of shape (bs, num_variables) with batch of ILp cost vectors
@param constraints: torch.Tensor of shape (bs, num_const, num_variables + 1) with batch of ILP constraints
@param params: a dict of additional params. Must contain:
tau: a float/np.float32/torch.float32, the value of tau for computing the constraint gradient
clip_gradients_to_box: boolean flag, if true the gradients are projected into the feasible hypercube
@return: torch.Tensor of shape (bs, num_variables) with integer values capturing the solution of the ILP,
torch.Tensor of shape (bs) with 0/1 values, where 1 corresponds to an infeasible ILP instance
"""
device = constraints.device
maybe_parallelize = params['parallel_processing'].maybe_parallelize
dynamic_args = [{"cost_vector": cost_vector, "constraints": const} for cost_vector, const in
zip(cost_vector.cpu().detach().numpy(), constraints.cpu().detach().numpy())]
result = maybe_parallelize(ilp_solver, params['variable_range'], dynamic_args)
y, infeasibility_indicator = [torch.from_numpy(np.array(res)).to(device) for res in zip(*result)]
ctx.params = params
ctx.save_for_backward(cost_vector, constraints, y, infeasibility_indicator)
return y, infeasibility_indicator
@staticmethod
def backward(ctx, y_grad, _):
"""
Backward pass computation.
@param ctx: context from the forward pass
@param y_grad: torch.Tensor of shape (bs, num_variables) describing the incoming gradient dy for y
@return: torch.Tensor of shape (bs, num_variables) gradient dL / cost_vector
torch.Tensor of shape (bs, num_constraints, num_variables + 1) gradient dL / constraints
"""
cost_vector, constraints, y, infeasibility_indicator = ctx.saved_tensors
assert y.shape == y_grad.shape
grad_mismatch_function = grad(mismatch_function, argnums=[0, 1])
grad_cost_vector, grad_constraints = grad_mismatch_function(tensor_to_jax(cost_vector),
tensor_to_jax(constraints),
tensor_to_jax(y),
tensor_to_jax(y_grad),
tensor_to_jax(infeasibility_indicator),
variable_range=ctx.params['variable_range'],
clip_gradients_to_box=ctx.params[
'clip_gradients_to_box'],
use_canonical_basis=ctx.params[
'use_canonical_basis'],
tau=ctx.params['tau'])
cost_vector_grad = torch.from_numpy(np.array(grad_cost_vector)).to(y_grad.device)
constraints_gradient = torch.from_numpy(np.array(grad_constraints)).to(y_grad.device)
return cost_vector_grad, constraints_gradient, None
def ilp_solver(cost_vector, constraints, lb, ub):
"""
ILP solver using Gurobi. Computes the solution of a single integer linear program
y* = argmin_y (c * y) subject to A @ y + b <= 0, y integer, lb <= y <= ub
@param cost_vector: np.array of shape (num_variables) with cost vector of the ILP
@param constraints: np.array of shape (num_const, num_variables + 1) with constraints of the ILP
@param lb: float, lower bound of variables
@param ub: float, upper bound of variables
@return: np.array of shape (num_variables) with integer values capturing the solution of the ILP,
boolean flag, where true corresponds to an infeasible ILP instance
"""
A, b = constraints[:, :-1], constraints[:, -1]
num_constraints, num_variables = A.shape
model = gp.Model("mip1")
model.setParam('OutputFlag', 0)
model.setParam("Threads", 1)
variables = [model.addVar(lb=lb, ub=ub, vtype=GRB.INTEGER, name='v' + str(i)) for i in range(num_variables)]
model.setObjective(quicksum(c * var for c, var in zip(cost_vector, variables)), GRB.MINIMIZE)
for a, _b in zip(A, b):
model.addConstr(quicksum(c * var for c, var in zip(a, variables)) + _b <= 0)
model.optimize()
try:
y = np.array([v.x for v in model.getVars()])
infeasible = False
except AttributeError:
warnings.warn(f'Infeasible ILP encountered. Dummy solution should be handled as special case.')
y = np.zeros_like(cost_vector)
infeasible = True
return y, infeasible
def mismatch_function(cost_vector, constraints, y, y_grad, infeasibility_indicator, variable_range, tau,
clip_gradients_to_box, use_canonical_basis, average_solution=True, use_cost_mismatch=True):
"""
Computes the combined mismatch function for cost vectors and constraints P_(dy)(A, b, c) = P_(dy)(A, b) + P_(dy)(c)
P_(dy)(A, b) = sum_k(lambda_k * P_(delta_k)(A, b)),
P_(dy)(c) = sum_k(lambda_k * P_(delta_k)(c)),
where delta_k = y'_k - y
@param cost_vector: jnp.array of shape (bs, num_variables) with batch of ILP cost vectors
@param constraints: jnp.array of shape (bs, num_const, num_variables + 1) with batch of ILP constraints
@param y: jnp.array of shape (bs, num_variables) with batch of ILP solutions
@param y_grad: jnp.array of shape (bs, num_variables) with batch of incoming gradients for y
@param infeasibility_indicator: jnp.array of shape (bs) with batch of indicators whether ILP has feasible solution
@param variable_range: dict(lb, ub), range of variables in the ILP
@param tau: a float/np.float32/torch.float32, the value of tau for computing the constraint gradient
@param clip_gradients_to_box: boolean flag, if true the gradients are projected into the feasible hypercube
@param use_canonical_basis: boolean flag, if true the canonical basis is used instead of delta basis
@return: jnp.array scalar with value of mismatch function
"""
num_constraints = constraints.shape[1]
if num_constraints > 1 and tau is None:
raise ValueError('If more than one constraint is used the parameter tau needs to be specified.')
if num_constraints == 1 and tau is not None:
warnings.warn('The specified parameter tau has no influence as only a single constraint is used.')
delta_y, lambdas = compute_delta_y(y=y, y_grad=y_grad, clip_gradients_to_box=clip_gradients_to_box,
use_canonical_basis=use_canonical_basis, **variable_range)
y = y[:, None, :]
y_prime = y + delta_y
cost_vector = cost_vector[:, None, :]
constraints = constraints[:, None, :, :]
y_prime_feasible_constraints, y_prime_inside_box = check_point_feasibility(point=y_prime, constraints=constraints,
**variable_range)
feasibility_indicator = 1.0 - infeasibility_indicator
correct_solution_indicator = jnp.all(jnp.isclose(y, y_prime), axis=-1)
# solution can only be correct if we also have a feasible problem
# (fixes case in which infeasible solution dummy matches ground truth)
correct_solution_indicator *= feasibility_indicator[:, None]
incorrect_solution_indicator = 1.0 - correct_solution_indicator
constraints_mismatch = compute_constraints_mismatch(constraints=constraints, y=y, y_prime=y_prime,
y_prime_feasible_constraints=y_prime_feasible_constraints,
y_prime_inside_box=y_prime_inside_box, tau=tau,
incorrect_solution_indicator=incorrect_solution_indicator)
cost_mismatch = compute_cost_mismatch(cost_vector=cost_vector, y=y, y_prime=y_prime,
y_prime_feasible_constraints=y_prime_feasible_constraints,
y_prime_inside_box=y_prime_inside_box)
total_mismatch = constraints_mismatch
if use_cost_mismatch:
total_mismatch += cost_mismatch
total_mismatch = jnp.mean(total_mismatch * lambdas, axis=-1) # scale mismatch functions of sparse y' with lambda
if average_solution:
total_mismatch = jnp.mean(total_mismatch)
return total_mismatch
def compute_cost_mismatch(cost_vector, y, y_prime, y_prime_feasible_constraints, y_prime_inside_box):
"""
Computes the mismatch function for cost vectors P_(delta_k)(c), where delta_k = y'_k - y
"""
c_diff = jnp.sum(cost_vector * y_prime, axis=-1) - jnp.sum(cost_vector * y, axis=-1)
cost_mismatch = jnp.maximum(c_diff, 0.0)
# case distinction in paper: if y' is (constraint-)infeasible or outside of hypercube cost mismatch function is zero
cost_mismatch = cost_mismatch * y_prime_inside_box * y_prime_feasible_constraints
return cost_mismatch
def compute_constraints_mismatch(constraints, y, y_prime, y_prime_inside_box, y_prime_feasible_constraints,
incorrect_solution_indicator, tau):
"""
Computes the mismatch function for constraints P_(delta_k)(A, b), where delta_k = y'_k - y
"""
# case 1 in paper: if y' is (constraint-)feasible, y' is inside the hypercube and y != y'
constraints_mismatch_feasible = compute_constraints_mismatch_feasible(constraints=constraints, y=y, tau=tau)
constraints_mismatch_feasible *= y_prime_feasible_constraints
# case 2 in paper: if y' is (constraint-)infeasible, y' is inside the hypercube and y != y'
constraints_mismatch_infeasible = compute_constraints_mismatch_infeasible(constraints=constraints, y_prime=y_prime)
constraints_mismatch_infeasible *= (1.0 - y_prime_feasible_constraints)
constraints_mismatch = constraints_mismatch_feasible + constraints_mismatch_infeasible
# case 3 in paper: if y prime is outside the hypercube or y = y' constraint mismatch function is zero
constraints_mismatch = constraints_mismatch * y_prime_inside_box * incorrect_solution_indicator
return constraints_mismatch
def compute_constraints_mismatch_feasible(constraints, y, tau):
distance_y_const = signed_euclidean_distance_constraint_point(constraints=constraints, point=y)
constraints_mismatch_feasible = jnp.maximum(-distance_y_const, 0.0)
constraints_mismatch_feasible = softmin(constraints_mismatch_feasible, tau=tau, axis=-1)
return constraints_mismatch_feasible
def compute_constraints_mismatch_infeasible(constraints, y_prime):
distance_y_prime_const = signed_euclidean_distance_constraint_point(constraints=constraints, point=y_prime)
constraints_mismatch_infeasible = jnp.maximum(distance_y_prime_const, 0.0)
constraints_mismatch_infeasible = jnp.sum(constraints_mismatch_infeasible, axis=-1)
return constraints_mismatch_infeasible
| 56.6639 | 120 | 0.676333 |
32fdad643dd82cfe10f83f5e9f281b7bdb9e41b1 | 40,694 | py | Python | sympy/utilities/autowrap.py | clyring/sympy | 54d7726c182065fc25df69b5d1030e568931d82f | [
"BSD-3-Clause"
] | 3 | 2015-01-17T23:15:04.000Z | 2015-05-26T14:11:44.000Z | sympy/utilities/autowrap.py | clyring/sympy | 54d7726c182065fc25df69b5d1030e568931d82f | [
"BSD-3-Clause"
] | 1 | 2017-08-26T01:07:46.000Z | 2017-08-26T16:05:49.000Z | sympy/utilities/autowrap.py | leosartaj/sympy | 28d913d3cead6c5646307ffa6540b21d65059dfd | [
"BSD-3-Clause"
] | null | null | null | """Module for compiling codegen output, and wrap the binary for use in
python.
.. note:: To use the autowrap module it must first be imported
>>> from sympy.utilities.autowrap import autowrap
This module provides a common interface for different external backends, such
as f2py, fwrap, Cython, SWIG(?) etc. (Currently only f2py and Cython are
implemented) The goal is to provide access to compiled binaries of acceptable
performance with a one-button user interface, i.e.
>>> from sympy.abc import x,y
>>> expr = ((x - y)**(25)).expand()
>>> binary_callable = autowrap(expr)
>>> binary_callable(1, 2)
-1.0
The callable returned from autowrap() is a binary python function, not a
SymPy object. If it is desired to use the compiled function in symbolic
expressions, it is better to use binary_function() which returns a SymPy
Function object. The binary callable is attached as the _imp_ attribute and
invoked when a numerical evaluation is requested with evalf(), or with
lambdify().
>>> from sympy.utilities.autowrap import binary_function
>>> f = binary_function('f', expr)
>>> 2*f(x, y) + y
y + 2*f(x, y)
>>> (2*f(x, y) + y).evalf(2, subs={x: 1, y:2})
0.e-110
The idea is that a SymPy user will primarily be interested in working with
mathematical expressions, and should not have to learn details about wrapping
tools in order to evaluate expressions numerically, even if they are
computationally expensive.
When is this useful?
1) For computations on large arrays, Python iterations may be too slow,
and depending on the mathematical expression, it may be difficult to
exploit the advanced index operations provided by NumPy.
2) For *really* long expressions that will be called repeatedly, the
compiled binary should be significantly faster than SymPy's .evalf()
3) If you are generating code with the codegen utility in order to use
it in another project, the automatic python wrappers let you test the
binaries immediately from within SymPy.
4) To create customized ufuncs for use with numpy arrays.
See *ufuncify*.
When is this module NOT the best approach?
1) If you are really concerned about speed or memory optimizations,
you will probably get better results by working directly with the
wrapper tools and the low level code. However, the files generated
by this utility may provide a useful starting point and reference
code. Temporary files will be left intact if you supply the keyword
tempdir="path/to/files/".
2) If the array computation can be handled easily by numpy, and you
don't need the binaries for another project.
"""
from __future__ import print_function, division
import sys
import os
import shutil
import tempfile
from subprocess import STDOUT, CalledProcessError, check_output
from string import Template
from warnings import warn
from sympy.core.cache import cacheit
from sympy.core.compatibility import range, iterable
from sympy.core.function import Lambda
from sympy.core.relational import Eq
from sympy.core.symbol import Dummy, Symbol
from sympy.tensor.indexed import Idx, IndexedBase
from sympy.utilities.codegen import (make_routine, get_code_generator,
OutputArgument, InOutArgument,
InputArgument, CodeGenArgumentListError,
Result, ResultBase, C99CodeGen)
from sympy.utilities.lambdify import implemented_function
from sympy.utilities.decorator import doctest_depends_on
_doctest_depends_on = {'exe': ('f2py', 'gfortran', 'gcc'),
'modules': ('numpy',)}
class CodeWrapError(Exception):
pass
class CodeWrapper(object):
"""Base Class for code wrappers"""
_filename = "wrapped_code"
_module_basename = "wrapper_module"
_module_counter = 0
@property
def filename(self):
return "%s_%s" % (self._filename, CodeWrapper._module_counter)
@property
def module_name(self):
return "%s_%s" % (self._module_basename, CodeWrapper._module_counter)
def __init__(self, generator, filepath=None, flags=[], verbose=False):
"""
generator -- the code generator to use
"""
self.generator = generator
self.filepath = filepath
self.flags = flags
self.quiet = not verbose
@property
def include_header(self):
return bool(self.filepath)
@property
def include_empty(self):
return bool(self.filepath)
def _generate_code(self, main_routine, routines):
routines.append(main_routine)
self.generator.write(
routines, self.filename, True, self.include_header,
self.include_empty)
def wrap_code(self, routine, helpers=[]):
if self.filepath:
workdir = os.path.abspath(self.filepath)
else:
workdir = tempfile.mkdtemp("_sympy_compile")
if not os.access(workdir, os.F_OK):
os.mkdir(workdir)
oldwork = os.getcwd()
os.chdir(workdir)
try:
sys.path.append(workdir)
self._generate_code(routine, helpers)
self._prepare_files(routine)
self._process_files(routine)
mod = __import__(self.module_name)
finally:
sys.path.remove(workdir)
CodeWrapper._module_counter += 1
os.chdir(oldwork)
if not self.filepath:
try:
shutil.rmtree(workdir)
except OSError:
# Could be some issues on Windows
pass
return self._get_wrapped_function(mod, routine.name)
def _process_files(self, routine):
command = self.command
command.extend(self.flags)
try:
retoutput = check_output(command, stderr=STDOUT)
except CalledProcessError as e:
raise CodeWrapError(
"Error while executing command: %s. Command output is:\n%s" % (
" ".join(command), e.output.decode('utf-8')))
if not self.quiet:
print(retoutput)
class DummyWrapper(CodeWrapper):
"""Class used for testing independent of backends """
template = """# dummy module for testing of SymPy
def %(name)s():
return "%(expr)s"
%(name)s.args = "%(args)s"
%(name)s.returns = "%(retvals)s"
"""
def _prepare_files(self, routine):
return
def _generate_code(self, routine, helpers):
with open('%s.py' % self.module_name, 'w') as f:
printed = ", ".join(
[str(res.expr) for res in routine.result_variables])
# convert OutputArguments to return value like f2py
args = filter(lambda x: not isinstance(
x, OutputArgument), routine.arguments)
retvals = []
for val in routine.result_variables:
if isinstance(val, Result):
retvals.append('nameless')
else:
retvals.append(val.result_var)
print(DummyWrapper.template % {
'name': routine.name,
'expr': printed,
'args': ", ".join([str(a.name) for a in args]),
'retvals': ", ".join([str(val) for val in retvals])
}, end="", file=f)
def _process_files(self, routine):
return
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name)
class CythonCodeWrapper(CodeWrapper):
"""Wrapper that uses Cython"""
setup_template = """\
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
cy_opts = {cythonize_options}
{np_import}
ext_mods = [Extension(
{ext_args},
include_dirs={include_dirs},
library_dirs={library_dirs},
libraries={libraries},
extra_compile_args={extra_compile_args},
extra_link_args={extra_link_args}
)]
setup(ext_modules=cythonize(ext_mods, **cy_opts))
"""
pyx_imports = (
"import numpy as np\n"
"cimport numpy as np\n\n")
pyx_header = (
"cdef extern from '{header_file}.h':\n"
" {prototype}\n\n")
pyx_func = (
"def {name}_c({arg_string}):\n"
"\n"
"{declarations}"
"{body}")
std_compile_flag = '-std=c99'
def __init__(self, *args, **kwargs):
"""Instantiates a Cython code wrapper.
The following optional parameters get passed to ``distutils.Extension``
for building the Python extension module. Read its documentation to
learn more.
Parameters
==========
include_dirs : [list of strings]
A list of directories to search for C/C++ header files (in Unix
form for portability).
library_dirs : [list of strings]
A list of directories to search for C/C++ libraries at link time.
libraries : [list of strings]
A list of library names (not filenames or paths) to link against.
extra_compile_args : [list of strings]
Any extra platform- and compiler-specific information to use when
compiling the source files in 'sources'. For platforms and
compilers where "command line" makes sense, this is typically a
list of command-line arguments, but for other platforms it could be
anything. Note that the attribute ``std_compile_flag`` will be
appended to this list.
extra_link_args : [list of strings]
Any extra platform- and compiler-specific information to use when
linking object files together to create the extension (or to create
a new static Python interpreter). Similar interpretation as for
'extra_compile_args'.
cythonize_options : [dictionary]
Keyword arguments passed on to cythonize.
"""
self._include_dirs = kwargs.pop('include_dirs', [])
self._library_dirs = kwargs.pop('library_dirs', [])
self._libraries = kwargs.pop('libraries', [])
self._extra_compile_args = kwargs.pop('extra_compile_args', [])
self._extra_compile_args.append(self.std_compile_flag)
self._extra_link_args = kwargs.pop('extra_link_args', [])
self._cythonize_options = kwargs.pop('cythonize_options', {})
self._need_numpy = False
super(CythonCodeWrapper, self).__init__(*args, **kwargs)
@property
def command(self):
command = [sys.executable, "setup.py", "build_ext", "--inplace"]
return command
def _prepare_files(self, routine, build_dir=os.curdir):
# NOTE : build_dir is used for testing purposes.
pyxfilename = self.module_name + '.pyx'
codefilename = "%s.%s" % (self.filename, self.generator.code_extension)
# pyx
with open(os.path.join(build_dir, pyxfilename), 'w') as f:
self.dump_pyx([routine], f, self.filename)
# setup.py
ext_args = [repr(self.module_name), repr([pyxfilename, codefilename])]
if self._need_numpy:
np_import = 'import numpy as np\n'
self._include_dirs.append('np.get_include()')
else:
np_import = ''
with open(os.path.join(build_dir, 'setup.py'), 'w') as f:
includes = str(self._include_dirs).replace("'np.get_include()'",
'np.get_include()')
f.write(self.setup_template.format(
ext_args=", ".join(ext_args),
np_import=np_import,
include_dirs=includes,
library_dirs=self._library_dirs,
libraries=self._libraries,
extra_compile_args=self._extra_compile_args,
extra_link_args=self._extra_link_args,
cythonize_options=self._cythonize_options
))
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name + '_c')
def dump_pyx(self, routines, f, prefix):
"""Write a Cython file with python wrappers
This file contains all the definitions of the routines in c code and
refers to the header file.
Arguments
---------
routines
List of Routine instances
f
File-like object to write the file to
prefix
The filename prefix, used to refer to the proper header file.
Only the basename of the prefix is used.
"""
headers = []
functions = []
for routine in routines:
prototype = self.generator.get_prototype(routine)
# C Function Header Import
headers.append(self.pyx_header.format(header_file=prefix,
prototype=prototype))
# Partition the C function arguments into categories
py_rets, py_args, py_loc, py_inf = self._partition_args(routine.arguments)
# Function prototype
name = routine.name
arg_string = ", ".join(self._prototype_arg(arg) for arg in py_args)
# Local Declarations
local_decs = []
for arg, val in py_inf.items():
proto = self._prototype_arg(arg)
mat, ind = val
local_decs.append(" cdef {0} = {1}.shape[{2}]".format(proto, mat, ind))
local_decs.extend([" cdef {0}".format(self._declare_arg(a)) for a in py_loc])
declarations = "\n".join(local_decs)
if declarations:
declarations = declarations + "\n"
# Function Body
args_c = ", ".join([self._call_arg(a) for a in routine.arguments])
rets = ", ".join([str(r.name) for r in py_rets])
if routine.results:
body = ' return %s(%s)' % (routine.name, args_c)
if rets:
body = body + ', ' + rets
else:
body = ' %s(%s)\n' % (routine.name, args_c)
body = body + ' return ' + rets
functions.append(self.pyx_func.format(name=name, arg_string=arg_string,
declarations=declarations, body=body))
# Write text to file
if self._need_numpy:
# Only import numpy if required
f.write(self.pyx_imports)
f.write('\n'.join(headers))
f.write('\n'.join(functions))
def _partition_args(self, args):
"""Group function arguments into categories."""
py_args = []
py_returns = []
py_locals = []
py_inferred = {}
for arg in args:
if isinstance(arg, OutputArgument):
py_returns.append(arg)
py_locals.append(arg)
elif isinstance(arg, InOutArgument):
py_returns.append(arg)
py_args.append(arg)
else:
py_args.append(arg)
# Find arguments that are array dimensions. These can be inferred
# locally in the Cython code.
if isinstance(arg, (InputArgument, InOutArgument)) and arg.dimensions:
dims = [d[1] + 1 for d in arg.dimensions]
sym_dims = [(i, d) for (i, d) in enumerate(dims) if
isinstance(d, Symbol)]
for (i, d) in sym_dims:
py_inferred[d] = (arg.name, i)
for arg in args:
if arg.name in py_inferred:
py_inferred[arg] = py_inferred.pop(arg.name)
# Filter inferred arguments from py_args
py_args = [a for a in py_args if a not in py_inferred]
return py_returns, py_args, py_locals, py_inferred
def _prototype_arg(self, arg):
mat_dec = "np.ndarray[{mtype}, ndim={ndim}] {name}"
np_types = {'double': 'np.double_t',
'int': 'np.int_t'}
t = arg.get_datatype('c')
if arg.dimensions:
self._need_numpy = True
ndim = len(arg.dimensions)
mtype = np_types[t]
return mat_dec.format(mtype=mtype, ndim=ndim, name=arg.name)
else:
return "%s %s" % (t, str(arg.name))
def _declare_arg(self, arg):
proto = self._prototype_arg(arg)
if arg.dimensions:
shape = '(' + ','.join(str(i[1] + 1) for i in arg.dimensions) + ')'
return proto + " = np.empty({shape})".format(shape=shape)
else:
return proto + " = 0"
def _call_arg(self, arg):
if arg.dimensions:
t = arg.get_datatype('c')
return "<{0}*> {1}.data".format(t, arg.name)
elif isinstance(arg, ResultBase):
return "&{0}".format(arg.name)
else:
return str(arg.name)
class F2PyCodeWrapper(CodeWrapper):
"""Wrapper that uses f2py"""
def __init__(self, *args, **kwargs):
ext_keys = ['include_dirs', 'library_dirs', 'libraries',
'extra_compile_args', 'extra_link_args']
msg = ('The compilation option kwarg {} is not supported with the f2py '
'backend.')
for k in ext_keys:
if k in kwargs.keys():
warn(msg.format(k))
kwargs.pop(k, None)
super(F2PyCodeWrapper, self).__init__(*args, **kwargs)
@property
def command(self):
filename = self.filename + '.' + self.generator.code_extension
args = ['-c', '-m', self.module_name, filename]
command = [sys.executable, "-c", "import numpy.f2py as f2py2e;f2py2e.main()"]+args
return command
def _prepare_files(self, routine):
pass
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name)
# Here we define a lookup of backends -> tuples of languages. For now, each
# tuple is of length 1, but if a backend supports more than one language,
# the most preferable language is listed first.
_lang_lookup = {'CYTHON': ('C99', 'C89', 'C'),
'F2PY': ('F95',),
'NUMPY': ('C99', 'C89', 'C'),
'DUMMY': ('F95',)} # Dummy here just for testing
def _infer_language(backend):
"""For a given backend, return the top choice of language"""
langs = _lang_lookup.get(backend.upper(), False)
if not langs:
raise ValueError("Unrecognized backend: " + backend)
return langs[0]
def _validate_backend_language(backend, language):
"""Throws error if backend and language are incompatible"""
langs = _lang_lookup.get(backend.upper(), False)
if not langs:
raise ValueError("Unrecognized backend: " + backend)
if language.upper() not in langs:
raise ValueError(("Backend {0} and language {1} are "
"incompatible").format(backend, language))
@cacheit
@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))
def autowrap(expr, language=None, backend='f2py', tempdir=None, args=None,
flags=None, verbose=False, helpers=None, code_gen=None, **kwargs):
"""Generates python callable binaries based on the math expression.
Parameters
----------
expr
The SymPy expression that should be wrapped as a binary routine.
language : string, optional
If supplied, (options: 'C' or 'F95'), specifies the language of the
generated code. If ``None`` [default], the language is inferred based
upon the specified backend.
backend : string, optional
Backend used to wrap the generated code. Either 'f2py' [default],
or 'cython'.
tempdir : string, optional
Path to directory for temporary files. If this argument is supplied,
the generated code and the wrapper input files are left intact in the
specified path.
args : iterable, optional
An ordered iterable of symbols. Specifies the argument sequence for the
function.
flags : iterable, optional
Additional option flags that will be passed to the backend.
verbose : bool, optional
If True, autowrap will not mute the command line backends. This can be
helpful for debugging.
helpers : 3-tuple or iterable of 3-tuples, optional
Used to define auxiliary expressions needed for the main expr. If the
main expression needs to call a specialized function it should be
passed in via ``helpers``. Autowrap will then make sure that the
compiled main expression can link to the helper routine. Items should
be 3-tuples with (<function_name>, <sympy_expression>,
<argument_tuple>). It is mandatory to supply an argument sequence to
helper routines.
code_gen : CodeGen instance
An instance of a CodeGen subclass. Overrides ``language``.
include_dirs : [string]
A list of directories to search for C/C++ header files (in Unix form
for portability).
library_dirs : [string]
A list of directories to search for C/C++ libraries at link time.
libraries : [string]
A list of library names (not filenames or paths) to link against.
extra_compile_args : [string]
Any extra platform- and compiler-specific information to use when
compiling the source files in 'sources'. For platforms and compilers
where "command line" makes sense, this is typically a list of
command-line arguments, but for other platforms it could be anything.
extra_link_args : [string]
Any extra platform- and compiler-specific information to use when
linking object files together to create the extension (or to create a
new static Python interpreter). Similar interpretation as for
'extra_compile_args'.
Examples
--------
>>> from sympy.abc import x, y, z
>>> from sympy.utilities.autowrap import autowrap
>>> expr = ((x - y + z)**(13)).expand()
>>> binary_func = autowrap(expr)
>>> binary_func(1, 4, 2)
-1.0
"""
if language:
if not isinstance(language, type):
_validate_backend_language(backend, language)
else:
language = _infer_language(backend)
# two cases 1) helpers is an iterable of 3-tuples and 2) helpers is a
# 3-tuple
if iterable(helpers) and len(helpers) != 0 and iterable(helpers[0]):
helpers = helpers if helpers else ()
else:
helpers = [helpers] if helpers else ()
args = list(args) if iterable(args, exclude=set) else args
if code_gen is None:
code_gen = get_code_generator(language, "autowrap")
CodeWrapperClass = {
'F2PY': F2PyCodeWrapper,
'CYTHON': CythonCodeWrapper,
'DUMMY': DummyWrapper
}[backend.upper()]
code_wrapper = CodeWrapperClass(code_gen, tempdir, flags if flags else (),
verbose, **kwargs)
helps = []
for name_h, expr_h, args_h in helpers:
helps.append(code_gen.routine(name_h, expr_h, args_h))
for name_h, expr_h, args_h in helpers:
if expr.has(expr_h):
name_h = binary_function(name_h, expr_h, backend='dummy')
expr = expr.subs(expr_h, name_h(*args_h))
try:
routine = code_gen.routine('autofunc', expr, args)
except CodeGenArgumentListError as e:
# if all missing arguments are for pure output, we simply attach them
# at the end and try again, because the wrappers will silently convert
# them to return values anyway.
new_args = []
for missing in e.missing_args:
if not isinstance(missing, OutputArgument):
raise
new_args.append(missing.name)
routine = code_gen.routine('autofunc', expr, args + new_args)
return code_wrapper.wrap_code(routine, helpers=helps)
@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))
def binary_function(symfunc, expr, **kwargs):
"""Returns a sympy function with expr as binary implementation
This is a convenience function that automates the steps needed to
autowrap the SymPy expression and attaching it to a Function object
with implemented_function().
Parameters
----------
symfunc : sympy Function
The function to bind the callable to.
expr : sympy Expression
The expression used to generate the function.
kwargs : dict
Any kwargs accepted by autowrap.
Examples
--------
>>> from sympy.abc import x, y
>>> from sympy.utilities.autowrap import binary_function
>>> expr = ((x - y)**(25)).expand()
>>> f = binary_function('f', expr)
>>> type(f)
<class 'sympy.core.function.UndefinedFunction'>
>>> 2*f(x, y)
2*f(x, y)
>>> f(x, y).evalf(2, subs={x: 1, y: 2})
-1.0
"""
binary = autowrap(expr, **kwargs)
return implemented_function(symfunc, binary)
#################################################################
# UFUNCIFY #
#################################################################
_ufunc_top = Template("""\
#include "Python.h"
#include "math.h"
#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/halffloat.h"
#include ${include_file}
static PyMethodDef ${module}Methods[] = {
{NULL, NULL, 0, NULL}
};""")
_ufunc_outcalls = Template("*((double *)out${outnum}) = ${funcname}(${call_args});")
_ufunc_body = Template("""\
static void ${funcname}_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
{
npy_intp i;
npy_intp n = dimensions[0];
${declare_args}
${declare_steps}
for (i = 0; i < n; i++) {
${outcalls}
${step_increments}
}
}
PyUFuncGenericFunction ${funcname}_funcs[1] = {&${funcname}_ufunc};
static char ${funcname}_types[${n_types}] = ${types}
static void *${funcname}_data[1] = {NULL};""")
_ufunc_bottom = Template("""\
#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"${module}",
NULL,
-1,
${module}Methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_${module}(void)
{
PyObject *m, *d;
${function_creation}
m = PyModule_Create(&moduledef);
if (!m) {
return NULL;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
${ufunc_init}
return m;
}
#else
PyMODINIT_FUNC init${module}(void)
{
PyObject *m, *d;
${function_creation}
m = Py_InitModule("${module}", ${module}Methods);
if (m == NULL) {
return;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
${ufunc_init}
}
#endif\
""")
_ufunc_init_form = Template("""\
ufunc${ind} = PyUFunc_FromFuncAndData(${funcname}_funcs, ${funcname}_data, ${funcname}_types, 1, ${n_in}, ${n_out},
PyUFunc_None, "${module}", ${docstring}, 0);
PyDict_SetItemString(d, "${funcname}", ufunc${ind});
Py_DECREF(ufunc${ind});""")
_ufunc_setup = Template("""\
def configuration(parent_package='', top_path=None):
import numpy
from numpy.distutils.misc_util import Configuration
config = Configuration('',
parent_package,
top_path)
config.add_extension('${module}', sources=['${module}.c', '${filename}.c'])
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(configuration=configuration)""")
class UfuncifyCodeWrapper(CodeWrapper):
"""Wrapper for Ufuncify"""
def __init__(self, *args, **kwargs):
ext_keys = ['include_dirs', 'library_dirs', 'libraries',
'extra_compile_args', 'extra_link_args']
msg = ('The compilation option kwarg {} is not supported with the numpy'
' backend.')
for k in ext_keys:
if k in kwargs.keys():
warn(msg.format(k))
kwargs.pop(k, None)
super(UfuncifyCodeWrapper, self).__init__(*args, **kwargs)
@property
def command(self):
command = [sys.executable, "setup.py", "build_ext", "--inplace"]
return command
def wrap_code(self, routines, helpers=None):
# This routine overrides CodeWrapper because we can't assume funcname == routines[0].name
# Therefore we have to break the CodeWrapper private API.
# There isn't an obvious way to extend multi-expr support to
# the other autowrap backends, so we limit this change to ufuncify.
helpers = helpers if helpers is not None else []
# We just need a consistent name
funcname = 'wrapped_' + str(id(routines) + id(helpers))
workdir = self.filepath or tempfile.mkdtemp("_sympy_compile")
if not os.access(workdir, os.F_OK):
os.mkdir(workdir)
oldwork = os.getcwd()
os.chdir(workdir)
try:
sys.path.append(workdir)
self._generate_code(routines, helpers)
self._prepare_files(routines, funcname)
self._process_files(routines)
mod = __import__(self.module_name)
finally:
sys.path.remove(workdir)
CodeWrapper._module_counter += 1
os.chdir(oldwork)
if not self.filepath:
try:
shutil.rmtree(workdir)
except OSError:
# Could be some issues on Windows
pass
return self._get_wrapped_function(mod, funcname)
def _generate_code(self, main_routines, helper_routines):
all_routines = main_routines + helper_routines
self.generator.write(
all_routines, self.filename, True, self.include_header,
self.include_empty)
def _prepare_files(self, routines, funcname):
# C
codefilename = self.module_name + '.c'
with open(codefilename, 'w') as f:
self.dump_c(routines, f, self.filename, funcname=funcname)
# setup.py
with open('setup.py', 'w') as f:
self.dump_setup(f)
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name)
def dump_setup(self, f):
setup = _ufunc_setup.substitute(module=self.module_name,
filename=self.filename)
f.write(setup)
def dump_c(self, routines, f, prefix, funcname=None):
"""Write a C file with python wrappers
This file contains all the definitions of the routines in c code.
Arguments
---------
routines
List of Routine instances
f
File-like object to write the file to
prefix
The filename prefix, used to name the imported module.
funcname
Name of the main function to be returned.
"""
if (funcname is None) and (len(routines) == 1):
funcname = routines[0].name
elif funcname is None:
msg = 'funcname must be specified for multiple output routines'
raise ValueError(msg)
functions = []
function_creation = []
ufunc_init = []
module = self.module_name
include_file = "\"{0}.h\"".format(prefix)
top = _ufunc_top.substitute(include_file=include_file, module=module)
name = funcname
# Partition the C function arguments into categories
# Here we assume all routines accept the same arguments
r_index = 0
py_in, _ = self._partition_args(routines[0].arguments)
n_in = len(py_in)
n_out = len(routines)
# Declare Args
form = "char *{0}{1} = args[{2}];"
arg_decs = [form.format('in', i, i) for i in range(n_in)]
arg_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)])
declare_args = '\n '.join(arg_decs)
# Declare Steps
form = "npy_intp {0}{1}_step = steps[{2}];"
step_decs = [form.format('in', i, i) for i in range(n_in)]
step_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)])
declare_steps = '\n '.join(step_decs)
# Call Args
form = "*(double *)in{0}"
call_args = ', '.join([form.format(a) for a in range(n_in)])
# Step Increments
form = "{0}{1} += {0}{1}_step;"
step_incs = [form.format('in', i) for i in range(n_in)]
step_incs.extend([form.format('out', i, i) for i in range(n_out)])
step_increments = '\n '.join(step_incs)
# Types
n_types = n_in + n_out
types = "{" + ', '.join(["NPY_DOUBLE"]*n_types) + "};"
# Docstring
docstring = '"Created in SymPy with Ufuncify"'
# Function Creation
function_creation.append("PyObject *ufunc{0};".format(r_index))
# Ufunc initialization
init_form = _ufunc_init_form.substitute(module=module,
funcname=name,
docstring=docstring,
n_in=n_in, n_out=n_out,
ind=r_index)
ufunc_init.append(init_form)
outcalls = [_ufunc_outcalls.substitute(
outnum=i, call_args=call_args, funcname=routines[i].name) for i in
range(n_out)]
body = _ufunc_body.substitute(module=module, funcname=name,
declare_args=declare_args,
declare_steps=declare_steps,
call_args=call_args,
step_increments=step_increments,
n_types=n_types, types=types,
outcalls='\n '.join(outcalls))
functions.append(body)
body = '\n\n'.join(functions)
ufunc_init = '\n '.join(ufunc_init)
function_creation = '\n '.join(function_creation)
bottom = _ufunc_bottom.substitute(module=module,
ufunc_init=ufunc_init,
function_creation=function_creation)
text = [top, body, bottom]
f.write('\n\n'.join(text))
def _partition_args(self, args):
"""Group function arguments into categories."""
py_in = []
py_out = []
for arg in args:
if isinstance(arg, OutputArgument):
py_out.append(arg)
elif isinstance(arg, InOutArgument):
raise ValueError("Ufuncify doesn't support InOutArguments")
else:
py_in.append(arg)
return py_in, py_out
@cacheit
@doctest_depends_on(exe=('f2py', 'gfortran', 'gcc'), modules=('numpy',))
def ufuncify(args, expr, language=None, backend='numpy', tempdir=None,
flags=None, verbose=False, helpers=None, **kwargs):
"""Generates a binary function that supports broadcasting on numpy arrays.
Parameters
----------
args : iterable
Either a Symbol or an iterable of symbols. Specifies the argument
sequence for the function.
expr
A SymPy expression that defines the element wise operation.
language : string, optional
If supplied, (options: 'C' or 'F95'), specifies the language of the
generated code. If ``None`` [default], the language is inferred based
upon the specified backend.
backend : string, optional
Backend used to wrap the generated code. Either 'numpy' [default],
'cython', or 'f2py'.
tempdir : string, optional
Path to directory for temporary files. If this argument is supplied,
the generated code and the wrapper input files are left intact in
the specified path.
flags : iterable, optional
Additional option flags that will be passed to the backend.
verbose : bool, optional
If True, autowrap will not mute the command line backends. This can
be helpful for debugging.
helpers : iterable, optional
Used to define auxiliary expressions needed for the main expr. If
the main expression needs to call a specialized function it should
be put in the ``helpers`` iterable. Autowrap will then make sure
that the compiled main expression can link to the helper routine.
Items should be tuples with (<funtion_name>, <sympy_expression>,
<arguments>). It is mandatory to supply an argument sequence to
helper routines.
kwargs : dict
These kwargs will be passed to autowrap if the `f2py` or `cython`
backend is used and ignored if the `numpy` backend is used.
Note
----
The default backend ('numpy') will create actual instances of
``numpy.ufunc``. These support ndimensional broadcasting, and implicit type
conversion. Use of the other backends will result in a "ufunc-like"
function, which requires equal length 1-dimensional arrays for all
arguments, and will not perform any type conversions.
References
----------
[1] http://docs.scipy.org/doc/numpy/reference/ufuncs.html
Examples
========
>>> from sympy.utilities.autowrap import ufuncify
>>> from sympy.abc import x, y
>>> import numpy as np
>>> f = ufuncify((x, y), y + x**2)
>>> type(f)
<class 'numpy.ufunc'>
>>> f([1, 2, 3], 2)
array([ 3., 6., 11.])
>>> f(np.arange(5), 3)
array([ 3., 4., 7., 12., 19.])
For the 'f2py' and 'cython' backends, inputs are required to be equal length
1-dimensional arrays. The 'f2py' backend will perform type conversion, but
the Cython backend will error if the inputs are not of the expected type.
>>> f_fortran = ufuncify((x, y), y + x**2, backend='f2py')
>>> f_fortran(1, 2)
array([ 3.])
>>> f_fortran(np.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]))
array([ 2., 6., 12.])
>>> f_cython = ufuncify((x, y), y + x**2, backend='Cython')
>>> f_cython(1, 2) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int)
>>> f_cython(np.array([1.0]), np.array([2.0]))
array([ 3.])
"""
if isinstance(args, Symbol):
args = (args,)
else:
args = tuple(args)
if language:
_validate_backend_language(backend, language)
else:
language = _infer_language(backend)
helpers = helpers if helpers else ()
flags = flags if flags else ()
if backend.upper() == 'NUMPY':
# maxargs is set by numpy compile-time constant NPY_MAXARGS
# If a future version of numpy modifies or removes this restriction
# this variable should be changed or removed
maxargs = 32
helps = []
for name, expr, args in helpers:
helps.append(make_routine(name, expr, args))
code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"), tempdir,
flags, verbose)
if not isinstance(expr, (list, tuple)):
expr = [expr]
if len(expr) == 0:
raise ValueError('Expression iterable has zero length')
if (len(expr) + len(args)) > maxargs:
msg = ('Cannot create ufunc with more than {0} total arguments: '
'got {1} in, {2} out')
raise ValueError(msg.format(maxargs, len(args), len(expr)))
routines = [make_routine('autofunc{}'.format(idx), exprx, args) for
idx, exprx in enumerate(expr)]
return code_wrapper.wrap_code(routines, helpers=helps)
else:
# Dummies are used for all added expressions to prevent name clashes
# within the original expression.
y = IndexedBase(Dummy('y'))
m = Dummy('m', integer=True)
i = Idx(Dummy('i', integer=True), m)
f_dummy = Dummy('f')
f = implemented_function('%s_%d' % (f_dummy.name, f_dummy.dummy_index), Lambda(args, expr))
# For each of the args create an indexed version.
indexed_args = [IndexedBase(Dummy(str(a))) for a in args]
# Order the arguments (out, args, dim)
args = [y] + indexed_args + [m]
args_with_indices = [a[i] for a in indexed_args]
return autowrap(Eq(y[i], f(*args_with_indices)), language, backend,
tempdir, args, flags, verbose, helpers, **kwargs)
| 36.793852 | 115 | 0.603111 |
f11fe096d3440dc44ebba93de62c649a59e23971 | 1,500 | py | Python | contributions_rnn/core/metrics.py | MinCiencia/ECQQ | f93a01ce2dd140d073bd81afb9b4733c1d8a34c3 | [
"CC0-1.0"
] | 4 | 2021-10-05T00:55:28.000Z | 2021-12-21T10:56:14.000Z | contributions_rnn/core/metrics.py | MinCiencia/ECQQ | f93a01ce2dd140d073bd81afb9b4733c1d8a34c3 | [
"CC0-1.0"
] | null | null | null | contributions_rnn/core/metrics.py | MinCiencia/ECQQ | f93a01ce2dd140d073bd81afb9b4733c1d8a34c3 | [
"CC0-1.0"
] | 1 | 2022-01-14T17:31:16.000Z | 2022-01-14T17:31:16.000Z | import tensorflow as tf
class MaskedACC(tf.keras.metrics.Metric):
def __init__(self, name="Accuracy", **kwargs):
super(MaskedACC, self).__init__(name=name, **kwargs)
self.acc_value = tf.constant(0.)
def update_state(self, y_true, y_pred, sample_weight=None):
real = tf.slice(y_true, [0,0,0], [-1,-1,1])
mask = tf.slice(y_true, [0,0,1], [-1,-1,1])
real = tf.cast(real, dtype=tf.int64)
mask = tf.cast(mask, dtype=tf.bool)
real = tf.squeeze(real)
mask = tf.squeeze(mask)
accuracies = tf.equal(real, tf.argmax(y_pred, axis=2))
accuracies = tf.math.logical_and(mask, accuracies)
accuracies = tf.cast(accuracies, dtype=tf.float32)
mask = tf.cast(mask, dtype=tf.float32)
self.acc_value = tf.reduce_sum(accuracies)/tf.reduce_sum(mask)
def result(self):
return self.acc_value
class CustomAccuracy(tf.keras.metrics.Metric):
def __init__(self, name="Accuracy", **kwargs):
super(CustomAccuracy, self).__init__(name=name, **kwargs)
self.acc_value = 0.
def update_state(self, y_true, y_pred, sample_weight=None):
y_pred_labels = tf.argmax(y_pred, axis=1)
y_real_labels = tf.argmax(y_true, axis=1)
accuracies = tf.equal(y_real_labels, y_pred_labels)
accuracies = tf.cast(accuracies, dtype=tf.float32)
self.acc_value = tf.reduce_mean(accuracies)
def result(self):
return self.acc_value
| 37.5 | 70 | 0.637333 |
54b62fb420ad4b077c6414d49daabaf80869b5f1 | 181 | py | Python | python/gdal_cookbook/cookbook_general/check_version.py | zeroam/TIL | 43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1 | [
"MIT"
] | null | null | null | python/gdal_cookbook/cookbook_general/check_version.py | zeroam/TIL | 43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1 | [
"MIT"
] | null | null | null | python/gdal_cookbook/cookbook_general/check_version.py | zeroam/TIL | 43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1 | [
"MIT"
] | null | null | null | import sys
from osgeo import gdal
version_num = int(gdal.VersionInfo('VERSION_NUM'))
if version_num < 1100000:
sys.exit('ERROR: Python bindings of GDAL 1.10 or later required') | 30.166667 | 69 | 0.762431 |
5f236e7f47e529efde878e275e891e7029b3da3f | 28,237 | py | Python | AnkleSegmentation/extract_data_deepLearning.py | Benjamin-Fouquet/dynMRI | c80b48cee834e2042e95241701ce064c22e3d3d1 | [
"CECILL-B"
] | 6 | 2017-11-23T13:02:43.000Z | 2021-06-23T03:26:10.000Z | AnkleSegmentation/extract_data_deepLearning.py | Benjamin-Fouquet/dynMRI | c80b48cee834e2042e95241701ce064c22e3d3d1 | [
"CECILL-B"
] | null | null | null | AnkleSegmentation/extract_data_deepLearning.py | Benjamin-Fouquet/dynMRI | c80b48cee834e2042e95241701ce064c22e3d3d1 | [
"CECILL-B"
] | 3 | 2019-10-21T16:00:24.000Z | 2021-06-16T08:45:12.000Z | import os
import sys
import numpy as np
from extract_PatchesSegmentationHR import get_hcp_2dpatches_SegmentationHR
from extract_Patches import get_hcp_2dpatches
from extract_slices import get_hcp_coupes2d
import argparse
import nibabel as nib
from joblib import dump
parser = argparse.ArgumentParser()
parser.add_argument("Problem", help="Type of problem for the extraction (SegmentationHR/Reconstruction/SegmentationLR)")
parser.add_argument("Type of extraction", help="Type of data to extract (slices or patches)")
args = parser.parse_args()
"""
Ce script permet l'extraction des données nécessaires aux différents problèmes d'apprentissage profond.
Pour l'exécuter, l'utilisateur doit préciser:
- pour quel type de problème il souhaite extraire des données: SegmentationHR, Reconstruction ou SegmentationLR
- quels types de données il souhaite extraire: patches ou slices (l'extraction de slices n'a été implémentée que pour la segmentation sur IRM statique)
"""
if(sys.argv[1] == 'Reconstruction'):
""""""""""""""""Pipeline 2 : LR -> HR"""""""""""""""""""""""""""""""""""""""""
registrationDirectory = '/homes/p20coupe/Bureau/Local/Equinus_BIDS_dataset/derivatives/'
#seuil de correlation minimal entre le patch BR et le patchHR pour stocker les patchs et les utiliser lors de l'apprentissage
niveau_corr = 0.6
sujets = os.listdir(registrationDirectory)
for i in range(len(sujets)):
#Pas de registration fait pour ces sujets (E10 aucun registration correct)
if(sujets[i]!='sub_E09' and sujets[i]!='sub_E11' and sujets[i]!='sub_E12' and sujets[i]!='sub_E13' and sujets[i]!='sub_E10'):
print(sujets[i])
patches_HR_calcaneus=[]
patches_HR_talus=[]
patches_HR_tibia=[]
patches_BR_calcaneus=[]
patches_BR_talus=[]
patches_BR_tibia=[]
correlation_calcaneus=[]
correlation_talus=[]
correlation_tibia=[]
#cree repertoire pour patchs
if not os.path.exists(os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches')):
os.mkdir(os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches'))
#Recupere volume dynamique LR
sequences = os.listdir(os.path.join(registrationDirectory,sujets[i],'volumes'))
for seq in sequences:
if not(sujets[i]=='sub_T01' and seq.find('flipCorrected')==-1):
print(seq)
volumes = os.listdir(os.path.join(registrationDirectory,sujets[i],'volumes',seq,'volumes3D'))
for k in range(len(volumes)):
print(volumes[k])
T1s = []
dynamique = os.path.join(registrationDirectory,sujets[i],'volumes',seq,'volumes3D',volumes[k])
T2s = nib.load(dynamique).get_fdata()
#Recupere registration HR des volumes (registration du calcaneus) et le masque du calcaneus sur le registration
registrations = os.listdir(os.path.join(registrationDirectory, sujets[i],'correct_registrations',seq))
for j in range(len(registrations)):
if registrations[j].find(volumes[k].replace('.nii.gz','')) != -1 and registrations[j].find('registration_calcaneus.nii.gz')!=-1:
T1s= nib.load(os.path.join(registrationDirectory, sujets[i],'correct_registrations',seq,registrations[j])).get_fdata()
elif registrations[j].find(volumes[k].replace('.nii.gz','')) != -1 and registrations[j].find('segment_calcaneus.nii.gz')!=-1:
masks= nib.load(os.path.join(registrationDirectory, sujets[i],'correct_registrations',seq,registrations[j])).get_fdata()
#Si le registration de ce volume pour cet os existe (donc qu'il est correct), ob peut extraire les données
if not T1s==[]:
donnees = ([T1s],[T2s],[masks])
print("calcaneus")
#extraction patchs 32x32
(T1,T2)=get_hcp_2dpatches('Reconstruction',0.7,32,8000,donnees)
for l in range(T1.shape[0]):
cor = np.corrcoef(T1[l,:,:].flat, T2[l,:,:].flat)[0,1]
#si la correlation entre les deux patchs est inférieure au seuil de corrélation, on ne garde pas les patchs pour l'apprentissage
if cor>niveau_corr:
patches_HR_calcaneus.append(T1[l])
patches_BR_calcaneus.append(T2[l])
correlation_calcaneus.append(cor)
#Recupere registration HR des volumes (registration du talus) et le masque du talus sur le registration
T1s= []
for j in range(len(registrations)):
if registrations[j].find(volumes[k].replace('.nii.gz','')) != -1 and registrations[j].find('registration_talus.nii.gz')!=-1:
T1s= nib.load(os.path.join(registrationDirectory, sujets[i],'correct_registrations',seq,registrations[j])).get_fdata()
elif registrations[j].find(volumes[k].replace('.nii.gz','')) != -1 and registrations[j].find('segment_talus.nii.gz')!=-1:
masks= nib.load(os.path.join(registrationDirectory, sujets[i],'correct_registrations',seq,registrations[j])).get_fdata()
if not T1s==[]:
donnees = ([T1s],[T2s],[masks])
print("talus")
#extraction patchs 32x32
(T1,T2)=get_hcp_2dpatches('Reconstruction',0.5,32,14000,donnees)
for l in range(T1.shape[0]):
cor = np.corrcoef(T1[l,:,:].flat, T2[l,:,:].flat)[0,1]
if cor>niveau_corr:
patches_HR_talus.append(T1[l])
patches_BR_talus.append(T2[l])
correlation_talus.append(cor)
#Recupere registration HR des volumes (registration du tibia) et le masque du tibia sur le registration
T1s=[]
for j in range(len(registrations)):
if registrations[j].find(volumes[k].replace('.nii.gz','')) != -1 and registrations[j].find('registration_tibia.nii.gz')!=-1:
T1s= nib.load(os.path.join(registrationDirectory, sujets[i],'correct_registrations',seq,registrations[j])).get_fdata()
elif registrations[j].find(volumes[k].replace('.nii.gz','')) != -1 and registrations[j].find('segment_tibia.nii.gz')!=-1:
masks= nib.load(os.path.join(registrationDirectory, sujets[i],'correct_registrations',seq,registrations[j])).get_fdata()
if not T1s==[]:
donnees = ([T1s],[T2s],[masks])
print("tibia")
#extraction patchs 32x32
(T1,T2)=get_hcp_2dpatches('Reconstruction',0.6,32,8000,donnees)
for l in range(T1.shape[0]):
cor = np.corrcoef(T1[l,:,:].flat, T2[l,:,:].flat)[0,1]
if cor>niveau_corr:
patches_HR_tibia.append(T1[l])
patches_BR_tibia.append(T2[l])
correlation_tibia.append(cor)
#cree repertoires pour les 3 os
if not os.path.exists(os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','calcaneus')):
os.mkdir(os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','calcaneus'))
if not os.path.exists(os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','talus')):
os.mkdir(os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','talus'))
if not os.path.exists(os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','tibia')):
os.mkdir(os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','tibia'))
#stockage des patchs dans fichiers pickle
dump(correlation_calcaneus, os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','calcaneus','corr_calcaneus_'+sujets[i]+'.joblib'))
dump(correlation_talus, os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','talus','corr_talus_'+sujets[i]+'.joblib'))
dump(correlation_tibia, os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','tibia','corr_tibia_'+sujets[i]+'.joblib'))
dump(patches_HR_calcaneus, os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','calcaneus','HR_calcaneus_'+sujets[i]+'.joblib'))
dump(patches_HR_talus, os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','talus','HR_talus_'+sujets[i]+'.joblib'))
dump(patches_HR_tibia, os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','tibia','HR_tibia_'+sujets[i]+'.joblib'))
dump(patches_BR_calcaneus, os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','calcaneus','BR_calcaneus_'+sujets[i]+'.joblib'))
dump(patches_BR_talus, os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','talus','BR_talus_'+sujets[i]+'.joblib'))
dump(patches_BR_tibia, os.path.join(registrationDirectory,sujets[i],'DatasetReconstruction_patches','tibia','BR_tibia_'+sujets[i]+'.joblib'))
if(sys.argv[1]=='SegmentationHR'):
""""""""""""""""Pipeline 1 : Segmentation des IRMs statiques HR"""""""""""""""""""""""""""""""""""""""""
SegmentDirectory = '/homes/p20coupe/Bureau/Local/Equinus_BIDS_dataset/derivatives/'
dataDirectory = '/homes/p20coupe/Bureau/Local/Equinus_BIDS_dataset/sourcedata/'
patches_HR=[]
patches_segHR=[]
sujets = os.listdir(SegmentDirectory)
for i in range(len(sujets)):
#header incorrect pour sub_E09 et sub_E13 / pas de segmentation de l'IRM statique T1 pour sub_E11 / 2 IRMs pour sub_E12 (une sans calcaneus)
if(sujets[i]!='sub_E09' and sujets[i]!='sub_E11' and sujets[i]!='sub_E12' and sujets[i]!='sub_E13'):
T1=[]
T2=[]
T3=[]
T4=[]
patches_HR=[]
patches_segHR_calcaneus=[]
patches_segHR_talus=[]
patches_segHR_tibia=[]
print(sujets[i])
#Cree repertoire pour patchs ou pour les coupes 2D
if(sys.argv[2]=='patches'):
if not os.path.exists(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_patches')):
os.mkdir(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_patches'))
elif(sys.argv[2]=='slices'):
if not os.path.exists(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_slices')):
os.mkdir(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_slices'))
#Recupere image statique
suffixe = '_static_3DT1'
if os.path.exists(os.path.join(dataDirectory, sujets[i],sujets[i]+suffixe+'_flipCorrected.nii.gz')):
file_in = os.path.join(dataDirectory, sujets[i],sujets[i]+suffixe+'_flipCorrected.nii.gz')
else:
file_in = os.path.join(dataDirectory, sujets[i], sujets[i]+suffixe + '.nii.gz')
print(file_in)
T2s = nib.load(file_in).get_fdata()
#Recupere masque cheville
masks= nib.load(os.path.join(SegmentDirectory,sujets[i],'footmask.nii.gz')).get_fdata()
#Recupere masque calcaneus
bone = 'calcaneus'
suffixe = sujets[i] + '_static_3DT1_segment_' + bone
if os.path.exists(os.path.join(SegmentDirectory, sujets[i], suffixe+'_flipped_binarized.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_flipped_binarized.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i], suffixe+'_binarized_flipCorrected.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_binarized_flipCorrected.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i], suffixe+'_flipCorrected.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_flipCorrected.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i],suffixe+'_binarized.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_binarized.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i],suffixe+'.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe + '.nii.gz')
else:
file_seg = os.path.join(SegmentDirectory, sujets[i], sujets[i]+'_static_3DT1_segment_smooth_' + bone + '.nii.gz')
print(file_seg)
T1s=nib.load(file_seg).get_fdata()
#Recupere masque talus
bone = 'talus'
suffixe = sujets[i] + '_static_3DT1_segment_' + bone
if os.path.exists(os.path.join(SegmentDirectory, sujets[i], suffixe+'_flipped_binarized.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_flipped_binarized.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i], suffixe+'_binarized_flipCorrected.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_binarized_flipCorrected.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i], suffixe+'_flipCorrected.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_flipCorrected.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i],suffixe+'_binarized.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_binarized.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i],suffixe+'.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe + '.nii.gz')
else:
file_seg = os.path.join(SegmentDirectory, sujets[i], sujets[i]+'_static_3DT1_segment_smooth_' + bone + '.nii.gz')
print(file_seg)
T3s=nib.load(file_seg).get_fdata()
#Recupere masque tibia
bone = 'tibia'
suffixe = sujets[i] + '_static_3DT1_segment_' + bone
if os.path.exists(os.path.join(SegmentDirectory, sujets[i], suffixe+'_flipped_binarized.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_flipped_binarized.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i], suffixe+'_binarized_flipCorrected.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_binarized_flipCorrected.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i], suffixe+'_flipCorrected.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_flipCorrected.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i],suffixe+'_binarized.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe+'_binarized.nii.gz')
elif os.path.exists(os.path.join(SegmentDirectory, sujets[i],suffixe+'.nii.gz')):
file_seg = os.path.join(SegmentDirectory, sujets[i],suffixe + '.nii.gz')
else:
file_seg = os.path.join(SegmentDirectory, sujets[i], sujets[i]+'_static_3DT1_segment_smooth_' + bone + '.nii.gz')
print(file_seg)
T4s=nib.load(file_seg).get_fdata()
#On va extraire pour 1 patch de l'IRM statique, des patchs de segmentation des 3 os -> les 3 os ne sont pas forcément sur tous les patchs
donnees = ([T1s],[T2s],[T3s],[T4s],[masks])
#Extraction des coupes 2D et des 3 segmentations de celles-ci
if(sys.argv[2]=="slices"):
(T1,T2,T3,T4)=get_hcp_coupes2d(donnees)
print(T1.shape)
for l in range(T1.shape[0]):
patches_HR.append(T2[l])
patches_segHR_calcaneus.append(T1[l])
patches_segHR_talus.append(T3[l])
patches_segHR_tibia.append(T4[l])
#stockage des coupes 2D dans un fichier pickle
dump(patches_HR, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_slices','HR_PipelineSegHR'+sujets[i]+'.joblib'))
dump(patches_segHR_calcaneus, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_slices','seg_PipelineSegHR'+sujets[i]+'calcaneus.joblib'))
dump(patches_segHR_talus, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_slices','seg_PipelineSegHR'+sujets[i]+'talus.joblib'))
dump(patches_segHR_tibia, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_slices','seg_PipelineSegHR'+sujets[i]+'tibia.joblib'))
#Extraction de patchs 128x128 de l'IRM statique et des 3 segmentations associées
elif(sys.argv[2]=="patches"):
(T1,T2,T3,T4)=get_hcp_2dpatches_SegmentationHR(0.75,128,300,donnees)
for l in range(T1.shape[0]):
patches_HR.append(T2[l])
patches_segHR_calcaneus.append(T1[l])
patches_segHR_talus.append(T3[l])
patches_segHR_tibia.append(T4[l])
#stockage des patchs 128x128 dans un fichier pickle
dump(patches_HR, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_patches','HR_PipelineSegHR'+sujets[i]+'.joblib'))
dump(patches_segHR_calcaneus, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_patches','seg_PipelineSegHR'+sujets[i]+'calcaneus.joblib'))
dump(patches_segHR_talus, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_patches','seg_PipelineSegHR'+sujets[i]+'talus.joblib'))
dump(patches_segHR_tibia, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationHR_patches','seg_PipelineSegHR'+sujets[i]+'tibia.joblib'))
else:
print("Please enter a correct type of data to extract: slices ou patches")
quit()
if(sys.argv[1]=='SegmentationLR'):
""""""""""""""""Pipeline 3 : Segmentation des IRMs dynamiques LR"""""""""""""""""""""""""""""""""""""""""
dataDirectory = '/homes/p20coupe/Bureau/Local/Equinus_BIDS_dataset/sourcedata/'
SegmentDirectory = '/homes/p20coupe/Bureau/Local/Equinus_BIDS_dataset/derivatives/'
sujets = os.listdir(SegmentDirectory)
for i in range(len(sujets)):
#Pas de registration fait pour ces sujets (E10 aucun registration correct)
if(sujets[i]!='sub_E09' and sujets[i]!='sub_E11' and sujets[i]!='sub_E12' and sujets[i]!='sub_E13' and sujets[i]!='sub_E10'):
print(sujets[i])
patches_BR_calcaneus=[]
patches_BR_talus=[]
patches_BR_tibia=[]
patches_segBR_calcaneus=[]
patches_segBR_talus=[]
patches_segBR_tibia=[]
#Cree repertoire pour patchs
if not os.path.exists(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches')):
os.mkdir(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches'))
#recupere volumes dynamiques 3D LR
images = os.listdir(os.path.join(dataDirectory, sujets[i]))
for j in range(len(images)):
#recupere les irms dynamiques MovieClear
if (images[j].find('MovieClear')!=-1 and sujets[i]!='sub_T01') or (images[j].find('MovieClear')!=-1 and images[j].find('flipCorrected')!=-1) :
if not(sujets[i]=='sub_E03' and images[j].find('10')!=-1):
file_ref = images[j]
volumes = os.listdir(os.path.join(SegmentDirectory,sujets[i],'volumes',images[j].replace('.nii.gz',''),'volumes3D'))
for k in range(len(volumes)):
T1s=[]
T2s=[]
T3s=[]
T4s=[]
if volumes[k].find(file_ref.replace('.nii.gz',''))!=-1 :
T2s= nib.load(os.path.join(SegmentDirectory,sujets[i],'volumes',images[j].replace('.nii.gz',''),'volumes3D',volumes[k])).get_fdata()
#Recupere masque cheville
masks= nib.load(os.path.join(SegmentDirectory,sujets[i],'volumes',images[j].replace('.nii.gz',''),'footmask','footmask'+volumes[k])).get_fdata()
#Recupere masque calcaneus recalé
bone = 'calcaneus'
suffixe= volumes[k].replace('.nii.gz','')+'_registration_segment_' + bone+'.nii.gz'
if os.path.exists(os.path.join(SegmentDirectory, sujets[i],'correct_registrations',images[j].replace('.nii.gz',''), suffixe)):
file_seg = os.path.join(SegmentDirectory, sujets[i],'correct_registrations',images[j].replace('.nii.gz',''), suffixe)
T1s=nib.load(file_seg).get_fdata()
#Recupere masque talus recalé
bone = 'talus'
suffixe= volumes[k].replace('.nii.gz','')+'_registration_segment_' + bone+'.nii.gz'
if os.path.exists(os.path.join(SegmentDirectory, sujets[i],'correct_registrations',images[j].replace('.nii.gz',''), suffixe)):
file_seg = os.path.join(SegmentDirectory, sujets[i],'correct_registrations',images[j].replace('.nii.gz',''), suffixe)
T3s=nib.load(file_seg).get_fdata()
#Recupere masque tibia recalé
bone = 'tibia'
suffixe= volumes[k].replace('.nii.gz','')+'_registration_segment_' + bone+'.nii.gz'
if os.path.exists(os.path.join(SegmentDirectory, sujets[i],'correct_registrations',images[j].replace('.nii.gz',''), suffixe)):
file_seg = os.path.join(SegmentDirectory, sujets[i],'correct_registrations',images[j].replace('.nii.gz',''), suffixe)
T4s=nib.load(file_seg).get_fdata()
"""Pour ce problème, on extrait pour un patch de l'IRM statique que les patchs de segmentation des os pour lesquels le registration a fonctionné"""
#extraction patchs 128x128 calcaneus:
if not T1s==[]:
donnees=([T1s],[T2s],[masks])
(T1,T2)=get_hcp_2dpatches('SegmentationLR',0.75,128,300,donnees)
for l in range(T2.shape[0]):
patches_BR_calcaneus.append(T2[l])
patches_segBR_calcaneus.append(T1[l])
#extraction patchs 128x128 talus
if not T3s==[]:
donnees=([T3s],[T2s],[masks])
(T1,T2)=get_hcp_2dpatches('SegmentationLR',0.75,128,300,donnees)
for l in range(T2.shape[0]):
patches_BR_talus.append(T2[l])
patches_segBR_talus.append(T1[l])
#extraction patchs 128x128 tibia
if not T4s==[]:
donnees=([T4s],[T2s],[masks])
(T1,T2)=get_hcp_2dpatches('SegmentationLR',0.75,128,300,donnees)
for l in range(T2.shape[0]):
patches_BR_tibia.append(T2[l])
patches_segBR_tibia.append(T1[l])
#cree repertoires pour les 3 os
if not os.path.exists(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','calcaneus')):
os.mkdir(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','calcaneus'))
if not os.path.exists(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','talus')):
os.mkdir(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','talus'))
if not os.path.exists(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','tibia')):
os.mkdir(os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','tibia'))
#stockage des patchs 128x128 dans fichiers pickle
dump(patches_BR_calcaneus,os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','calcaneus','BR_calcaneus_PipelineSegBR_'+sujets[i]+'.joblib'))
dump(patches_segBR_calcaneus, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','calcaneus','seg_PipelineSegBR_calcaneus_'+sujets[i]+'.joblib'))
dump(patches_BR_talus, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','talus','BR_talus_PipelineSegBR_'+sujets[i]+'.joblib'))
dump(patches_segBR_talus, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','talus','seg_PipelineSegBR_talus_'+sujets[i]+'.joblib'))
dump(patches_BR_tibia, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','tibia','BR_tibia_PipelineSegBR_'+sujets[i]+'.joblib'))
dump(patches_segBR_tibia, os.path.join(SegmentDirectory,sujets[i],'DatasetSegmentationLR_patches','tibia','seg_PipelineSegBR_tibia_'+sujets[i]+'.joblib'))
#Le type de problème rentré par l'utilisateur est incorrect
else:
print("Please enter a correct type of problem: SegmentationHR, Reconstruction,SegmentationLR") | 70.241294 | 179 | 0.571413 |
7c86d7967ac38697f069c1caf99de9ec998bc176 | 3,880 | py | Python | mxfusion/inference/prediction.py | JeremiasKnoblauch/MXFusion | af6223e9636b055d029d136dd7ae023b210b4560 | [
"Apache-2.0"
] | 2 | 2019-05-31T09:50:47.000Z | 2021-03-06T09:38:47.000Z | mxfusion/inference/prediction.py | JeremiasKnoblauch/MXFusion | af6223e9636b055d029d136dd7ae023b210b4560 | [
"Apache-2.0"
] | null | null | null | mxfusion/inference/prediction.py | JeremiasKnoblauch/MXFusion | af6223e9636b055d029d136dd7ae023b210b4560 | [
"Apache-2.0"
] | 1 | 2019-05-30T09:39:46.000Z | 2019-05-30T09:39:46.000Z | # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
# ==============================================================================
from ..components import FunctionEvaluation, Distribution
from ..inference.inference_alg import SamplingAlgorithm
from ..modules.module import Module
from ..common.exceptions import InferenceError
class ModulePredictionAlgorithm(SamplingAlgorithm):
"""
A prediction algorithm for modules. The algorithm evaluates all the functions, draws samples from distributions and
runs the predict method on all the modules.
:param model: the definition of the probabilistic model
:type model: Model
:param observed: A list of observed variables
:type observed: [Variable]
:param num_samples: the number of samples used in estimating the variational lower bound
:type num_samples: int
:param target_variables: (optional) the target variables to sample
:type target_variables: [UUID]
:param extra_graphs: a list of extra FactorGraph used in the inference
algorithm.
:type extra_graphs: [FactorGraph]
"""
def compute(self, F, variables):
"""
Compute the inference algorithm
:param F: the execution context (mxnet.ndarray or mxnet.symbol)
:type F: Python module
:param variables: the set of MXNet arrays that holds the values of
variables at runtime.
:type variables: {str(UUID): MXNet NDArray or MXNet Symbol}
:returns: the outcome of the inference algorithm
:rtype: mxnet.ndarray.ndarray.NDArray or mxnet.symbol.symbol.Symbol
"""
outcomes = {}
for f in self.model.ordered_factors:
if isinstance(f, FunctionEvaluation):
outcome = f.eval(F=F, variables=variables,
always_return_tuple=True)
outcome_uuid = [v.uuid for _, v in f.outputs]
for v, uuid in zip(outcome, outcome_uuid):
variables[uuid] = v
outcomes[uuid] = v
elif isinstance(f, Distribution):
known = [v in variables for _, v in f.outputs]
if all(known):
continue
elif any(known):
raise InferenceError("Part of the outputs of the distribution " + f.__class__.__name__ +
" has been observed!")
outcome_uuid = [v.uuid for _, v in f.outputs]
outcome = f.draw_samples(
F=F, num_samples=self.num_samples, variables=variables,
always_return_tuple=True)
for v, uuid in zip(outcome, outcome_uuid):
variables[uuid] = v
outcomes[uuid] = v
elif isinstance(f, Module):
outcome_uuid = [v.uuid for _, v in f.outputs]
outcome = f.predict(
F=F, variables=variables, targets=outcome_uuid,
num_samples=self.num_samples)
for v, uuid in zip(outcome, outcome_uuid):
variables[uuid] = v
outcomes[uuid] = v
if self.target_variables:
return tuple(outcomes[uuid] for uuid in self.target_variables)
else:
return outcomes
| 45.116279 | 119 | 0.605155 |
4eb47cb9f92cb6694a2511c91823ba69aff6c931 | 4,911 | py | Python | tests/SMB_RPC/test_mimilib.py | kamnsv/impacket | 83a581e4ba0cb3b7ba5dfa3018b87f9bf1a2cb58 | [
"Apache-1.1"
] | 6,612 | 2018-10-10T22:45:11.000Z | 2022-03-31T18:13:01.000Z | tests/SMB_RPC/test_mimilib.py | kamnsv/impacket | 83a581e4ba0cb3b7ba5dfa3018b87f9bf1a2cb58 | [
"Apache-1.1"
] | 703 | 2018-10-11T11:38:30.000Z | 2022-03-31T14:59:22.000Z | tests/SMB_RPC/test_mimilib.py | kamnsv/impacket | 83a581e4ba0cb3b7ba5dfa3018b87f9bf1a2cb58 | [
"Apache-1.1"
] | 2,172 | 2018-10-11T10:51:26.000Z | 2022-03-31T04:45:49.000Z | # Impacket - Collection of Python classes for working with network protocols.
#
# SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Tested so far:
#
# Not yet:
#
# Shouldn't dump errors against a win7
#
import unittest
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
from impacket.dcerpc.v5 import transport
from impacket.dcerpc.v5 import mimilib, epm
from impacket.winregistry import hexdump
class RRPTests(unittest.TestCase):
def connect(self):
rpctransport = transport.DCERPCTransportFactory(self.stringBinding)
rpctransport.set_connect_timeout(30000)
#if hasattr(rpctransport, 'set_credentials'):
# This method exists only for selected protocol sequences.
# rpctransport.set_credentials(self.username,self.password, self.domain, lmhash, nthash)
dce = rpctransport.get_dce_rpc()
#dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
dce.connect()
dce.bind(mimilib.MSRPC_UUID_MIMIKATZ, transfer_syntax = self.ts)
dh = mimilib.MimiDiffeH()
blob = mimilib.PUBLICKEYBLOB()
blob['y'] = dh.genPublicKey()[::-1]
request = mimilib.MimiBind()
request['clientPublicKey']['sessionType'] = mimilib.CALG_RC4
request['clientPublicKey']['cbPublicKey'] = 144
request['clientPublicKey']['pbPublicKey'] = blob.getData()
resp = dce.request(request)
blob = mimilib.PUBLICKEYBLOB(b''.join(resp['serverPublicKey']['pbPublicKey']))
key = dh.getSharedSecret(blob['y'][::-1])
pHandle = resp['phMimi']
return dce, rpctransport, pHandle, key[-16:]
def test_MimiBind(self):
dce, rpctransport, pHandle, key = self.connect()
dh = mimilib.MimiDiffeH()
print('Our Public')
print('='*80)
hexdump(dh.genPublicKey())
blob = mimilib.PUBLICKEYBLOB()
blob['y'] = dh.genPublicKey()[::-1]
request = mimilib.MimiBind()
request['clientPublicKey']['sessionType'] = mimilib.CALG_RC4
request['clientPublicKey']['cbPublicKey'] = 144
request['clientPublicKey']['pbPublicKey'] = blob.getData()
resp = dce.request(request)
blob = mimilib.PUBLICKEYBLOB(b''.join(resp['serverPublicKey']['pbPublicKey']))
print('='*80)
print('Server Public')
hexdump(blob['y'])
print('='*80)
print('Shared')
hexdump(dh.getSharedSecret(blob['y'][::-1]))
resp.dump()
def test_MimiCommand(self):
dce, rpctransport, pHandle, key = self.connect()
from Cryptodome.Cipher import ARC4
cipher = ARC4.new(key[::-1])
command = cipher.encrypt('token::whoami\x00'.encode('utf-16le'))
#command = cipher.encrypt('sekurlsa::logonPasswords\x00'.encode('utf-16le'))
#command = cipher.encrypt('process::imports\x00'.encode('utf-16le'))
request = mimilib.MimiCommand()
request['phMimi'] = pHandle
request['szEncCommand'] = len(command)
request['encCommand'] = list(command)
resp = dce.request(request)
cipherText = b''.join(resp['encResult'])
cipher = ARC4.new(key[::-1])
plain = cipher.decrypt(cipherText)
print('='*80)
print(plain)
#resp.dump()
def test_MimiUnBind(self):
dce, rpctransport, pHandle, key = self.connect()
request = mimilib.MimiUnbind()
request['phMimi'] = pHandle
hexdump(request.getData())
resp = dce.request(request)
resp.dump()
class TCPTransport(RRPTests):
def setUp(self):
RRPTests.setUp(self)
configFile = ConfigParser.ConfigParser()
configFile.read('dcetests.cfg')
self.username = configFile.get('TCPTransport', 'username')
self.domain = configFile.get('TCPTransport', 'domain')
self.serverName = configFile.get('TCPTransport', 'servername')
self.password = configFile.get('TCPTransport', 'password')
self.machine = configFile.get('TCPTransport', 'machine')
self.hashes = configFile.get('TCPTransport', 'hashes')
self.stringBinding = epm.hept_map(self.machine, mimilib.MSRPC_UUID_MIMIKATZ, protocol = 'ncacn_ip_tcp')
self.ts = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')
# Process command-line arguments.
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
testcase = sys.argv[1]
suite = unittest.TestLoader().loadTestsFromTestCase(globals()[testcase])
else:
suite = unittest.TestLoader().loadTestsFromTestCase(TCPTransport)
#suite.addTests(unittest.TestLoader().loadTestsFromTestCase(SMBTransport64))
unittest.main(defaultTest='suite')
| 38.669291 | 111 | 0.653431 |
6c526ed491c8018ce9a5da553a94bca1d61a8201 | 3,071 | py | Python | test/integration/test_replicas.py | ssavrim/curator | 3ddfbb95ea7a164bb3f8c773b0392481f067da7c | [
"Apache-2.0"
] | 2,449 | 2015-03-11T05:04:13.000Z | 2022-03-30T11:24:31.000Z | test/integration/test_replicas.py | ssavrim/curator | 3ddfbb95ea7a164bb3f8c773b0392481f067da7c | [
"Apache-2.0"
] | 960 | 2015-03-10T20:58:11.000Z | 2022-03-24T15:26:40.000Z | test/integration/test_replicas.py | ssavrim/curator | 3ddfbb95ea7a164bb3f8c773b0392481f067da7c | [
"Apache-2.0"
] | 702 | 2015-03-11T09:35:39.000Z | 2022-03-28T06:22:59.000Z | import elasticsearch
import curator
import os
import json
import string, random, tempfile
import click
from click import testing as clicktest
from mock import patch, Mock
from . import CuratorTestCase
from . import testvars as testvars
import logging
logger = logging.getLogger(__name__)
host, port = os.environ.get('TEST_ES_SERVER', 'localhost:9200').split(':')
port = int(port) if port else 9200
class TestActionFileReplicas(CuratorTestCase):
def test_increase_count(self):
count = 2
idx = 'my_index'
self.write_config(
self.args['configfile'], testvars.client_config.format(host, port))
self.write_config(self.args['actionfile'],
testvars.replicas_test.format(count))
self.create_index(idx)
test = clicktest.CliRunner()
_ = test.invoke(
curator.cli,
[
'--config', self.args['configfile'],
self.args['actionfile']
],
)
self.assertEqual(
count,
int(self.client.indices.get_settings(
index=idx)[idx]['settings']['index']['number_of_replicas'])
)
def test_no_count(self):
self.create_index('foo')
self.write_config(
self.args['configfile'], testvars.client_config.format(host, port))
self.write_config(self.args['actionfile'],
testvars.replicas_test.format(' '))
test = clicktest.CliRunner()
_ = test.invoke(
curator.cli,
[
'--config', self.args['configfile'],
self.args['actionfile']
],
)
self.assertEqual(1, _.exit_code)
def test_extra_option(self):
self.create_index('foo')
self.write_config(
self.args['configfile'], testvars.client_config.format(host, port))
self.write_config(self.args['actionfile'],
testvars.bad_option_proto_test.format('replicas'))
test = clicktest.CliRunner()
_ = test.invoke(
curator.cli,
[
'--config', self.args['configfile'],
self.args['actionfile']
],
)
self.assertEqual(1, _.exit_code)
class TestCLIReplicas(CuratorTestCase):
def test_increase_count(self):
count = 2
idx = 'my_index'
self.create_index(idx)
args = self.get_runner_args()
args += [
'--config', self.args['configfile'],
'replicas',
'--count', str(count),
'--filter_list', '{"filtertype":"pattern","kind":"prefix","value":"my"}',
]
self.assertEqual(0, self.run_subprocess(args, logname='TestCLIOpenClosed.test_open_closed'))
self.assertEqual(
count,
int(self.client.indices.get_settings(index=idx)[idx]['settings']['index']['number_of_replicas'])
) | 34.897727 | 108 | 0.553566 |
4e1b06a2f38826287ed4340b53ea71fb9707d9af | 5,083 | py | Python | main.py | njfanxun/san | 120b76ade4a12ce5bde8821bf79ab1464673ce91 | [
"MIT"
] | null | null | null | main.py | njfanxun/san | 120b76ade4a12ce5bde8821bf79ab1464673ce91 | [
"MIT"
] | null | null | null | main.py | njfanxun/san | 120b76ade4a12ce5bde8821bf79ab1464673ce91 | [
"MIT"
] | null | null | null | import time
import cv2
import glob
import numpy
from PIL import Image
import os
import torch
from animegan import AnimeGANer
from torchvision.transforms.functional import to_tensor, to_pil_image
from basicsr.archs.rrdbnet_arch import RRDBNet
from realesrgan import RealESRGANer
from gfpgan import GFPGANer
import ssl
from basicsr.utils import imwrite
import options
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
ssl._create_default_https_context = ssl._create_unverified_context
torch.backends.cudnn.enabled = False
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
opt = options.Options()
def get_time(f):
def inner(*arg, **kwarg):
s_time = time.time()
res = f(*arg, **kwarg)
e_time = time.time()
print('耗时:{}秒'.format(e_time - s_time))
return res
return inner
class FileWatchHandler(PatternMatchingEventHandler):
def __init__(self, patterns=None, ignore_patterns=None, ignore_directories=False, case_sensitive=False):
super().__init__(patterns, ignore_patterns, ignore_directories, case_sensitive)
self.restorer = None
self.animeGen = None
self.restorer_image = 'gfp_'
self.anime_image = 'anime_'
def prepareGANs(self, ):
# background upsampler
net = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)
bg_upsampler = RealESRGANer(scale=opt.upscale, model_path=opt.realesr_model_path,
model=net, tile=opt.bg_tile, tile_pad=0, pre_pad=0, half=False)
self.restorer = GFPGANer(model_path=opt.gfp_model_path, upscale=opt.upscale, arch=opt.arch,
channel_multiplier=opt.channel, bg_upsampler=bg_upsampler)
self.animeGen = AnimeGANer(opt.anime_model_path, opt.face_model_path, upscale=opt.upscale)
print('完成对抗网络模型加载...')
def restorer_img_path(self, img_name: str):
basename, ext = os.path.splitext(img_name)
if opt.ext == 'auto':
extension = ext[1:]
else:
extension = opt.ext
return os.path.join(opt.output_dir, f'{self.restorer_image}{basename}.{extension}'), extension
def anime_img_path(self, img_name: str):
basename, ext = os.path.splitext(img_name)
if opt.ext == 'auto':
extension = ext[1:]
else:
extension = opt.ext
return os.path.join(opt.output_dir, f'{self.anime_image}{basename}.{extension}'), extension
@get_time
def gfp_process(self, img_path: str) -> (bool, str):
img_name = os.path.basename(img_path)
input_img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
__, __, restored_img = self.restorer.enhance(input_img, has_aligned=opt.aligned,
only_center_face=opt.only_center_face, paste_back=opt.paste_back)
if restored_img is not None:
restored_img_path, _ = self.restorer_img_path(img_name)
imwrite(restored_img, restored_img_path)
print(f'完成图像增强:{img_name}')
return True, restored_img_path
else:
print(f'图像增强处理失败:{img_path}')
return False, None
@get_time
def anime_process(self, img_path: str):
img_name = os.path.basename(img_path)
image = Image.open(img_path)
full_img = self.animeGen.enhance(image)
if full_img is not None:
save_full_path, ext = self.anime_img_path(img_name)
full_img.save(save_full_path, ext)
print(f'完成漫画风格化{img_name}')
def on_created(self, event):
print('===============================================================================')
print(f'开始处理图像:{event.src_path}')
success, img_path = self.gfp_process(event.src_path)
if success:
self.anime_process(img_path)
print('===============================================================================')
def on_deleted(self, event):
img_name = os.path.basename(event.src_path)
restorer_img_path, _ = self.restorer_img_path(img_name=img_name)
img_name = os.path.basename(restorer_img_path)
anime_full_img_path, _ = self.anime_img_path(img_name=img_name)
if os.path.exists(restorer_img_path):
os.remove(restorer_img_path)
if os.path.exists(anime_full_img_path):
os.remove(anime_full_img_path)
if __name__ == '__main__':
os.makedirs(opt.output_dir, exist_ok=True)
event_handler = FileWatchHandler(patterns=['*.jpg', '*.png'], ignore_patterns=None,
ignore_directories=True, case_sensitive=True)
event_handler.prepareGANs()
observer = Observer()
observer.schedule(event_handler, opt.input_dir, recursive=False)
observer.start()
print("开始监视文件夹:%s" % opt.input_dir)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
| 36.833333 | 118 | 0.641747 |
9e7b6692496d67549336e79d96f735c6f81273ca | 12,830 | py | Python | rvlyzer/rep/base.py | nessdoor/RVlyzer | 239beb63a4db1653261bc1cc59227ee2ddb77d1a | [
"MIT"
] | null | null | null | rvlyzer/rep/base.py | nessdoor/RVlyzer | 239beb63a4db1653261bc1cc59227ee2ddb77d1a | [
"MIT"
] | null | null | null | rvlyzer/rep/base.py | nessdoor/RVlyzer | 239beb63a4db1653261bc1cc59227ee2ddb77d1a | [
"MIT"
] | null | null | null | from enum import Enum
from typing import NamedTuple, Union, Iterator, Sequence, Optional, Mapping, Tuple
from BitVector import BitVector
from rep.instr_pretty_print import familystr
class Register(Enum):
"""An enumeration of the 32 unprivileged RISC-V integer registers."""
ZERO = 0
RA = 1
SP = 2
GP = 3
TP = 4
T0 = 5
T1 = 6
T2 = 7
S0 = 8
S1 = 9
A0 = 10
A1 = 11
A2 = 12
A3 = 13
A4 = 14
A5 = 15
A6 = 16
A7 = 17
S2 = 18
S3 = 19
S4 = 20
S5 = 21
S6 = 22
S7 = 23
S8 = 24
S9 = 25
S10 = 26
S11 = 27
T3 = 28
T4 = 29
T5 = 30
T6 = 31
imm_sizes: Mapping[str, int] = {
"i": 12,
"s": 12,
"b": 12,
"bz": 12,
"u": 20,
"j": 20,
"li": 32
}
"""Dictionary of immediate formats with associated immediate field size."""
class Statement:
"""An assembler source statement."""
labels: Sequence[str]
def __init__(self, labels: Optional[Sequence[str]] = None):
"""
Instantiates a new assembler source statement.
:param labels: an optional set of labels to mark the new statement with
"""
if labels is None:
self.labels = []
else:
self.labels = list(labels)
def __str__(self):
return "".join(lab + ":\n" for lab in self.labels)
class Instruction(Statement):
"""A parsed assembly instruction."""
class ImmediateConstant:
"""
An immediate constant.
This class represents some sort of constant used as an immediate value by an instruction.
Such constant can be a literal value or a symbolic one.
Immediate formats can differ in size, so a size must be specified at creation time for faithful representation
and correct manipulation of the binary value.
:var symbol: the symbolic identifier of the constant, if any
:var value: the binary representation of the value, if assigned
:var int_val: the integer representation of the value, if assigned
:var size: the size in bits of the containing immediate field
"""
_symbol: Optional[str]
_value: Optional[BitVector]
_size: int
def __init__(self, size, symbol: str = None, value: int = None):
"""
Instantiate an immediate constant of the specified size and value, identified by a symbol.
:param size: the size in bits of the constant
:param symbol: the symbol identifying the constant, if any
:param value: the integer value of the constant, if any
:raise ValueError: when both symbol and value are left unspecified
"""
if symbol is None and value is None:
raise ValueError("Constant must be symbolic or have a value")
self._size = size
self._symbol = symbol
if value is not None:
# Prepare the mask for cutting the supplied value's bit representation to the specified size
mask = 0
for f in range(0, size):
mask += 2 ** f
value = value & mask
self._value = BitVector(intVal=value, size=size)
# Sizes must be coherent
assert self._size == len(self._value)
else:
self._value = None
@property
def symbol(self) -> str:
return self._symbol
@property
def value(self) -> BitVector:
return self._value.deep_copy()
@property
def int_val(self) -> int:
# Return the constant's integer representation, preserving its sign through an overly complicated procedure
return -((~self._value).int_val() + 1) if self._value[0] == 1 else self._value.int_val()
@property
def size(self):
return self._size
def __repr__(self):
return "Instruction.ImmediateConstant(size=" + repr(self._size) + ", symbol=" + repr(self._symbol) + \
", value=" + repr(None if self._value is None else self.int_val) + ")"
def __str__(self):
return str(self.int_val) if self._symbol is None else self.symbol
opcode: str
family: str
r1: Optional[Register]
r2: Optional[Register]
r3: Optional[Register]
immediate: Optional[ImmediateConstant]
def __init__(self, opcode: str, family: str, labels: Sequence[str] = None, r1: Union[str, Register] = None,
r2: Union[str, Register] = None, r3: Union[str, Register] = None,
immediate: Union[str, int, ImmediateConstant] = None):
"""
Instantiates a new instruction statement.
:param opcode: the opcode of the new instruction
:param family: the instruction's format
:param labels: an optional list of labels to mark the instruction with
:param r1: the first register parameter, if any
:param r2: the second register parameter, if any
:param r3: the third register parameter, if any
:param immediate: the immediate constant passed to the function, if any
"""
# Clean register arguments from the 'unused' keyword and raise an exception if a 'reg_err' is found
if r1 == "reg_err" or r2 == "reg_err" or r3 == "reg_err":
raise ValueError("Received the output of a failed parsing pass")
r1 = r1 if r1 != "unused" else None
r2 = r2 if r2 != "unused" else None
r3 = r3 if r3 != "unused" else None
super().__init__(labels)
self.opcode = opcode
self.family = family
self.r1 = Register[r1.upper()] if type(r1) is str else r1
self.r2 = Register[r2.upper()] if type(r2) is str else r2
self.r3 = Register[r3.upper()] if type(r3) is str else r3
if family in imm_sizes:
if isinstance(immediate, int):
# Constant as literal value
self.immediate = Instruction.ImmediateConstant(value=immediate,
size=imm_sizes[family])
elif isinstance(immediate, str):
# Constant as symbolic value
self.immediate = Instruction.ImmediateConstant(symbol=immediate,
size=imm_sizes[family])
else:
# Maybe an ImmediateConstant itself
self.immediate = immediate
else:
self.immediate = None
def __repr__(self):
return "Instruction(" + repr(self.opcode) + ", " + repr(self.family) + ", " + repr(self.labels) + ", " + \
repr(self.r1) + ", " + repr(self.r2) + ", " + repr(self.r3) + ", " + repr(self.immediate) + ")"
def __str__(self):
return super().__str__() + familystr[self.family](self)
class Directive(Statement):
"""A parsed assembler directive."""
name: str
args: Sequence[str]
def __init__(self, name: str, labels: Optional[Sequence[str]] = None, args: Optional[Sequence[str]] = None):
"""
Instantiates a new assembler directive statement.
:param name: the directive's name
:param labels: an optional list of labels to mark the directive with
:param args: an optional sequence of arguments for the directive
"""
super().__init__(labels)
self.name = name
if args is None:
self.args = []
else:
self.args = list(args)
def __repr__(self):
return "Directive(" + repr(self.name) + ", " + repr(self.labels) + ", " + repr(self.args) + ")"
def __str__(self):
# TODO investigate correctness of this string representation
return super().__str__() + "\t" + str(self.name) + "\t" + ", ".join(self.args) + "\n"
class ASMLine(NamedTuple):
"""An assembler source line."""
number: int
statement: Statement
def to_line_iterator(statement_iterator: Iterator[Statement], starting_line: int = 0) -> Iterator[ASMLine]:
"""
Wrap an iterator over statements to make it an iterator over assembly lines.
For every statement returned by the wrapped iterator, an ASMLine object is made out of it, incrementing the line
number starting from the provided one, or 0 by default.
:param statement_iterator: the iterator to be wrapped
:param starting_line: the line number from which line numbering will start
:return: an iterator over ASM lines
"""
current_line = starting_line
for statement in statement_iterator:
yield ASMLine(current_line, statement)
current_line += 1
# Mapping contributed by Alessandro Nazzari (https://github.com/zoythum)
# This is a classification of all the possible opcodes.
# Each opcode is paired with a tuple (<int>, <boolean>) where the int value represents the number of registers used
# by that specific opcode, the boolean value instead tells if we are dealing with a write function (True)
# or a read only one (False)
opcodes: Mapping[str, Tuple[int, bool]] = {
'lui': (1, True), 'auipc': (1, True), 'jal': (1, True), 'jalr': (2, True), 'lb': (2, True), 'lh': (2, True),
'lw': (2, True), 'lbu': (2, True), 'lhu': (2, True), 'addi': (2, True), 'slti': (2, True),
'sltiu': (2, True), 'xori': (2, True), 'ori': (2, True), 'andi': (2, True), 'slli': (2, True),
'srli': (2, True), 'srai': (2, True), 'lwu': (2, True), 'ld': (2, True), 'addiw': (2, True),
'slliw': (2, True), 'srliw': (2, True), 'sext.w': (2, True), 'mv': (2, True), 'sraiw': (2, True), 'lr.w': (2, True),
'lr.d': (2, True), 'add': (3, True), 'sub': (3, True), 'sll': (3, True), 'slt': (3, True),
'sltu': (3, True), 'xor': (3, True), 'srl': (3, True), 'sra': (3, True), 'or': (3, True), 'and': (3, True),
'addw': (3, True), 'subw': (3, True), 'sllw': (3, True), 'srlw': (3, True), 'sraw': (3, True), 'mul': (3, True),
'mulh': (3, True), 'mulhsu': (3, True), "mulhu": (3, True), 'div': (3, True), 'divu': (3, True), 'rem': (3, True),
'remu': (3, True), 'mulw': (3, True), 'divw': (3, True), 'divuw': (3, True), 'remw': (3, True),
'remuw': (3, True), 'sc.w': (3, True), 'amoswap.w': (3, True), 'amoadd.w': (3, True),
'amoxor.w': (3, True), 'amoor.w': (3, True), 'amoand.w': (3, True), 'amomin.w': (3, True), 'amomax.w': (3, True),
'amominu.w': (3, True), 'amomaxu.w': (3, True), 'sc.d': (3, True), 'amoswap.d': (3, True), 'amoadd.d': (3, True),
'amoxor.d': (3, True), 'amoor.d': (3, True), 'amoand.d': (3, True), 'amomin.d': (3, True),
'amomax.d': (3, True), 'amominu.d': (3, True), 'amomaxu.d': (3, True), 'jr': (1, False), 'j': (0, False),
'beq': (2, False), 'bne': (2, False), 'blt': (2, False), 'bge': (2, False), 'ble': (2, False), 'bltu': (2, False),
'bgeu': (2, False), 'sb': (2, False), 'sh': (2, False), 'sw': (2, False), 'sd': (2, False), 'li': (1, True),
'beqz': (1, False), 'bnez': (1, False), 'blez': (1, False),
'bgez': (1, False), 'bgtu': (2, False), 'bleu': (2, False), 'nop': (0, False), 'call': (0, False)
}
# Mapping contributed by Mattia Iamundo (https://github.com/MattiaIamundo)
# This is a mapping that, for each instruction, associate the relative family name
opcd_family: Mapping[str, str] = {
'add': 'r', 'addw': 'r', 'and': 'r', 'or': 'r', 'sext.w': 'sext', 'sll': 'r', 'sllw': 'r', 'sub': 'r', 'subw': 'r',
'xor': 'r', 'xori': 'i', 'jr': 'jr', 'j': 'j', 'beqz': 'bz', 'bnez': 'bz', 'nop': 'nop', 'blez': 'bz', 'beq': 'b',
'bge': 'b', 'bgeu': 'b', 'blt': 'b', 'ble': 'b', 'bltu': 'b', 'bne': 'b', 'bgt': 'b', 'bgez': 'bz', 'bltz': 'bz',
'bleu': 'b', 'addi': 'i', 'addiw': 'i', 'andi': 'i', 'auipc': 'u', 'jal': 'j', 'jalr': 'jr', 'ori': 'i',
'slli': 'i', 'slliw': 'i', 'slt': 'r', 'slti': 'i', 'sltiu': 'i', 'sltu': 'r', 'sra': 'r', 'sraw': 'r', 'srai': 'i',
'sraiw': 'i', 'srl': 'r', 'srlw': 'r', 'srli': 'i', 'srliw': 'i', 'mul': 'r', 'mulh': 'r', 'mulhsu': 'r',
'mulhu': 'r', 'div': 'r', 'divu': 'r', 'rem': 'r', 'remu': 'r', 'mulw': 'r', 'divw': 'r', 'divuw': 'r', 'remw': 'r',
'remuw': 'r', 'lr.w': 'al', 'lb': 'i', 'lbu': 's', 'lh': 's', 'lui': 'u', 'lw': 's', 'sb': 's', 'sh': 's',
'sw': 's', 'call': 'j', 'sd': 's', 'mv': '_2arg', 'ld': 's', 'li': 'li', 'bgtu': 'b', 'lwu': 's', 'lhu': 's',
'not': '_2arg', 'negw': '_2arg', 'sc.w': 'as', 'amoswap.w': 'as', 'amoadd.w': 'as', 'amoxor.w': 'as',
'amoor.w': 'as', 'amoand.w': 'as', 'amomin.w': 'as', 'amomax.w': 'as', 'amominu.w': 'as', 'amomaxu.w': 'as',
'lr.d': 'al', 'sc.d': 'as', 'amoswap.d': 'as', 'amoadd.d': 'as', 'amoxor.d': 'as', 'amoand.d': 'as',
'amomin.d': 'as', 'amomax.d': 'as', 'amominu.d': 'as', 'amomaxu.d': 'as', 'bgtz': 'bz', 'snez': 'snez'
}
| 40.345912 | 120 | 0.555729 |
667723e2e61b5779064ef15ed968a1b41c1589bc | 1,116 | py | Python | parlai/tasks/snli/build.py | zl930216/ParlAI | abf0ad6d1779af0f8ce0b5aed00d2bab71416684 | [
"MIT"
] | 9,228 | 2017-05-03T03:40:34.000Z | 2022-03-31T14:03:29.000Z | parlai/tasks/snli/build.py | zl930216/ParlAI | abf0ad6d1779af0f8ce0b5aed00d2bab71416684 | [
"MIT"
] | 2,660 | 2017-05-03T23:06:02.000Z | 2022-03-31T21:24:29.000Z | parlai/tasks/snli/build.py | zl930216/ParlAI | abf0ad6d1779af0f8ce0b5aed00d2bab71416684 | [
"MIT"
] | 2,058 | 2017-05-04T12:19:48.000Z | 2022-03-31T10:28:11.000Z | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import parlai.core.build_data as build_data
from parlai.core.build_data import DownloadableFile
RESOURCES = [
DownloadableFile(
'https://nlp.stanford.edu/projects/snli/snli_1.0.zip',
'snli_1.0.zip',
'afb3d70a5af5d8de0d9d81e2637e0fb8c22d1235c2749d83125ca43dab0dbd3e',
)
]
def build(opt):
dpath = os.path.join(opt['datapath'], 'SNLI')
version = '1.0'
if not build_data.built(dpath, version_string=version):
print('[building data: ' + dpath + ']')
if build_data.built(dpath):
# an older version exists, so remove these outdated files.
build_data.remove_dir(dpath)
build_data.make_dir(dpath)
# Download the data.
for downloadable_file in RESOURCES:
downloadable_file.download_file(dpath)
# mark the data as built
build_data.mark_done(dpath, version_string=version)
| 27.9 | 75 | 0.681004 |
90821a59c87967debb6eb604d4316780516b638d | 270 | py | Python | ecommerce/ordering/ordering/commands.py | NetstationPL/example_event_source_ecommerce | 67e673e91da4e24ff88d17e34e69a312da65b80d | [
"MIT"
] | null | null | null | ecommerce/ordering/ordering/commands.py | NetstationPL/example_event_source_ecommerce | 67e673e91da4e24ff88d17e34e69a312da65b80d | [
"MIT"
] | null | null | null | ecommerce/ordering/ordering/commands.py | NetstationPL/example_event_source_ecommerce | 67e673e91da4e24ff88d17e34e69a312da65b80d | [
"MIT"
] | null | null | null | from dataclasses import dataclass
from uuid import UUID
from infra.command_bus import Command
@dataclass
class AddItemToBasket(Command):
order_id: UUID
product_id: UUID
@dataclass
class RemoveItemFromBasket(Command):
order_id: UUID
product_id: UUID
| 15.882353 | 37 | 0.777778 |
b9d73f2878aefb0b8b5976f0f7cae5654c0ef806 | 13,421 | py | Python | auxiliary/table3.py | huiren-j/Replication-of-Decarolis-2014- | 162fc0f60b067c88370922f901fac7fa17d78cd3 | [
"MIT"
] | null | null | null | auxiliary/table3.py | huiren-j/Replication-of-Decarolis-2014- | 162fc0f60b067c88370922f901fac7fa17d78cd3 | [
"MIT"
] | null | null | null | auxiliary/table3.py | huiren-j/Replication-of-Decarolis-2014- | 162fc0f60b067c88370922f901fac7fa17d78cd3 | [
"MIT"
] | null | null | null | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from linearmodels import PanelOLS
import statsmodels.api as sm
import econtools as econ
import econtools.metrics as mt
import math
from statsmodels.stats.outliers_influence import variance_inflation_factor
from auxiliary.prepare import *
from auxiliary.table2 import *
from auxiliary.table3 import *
from auxiliary.table4 import *
from auxiliary.table5 import *
from auxiliary.table6 import *
from auxiliary.table7 import *
from auxiliary.extension import *
from auxiliary.table_formula import *
def calc_vif(X):
# Calculating VIF
vif = pd.DataFrame()
vif["variables"] = X.columns
vif["VIF"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]
return(vif)
def table3_col1(data):
df = data
df_reg_pr = df[(df['turin_pr_sample']==1)&(df['ctrl_exp_turin_pr_sample']==1)&(df['post_experience']>= 5) & (df['pre_experience']>=5) &(df['post_experience'].isnull() == False ) &
(df['pre_experience'].isnull()==False)&(df['missing']==0)]
outcome = ['discount', 'delay_ratio', 'overrun_ratio', 'days_to_award']
year_list = df['year'].unique()
#iteration
for o in outcome:
#days_to_award(4,6)
idx = df_reg_pr[df_reg_pr[o].isnull()==True].index
df_name = df_reg_pr.drop(idx)
#vif cal
#first, make a column list
reg_col = []
for j in year_list:
reg_col.append(j)
exog_var = ['fpsb_auction']
exog = exog_var + reg_col
#check multicollinearity
X = df_name.loc[:,exog]
vif = calc_vif(X)
#delete from col list
for i in range(len(vif)):
if np.isnan(vif.loc[i, 'VIF']) == True:
reg_col.remove(vif.loc[i, 'variables'])
exog = exog_var + reg_col
exog.remove(2000)
if o == 'discount':
fe_reg_discount = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'delay_ratio':
fe_reg_delay = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'overrun_ratio':
fe_reg_overrun = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
else :
fe_reg_award = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
fe_reg = (fe_reg_discount, fe_reg_delay, fe_reg_overrun, fe_reg_award )
return(fe_reg)
def table3_col2(data):
df= data
df_reg_pr = df[(df['turin_pr_sample']==1)&(df['ctrl_exp_turin_pr_sample']==1)&(df['post_experience']>= 5) & (df['pre_experience']>=5) &(df['post_experience'].isnull() == False ) &
(df['pre_experience'].isnull()==False)&(df['missing']==0)]
outcome = ['discount', 'delay_ratio', 'overrun_ratio', 'days_to_award']
year_list = df['year'].unique()
work_list = df['work_category'].unique()
for o in outcome:
#days_to_award(4,6)
idx = df_reg_pr[df_reg_pr[o].isnull()==True].index
df_name = df_reg_pr.drop(idx)
#vif cal
#first, make a column list
reg_col = []
for i in work_list:
reg_col.append(i)
for j in year_list:
reg_col.append(j)
exog_var = ['fpsb_auction','id_auth','reserve_price','municipality']
exog = exog_var + reg_col
#check multicollinearity
X = df_name.loc[:,exog]
vif = calc_vif(X)
#print(vif)
#delete from col list
for i in range(len(vif)):
if np.isnan(vif.loc[i, 'VIF']) == True:
reg_col.remove(vif.loc[i, 'variables'])
elif vif.loc[i,'VIF'] > 10:
for j in exog_var:
if str(vif.loc[i,'variables']) is j and vif.loc[i,'variables'] is not 'fpsb_auction' and vif.loc[i,'variables'] is not 'id_auth':
exog_var.remove(vif.loc[i,'variables'])
exog = exog_var + reg_col
exog.remove('id_auth')
exog.remove(2000)
exog.remove('OG01')
exog.remove('municipality')
if o == 'discount':
fe_reg_discount = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'delay_ratio':
fe_reg_delay = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'overrun_ratio':
fe_reg_overrun = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
else :
fe_reg_award = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
fe_reg = (fe_reg_discount, fe_reg_delay, fe_reg_overrun, fe_reg_award )
return(fe_reg)
def table3_col3(data):
df = data
df_reg_pr = df[(df['turin_pr_sample']==1)&(df['ctrl_pop_turin_pr_sample']==1)&(df['post_experience']>= 5) & (df['pre_experience']>=5) &(df['post_experience'].isnull() == False ) &
(df['pre_experience'].isnull()==False)&(df['missing']==0)]
outcome = ['discount', 'delay_ratio', 'overrun_ratio', 'days_to_award']
year_list = df['year'].unique()
for o in outcome:
#days_to_award(4,6)
idx = df_reg_pr[df_reg_pr[o].isnull()==True].index
df_name = df_reg_pr.drop(idx)
#vif cal
#first, make a column list
reg_col = []
for j in year_list:
reg_col.append(j)
exog_var = ['fpsb_auction']
exog = exog_var + reg_col
#check multicollinearity
X = df_name.loc[:,exog]
vif = calc_vif(X)
#delete from col list
for i in range(len(vif)):
if np.isnan(vif.loc[i, 'VIF']) == True:
reg_col.remove(vif.loc[i, 'variables'])
exog = exog_var + reg_col
exog.remove(2000)
if o == 'discount':
fe_reg_discount = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'delay_ratio':
fe_reg_delay = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'overrun_ratio':
fe_reg_overrun = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
else :
fe_reg_award = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
fe_reg = (fe_reg_discount, fe_reg_delay, fe_reg_overrun, fe_reg_award )
return(fe_reg)
def table3_col4(data):
df =data
df_reg_pr = df[(df['turin_pr_sample']==1)&(df['ctrl_pop_turin_pr_sample']==1)&(df['post_experience']>= 5) & (df['pre_experience']>=5) &(df['post_experience'].isnull() == False ) &
(df['pre_experience'].isnull()==False)&(df['missing']==0)]
outcome = ['discount', 'delay_ratio', 'overrun_ratio', 'days_to_award']
year_list = df['year'].unique()
work_list = df['work_category'].unique()
for o in outcome:
idx = df_reg_pr[df_reg_pr[o].isnull()==True].index
df_name = df_reg_pr.drop(idx)
#vif cal
#first, make a column list
reg_col = []
for i in work_list:
reg_col.append(i)
for j in year_list:
reg_col.append(j)
exog_var = ['fpsb_auction','id_auth','reserve_price','municipality']
exog = exog_var + reg_col
#check multicollinearity
X = df_name.loc[:,exog]
vif = calc_vif(X)
#delete from col list
for i in range(len(vif)):
if np.isnan(vif.loc[i, 'VIF']) == True:
reg_col.remove(vif.loc[i, 'variables'])
elif vif.loc[i,'VIF'] > 10:
for j in exog_var:
if str(vif.loc[i,'variables']) is j and vif.loc[i,'variables'] is not 'fpsb_auction' and vif.loc[i,'variables'] is not 'id_auth':
exog_var.remove(vif.loc[i,'variables'])
exog = exog_var + reg_col
exog.remove('id_auth')
exog.remove(2000)
exog.remove('OG01')
exog.remove('municipality')
if o == 'discount':
fe_reg_discount = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'delay_ratio':
fe_reg_delay = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'overrun_ratio':
fe_reg_overrun = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
else :
fe_reg_award = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
fe_reg = (fe_reg_discount, fe_reg_delay, fe_reg_overrun, fe_reg_award )
return(fe_reg)
def table3_col5(data):
df = data
df_reg_pr = df[(df['turin_pr_sample']==1)&(df['ctrl_pop_exp_turin_pr_sample']==1)&(df['post_experience']>= 5) & (df['pre_experience']>=5) &(df['post_experience'].isnull() == False ) &
(df['pre_experience'].isnull()==False)&(df['missing']==0)]
outcome = ['discount', 'delay_ratio', 'overrun_ratio', 'days_to_award']
year_list = df['year'].unique()
for o in outcome:
#days_to_award(4,6)
idx = df_reg_pr[df_reg_pr[o].isnull()==True].index
df_name = df_reg_pr.drop(idx)
#vif cal
#first, make a column list
reg_col = []
for j in year_list:
reg_col.append(j)
exog_var = ['fpsb_auction']
exog = exog_var + reg_col
#check multicollinearity
X = df_name.loc[:,exog]
vif = calc_vif(X)
#delete from col list
for i in range(len(vif)):
if np.isnan(vif.loc[i, 'VIF']) == True:
reg_col.remove(vif.loc[i, 'variables'])
exog = exog_var + reg_col
exog.remove(2000)
if o == 'discount':
fe_reg_discount = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'delay_ratio':
fe_reg_delay = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'overrun_ratio':
fe_reg_overrun = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
else :
fe_reg_award = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
fe_reg = (fe_reg_discount, fe_reg_delay, fe_reg_overrun, fe_reg_award )
return(fe_reg)
def table3_col6(data):
df = data
df_reg_pr = df[(df['turin_pr_sample']==1)&(df['ctrl_pop_exp_turin_pr_sample']==1)&(df['post_experience']>= 5) & (df['pre_experience']>=5) &(df['post_experience'].isnull() == False ) &
(df['pre_experience'].isnull()==False)&(df['missing']==0)]
outcome = ['discount', 'delay_ratio', 'overrun_ratio', 'days_to_award']
year_list = df['year'].unique()
work_list = df['work_category'].unique()
#iteration
for o in outcome:
#days_to_award(4,6)
idx = df_reg_pr[df_reg_pr[o].isnull()==True].index
df_name = df_reg_pr.drop(idx)
#vif cal
#first, make a column list
reg_col = []
for i in work_list:
reg_col.append(i)
for j in year_list:
reg_col.append(j)
exog_var = ['fpsb_auction','id_auth','reserve_price','municipality']
exog = exog_var + reg_col
#check multicollinearity
X = df_name.loc[:,exog]
vif = calc_vif(X)
#delete from col list
for i in range(len(vif)):
if np.isnan(vif.loc[i, 'VIF']) == True:
reg_col.remove(vif.loc[i, 'variables'])
elif vif.loc[i,'VIF'] > 10:
for j in exog_var:
if str(vif.loc[i,'variables']) is j and vif.loc[i,'variables'] is not 'fpsb_auction' and vif.loc[i,'variables'] is not 'id_auth':
exog_var.remove(vif.loc[i,'variables'])
exog = exog_var + reg_col
exog.remove('id_auth')
exog.remove(2000)
exog.remove('OG01')
exog.remove('municipality')
if o == 'discount':
fe_reg_discount = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'delay_ratio':
fe_reg_delay = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno')
elif o == 'overrun_ratio':
fe_reg_overrun = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
else :
fe_reg_award = mt.reg(df_reg_pr, o, exog, fe_name = 'authority_code', cluster = 'auth_anno',check_colinear = True)
fe_reg = (fe_reg_discount, fe_reg_delay, fe_reg_overrun, fe_reg_award )
return(fe_reg)
def table3_list(data):
table3_list= []
table3_list.append(table3_col1(data))
table3_list.append(table3_col2(data))
table3_list.append(table3_col3(data))
table3_list.append(table3_col4(data))
table3_list.append(table3_col5(data))
table3_list.append(table3_col6(data))
return(table3_list)
| 37.488827 | 188 | 0.596081 |
e6ed961e5ac2ed3f40b63a905807d40ed663818a | 1,035 | py | Python | py_sys_test/ping_test/ping_http_test.py | interhui/py-sys | 5d0f8cf5421a5766ed66d78a5364a017cb38aa3a | [
"Apache-2.0"
] | 1 | 2016-03-23T10:25:57.000Z | 2016-03-23T10:25:57.000Z | py_sys_test/ping_test/ping_http_test.py | vicky-tan/py-sys | 5d0f8cf5421a5766ed66d78a5364a017cb38aa3a | [
"Apache-2.0"
] | null | null | null | py_sys_test/ping_test/ping_http_test.py | vicky-tan/py-sys | 5d0f8cf5421a5766ed66d78a5364a017cb38aa3a | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
import unittest
from py_sys.ping import ping_http
class Test(unittest.TestCase):
def test_ping_http(self):
p = ping_http.PingHTTP()
result = p.ping('http://www.baidu.com', 80, 1, 5)
for item in result:
self.assertEqual(item.get('result'), 'success')
def test_ping_https(self):
p = ping_http.PingHTTP()
result = p.ping('https://www.baidu.com', 443, 1, 5)
for item in result:
self.assertEqual(item.get('result'), 'success')
def test_ping_timeout(self):
p = ping_http.PingHTTP()
result = p.ping('www.baidu.com', 8080, 1, 5)
for item in result:
self.assertEqual(item.get('result'), 'timeout')
def test_ping_err(self):
p = ping_http.PingHTTP()
result = p.ping('nosuchhost', 80, 1, 5)
for item in result:
self.assertEqual(item.get('result'), 'timeout')
if __name__ == "__main__":
unittest.main() | 32.34375 | 62 | 0.562319 |
4a02be56e21466ad79d4febb5791cb1bacbd5c6b | 418 | py | Python | Python/7/HalvingSum/test_halving_sum.py | hwakabh/codewars | 7afce5a7424d35abc55c350301ac134f2d3edd3d | [
"MIT"
] | null | null | null | Python/7/HalvingSum/test_halving_sum.py | hwakabh/codewars | 7afce5a7424d35abc55c350301ac134f2d3edd3d | [
"MIT"
] | 6 | 2020-02-21T17:01:59.000Z | 2021-05-04T07:04:41.000Z | Python/7/HalvingSum/test_halving_sum.py | hwakabh/codewars | 7afce5a7424d35abc55c350301ac134f2d3edd3d | [
"MIT"
] | null | null | null | from unittest import TestCase
from unittest import main
from halving_sum import halving_sum
class TestHalvingSum(TestCase):
def test_halving_sum(self):
ptr = [
(25, 47),
(127, 247),
]
for inp, exp in ptr:
with self.subTest(inp=inp, exp=exp):
self.assertEqual(halving_sum(n=inp), exp)
if __name__ == "__main__":
main(verbosity=2)
| 20.9 | 57 | 0.595694 |
40c216a84ec5f7a617a6edb7abcd803ed6df3cd4 | 3,769 | py | Python | ovis/estimators/reinforce.py | vlievin/ovis | 71f05a5f5219b2df66a9cdbd5a5339e0e179597b | [
"MIT"
] | 10 | 2020-08-06T22:25:11.000Z | 2022-03-07T13:10:15.000Z | ovis/estimators/reinforce.py | vlievin/ovis | 71f05a5f5219b2df66a9cdbd5a5339e0e179597b | [
"MIT"
] | 2 | 2021-06-08T22:15:24.000Z | 2022-03-12T00:45:59.000Z | ovis/estimators/reinforce.py | vlievin/ovis | 71f05a5f5219b2df66a9cdbd5a5339e0e179597b | [
"MIT"
] | null | null | null | from .vi import *
class Reinforce(VariationalInference):
"""
The "Reinforce" or "score-function" gradient estimator. The gradients of the generative model are given by
* d L_K/ d\theta = \E_q(z_1, ... z_K | x) [ d/d\theta \log Z ]
The gradients of the inference network are given by:
* d L_K/ d\phi = \E_q(z_1, ... z_K | x) [ \sum_k d_k h_k ]
Where
* d_k = \log Z - v_k
* v_k = w_k / \sum_l w_l
* h_k = d/d\phi \log q(z_k | x)
Using a control variate c_k, the gradient estimator g of the parameters of the inference network is:
* g = \sum_k (d_k - c_k) h_k
The control variate is a neural baseline `c(x)` if a model `baseline` is provided, otherwise `c(x)=0`
"""
def __init__(self, baseline: Optional[nn.Module] = None, **kwargs: Any):
assert not kwargs.get('sequential_computation',
False), f"{type(self).__name__} is not Compatible with Sequential Computation"
super().__init__(**kwargs, reparam=False, no_phi_grads=True)
self.baseline = baseline
control_loss_weight = 1. if baseline is not None else 0.
self.register_buffer('control_loss_weight', torch.tensor(control_loss_weight))
def compute_control_variate(self, x: Tensor, **data: Dict[str, Any]) -> Union[float, Tensor]:
"""
Compute the baseline (a.k.a control variate). Use the Neural Baseline model if available else the baseline is zero.
:param x: observation
:param data: additional data
:return: control variate of shape [bs, mc, iw]
"""
if self.baseline is None:
return 0.
return self.baseline(x).view((x.size(0), 1, 1))
def compute_control_variate_loss(self, d_k, c_k):
"""MSE between the score function and the control variate"""
return (c_k - d_k.detach()).pow(2).mean(dim=(1, 2))
def forward(self,
model: nn.Module,
x: Tensor,
backward: bool = False,
return_diagnostics: bool = True,
**kwargs: Any) -> Tuple[Tensor, Diagnostic, Dict]:
# update the `config` object with the `kwargs`
config = self.get_runtime_config(**kwargs)
# forward pass and eval of the log probs
log_probs, output = self.evaluate_model(model, x, **config)
iw_data = self.compute_log_weights_and_iw_bound(**log_probs, **config)
# unpack data
L_k, log_wk = [iw_data[k] for k in ('L_k', 'log_wk')]
log_qz = log_probs['log_qz']
# compute the score function d_k = \log Z - v_k
v_k = log_wk.softmax(2)
d_k = L_k[:, :, None] - v_k
# compute the control variate c_k
c_k = self.compute_control_variate(x, d_k=d_k, v_k=v_k, **log_probs, **iw_data, **config)
# compute the loss for the inference network (sum over `iw` and `log q(z|x) groups`, avg. over `mc`)
loss_phi = - ((d_k - c_k).detach() * log_qz.sum(3)).sum(2).mean(1)
# compute the loss for the generative model
loss_theta = - L_k.mean(1)
# compute control variate and MSE
control_variate_loss = self.compute_control_variate_loss(d_k, c_k)
# final loss
loss = loss_theta + loss_phi + self.control_loss_weight * control_variate_loss
loss = loss.mean()
# prepare diagnostics
diagnostics = Diagnostic()
if return_diagnostics:
diagnostics = self.base_loss_diagnostics(**iw_data, **log_probs)
diagnostics.update(self.additional_diagnostics(**output))
diagnostics.update({'reinforce': {'mse': control_variate_loss}})
if backward:
loss.backward()
return loss, diagnostics, output
| 38.459184 | 123 | 0.613691 |
048261aaee48869e292aeef875d8422f3fbbac7f | 18,719 | py | Python | venv/lib/python2.7/site-packages/scipy/interpolate/tests/test_fitpack2.py | bopopescu/fbserver | e812dbc4dc0cbf2fda19473015a3d7e253718a19 | [
"Apache-2.0"
] | null | null | null | venv/lib/python2.7/site-packages/scipy/interpolate/tests/test_fitpack2.py | bopopescu/fbserver | e812dbc4dc0cbf2fda19473015a3d7e253718a19 | [
"Apache-2.0"
] | 5 | 2021-03-19T08:36:48.000Z | 2022-01-13T01:52:34.000Z | venv/lib/python2.7/site-packages/scipy/interpolate/tests/test_fitpack2.py | bopopescu/fbserver | e812dbc4dc0cbf2fda19473015a3d7e253718a19 | [
"Apache-2.0"
] | 1 | 2020-07-23T19:26:19.000Z | 2020-07-23T19:26:19.000Z | #!/usr/bin/env python
# Created by Pearu Peterson, June 2003
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from numpy.testing import (assert_equal, assert_almost_equal, assert_array_equal,
assert_array_almost_equal, assert_allclose, assert_raises, TestCase,
run_module_suite)
from numpy import array, diff, linspace, meshgrid, ones, pi, shape
from scipy.interpolate.fitpack import bisplrep, bisplev
from scipy.interpolate.fitpack2 import (UnivariateSpline,
LSQUnivariateSpline, InterpolatedUnivariateSpline,
LSQBivariateSpline, SmoothBivariateSpline, RectBivariateSpline,
LSQSphereBivariateSpline, SmoothSphereBivariateSpline,
RectSphereBivariateSpline)
class TestUnivariateSpline(TestCase):
def test_linear_constant(self):
x = [1,2,3]
y = [3,3,3]
lut = UnivariateSpline(x,y,k=1)
assert_array_almost_equal(lut.get_knots(),[1,3])
assert_array_almost_equal(lut.get_coeffs(),[3,3])
assert_almost_equal(lut.get_residual(),0.0)
assert_array_almost_equal(lut([1,1.5,2]),[3,3,3])
def test_preserve_shape(self):
x = [1, 2, 3]
y = [0, 2, 4]
lut = UnivariateSpline(x, y, k=1)
arg = 2
assert_equal(shape(arg), shape(lut(arg)))
assert_equal(shape(arg), shape(lut(arg, nu=1)))
arg = [1.5, 2, 2.5]
assert_equal(shape(arg), shape(lut(arg)))
assert_equal(shape(arg), shape(lut(arg, nu=1)))
def test_linear_1d(self):
x = [1,2,3]
y = [0,2,4]
lut = UnivariateSpline(x,y,k=1)
assert_array_almost_equal(lut.get_knots(),[1,3])
assert_array_almost_equal(lut.get_coeffs(),[0,4])
assert_almost_equal(lut.get_residual(),0.0)
assert_array_almost_equal(lut([1,1.5,2]),[0,1,2])
def test_subclassing(self):
# See #731
class ZeroSpline(UnivariateSpline):
def __call__(self, x):
return 0*array(x)
sp = ZeroSpline([1,2,3,4,5], [3,2,3,2,3], k=2)
assert_array_equal(sp([1.5, 2.5]), [0., 0.])
def test_empty_input(self):
# Test whether empty input returns an empty output. Ticket 1014
x = [1,3,5,7,9]
y = [0,4,9,12,21]
spl = UnivariateSpline(x, y, k=3)
assert_array_equal(spl([]), array([]))
def test_resize_regression(self):
"""Regression test for #1375."""
x = [-1., -0.65016502, -0.58856235, -0.26903553, -0.17370892,
-0.10011001, 0., 0.10011001, 0.17370892, 0.26903553, 0.58856235,
0.65016502, 1.]
y = [1.,0.62928599, 0.5797223, 0.39965815, 0.36322694, 0.3508061,
0.35214793, 0.3508061, 0.36322694, 0.39965815, 0.5797223,
0.62928599, 1.]
w = [1.00000000e+12, 6.88875973e+02, 4.89314737e+02, 4.26864807e+02,
6.07746770e+02, 4.51341444e+02, 3.17480210e+02, 4.51341444e+02,
6.07746770e+02, 4.26864807e+02, 4.89314737e+02, 6.88875973e+02,
1.00000000e+12]
spl = UnivariateSpline(x=x, y=y, w=w, s=None)
desired = array([0.35100374, 0.51715855, 0.87789547, 0.98719344])
assert_allclose(spl([0.1, 0.5, 0.9, 0.99]), desired, atol=5e-4)
def test_out_of_range_regression(self):
# Test different extrapolation modes. See ticket 3557
x = np.arange(5, dtype=np.float)
y = x**3
xp = linspace(-8, 13, 100)
xp_zeros = xp.copy()
xp_zeros[np.logical_or(xp_zeros < 0., xp_zeros > 4.)] = 0
xp_clip = xp.copy()
xp_clip[xp_clip < x[0]] = x[0]
xp_clip[xp_clip > x[-1]] = x[-1]
for cls in [UnivariateSpline, InterpolatedUnivariateSpline]:
spl = cls(x=x, y=y)
for ext in [0, 'extrapolate']:
assert_allclose(spl(xp, ext=ext), xp**3, atol=1e-16)
assert_allclose(cls(x, y, ext=ext)(xp), xp**3, atol=1e-16)
for ext in [1, 'zeros']:
assert_allclose(spl(xp, ext=ext), xp_zeros**3, atol=1e-16)
assert_allclose(cls(x, y, ext=ext)(xp), xp_zeros**3, atol=1e-16)
for ext in [2, 'raise']:
assert_raises(ValueError, spl, xp, **dict(ext=ext))
for ext in [3, 'const']:
assert_allclose(spl(xp, ext=ext), xp_clip**3, atol=1e-16)
assert_allclose(cls(x, y, ext=ext)(xp), xp_clip**3, atol=1e-16)
# also test LSQUnivariateSpline [which needs explicit knots]
t = spl.get_knots()[3:4] # interior knots w/ default k=3
spl = LSQUnivariateSpline(x, y, t)
assert_allclose(spl(xp, ext=0), xp**3, atol=1e-16)
assert_allclose(spl(xp, ext=1), xp_zeros**3, atol=1e-16)
assert_raises(ValueError, spl, xp, **dict(ext=2))
assert_allclose(spl(xp, ext=3), xp_clip**3, atol=1e-16)
# also make sure that unknown values for `ext` are caught early
for ext in [-1, 'unknown']:
spl = UnivariateSpline(x, y)
assert_raises(ValueError, spl, xp, **dict(ext=ext))
assert_raises(ValueError, UnivariateSpline,
**dict(x=x, y=y, ext=ext))
def test_lsq_fpchec(self):
xs = np.arange(100) * 1.
ys = np.arange(100) * 1.
knots = np.linspace(0, 99, 10)
bbox = (-1, 101)
assert_raises(ValueError, LSQUnivariateSpline, xs, ys, knots,
bbox=bbox)
def test_derivative_and_antiderivative(self):
# Thin wrappers to splder/splantider, so light smoke test only.
x = np.linspace(0, 1, 70)**3
y = np.cos(x)
spl = UnivariateSpline(x, y, s=0)
spl2 = spl.antiderivative(2).derivative(2)
assert_allclose(spl(0.3), spl2(0.3))
spl2 = spl.antiderivative(1)
assert_allclose(spl2(0.6) - spl2(0.2),
spl.integral(0.2, 0.6))
class TestLSQBivariateSpline(TestCase):
# NOTE: The systems in this test class are rank-deficient
def test_linear_constant(self):
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [3,3,3,3,3,3,3,3,3]
s = 0.1
tx = [1+s,3-s]
ty = [1+s,3-s]
lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1)
assert_almost_equal(lut(2,2), 3.)
def test_bilinearity(self):
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [0,7,8,3,4,7,1,3,4]
s = 0.1
tx = [1+s,3-s]
ty = [1+s,3-s]
with warnings.catch_warnings():
# This seems to fail (ier=1, see ticket 1642).
warnings.simplefilter('ignore', UserWarning)
lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1)
tx, ty = lut.get_knots()
for xa, xb in zip(tx[:-1], tx[1:]):
for ya, yb in zip(ty[:-1], ty[1:]):
for t in [0.1, 0.5, 0.9]:
for s in [0.3, 0.4, 0.7]:
xp = xa*(1-t) + xb*t
yp = ya*(1-s) + yb*s
zp = (+ lut(xa, ya)*(1-t)*(1-s)
+ lut(xb, ya)*t*(1-s)
+ lut(xa, yb)*(1-t)*s
+ lut(xb, yb)*t*s)
assert_almost_equal(lut(xp,yp), zp)
def test_integral(self):
x = [1,1,1,2,2,2,8,8,8]
y = [1,2,3,1,2,3,1,2,3]
z = array([0,7,8,3,4,7,1,3,4])
s = 0.1
tx = [1+s,3-s]
ty = [1+s,3-s]
lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1)
tx, ty = lut.get_knots()
tz = lut(tx, ty)
trpz = .25*(diff(tx)[:,None]*diff(ty)[None,:]
* (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum()
assert_almost_equal(lut.integral(tx[0], tx[-1], ty[0], ty[-1]), trpz)
def test_empty_input(self):
# Test whether empty inputs returns an empty output. Ticket 1014
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [3,3,3,3,3,3,3,3,3]
s = 0.1
tx = [1+s,3-s]
ty = [1+s,3-s]
lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1)
assert_array_equal(lut([], []), np.zeros((0,0)))
assert_array_equal(lut([], [], grid=False), np.zeros((0,)))
class TestSmoothBivariateSpline(TestCase):
def test_linear_constant(self):
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [3,3,3,3,3,3,3,3,3]
lut = SmoothBivariateSpline(x,y,z,kx=1,ky=1)
assert_array_almost_equal(lut.get_knots(),([1,1,3,3],[1,1,3,3]))
assert_array_almost_equal(lut.get_coeffs(),[3,3,3,3])
assert_almost_equal(lut.get_residual(),0.0)
assert_array_almost_equal(lut([1,1.5,2],[1,1.5]),[[3,3],[3,3],[3,3]])
def test_linear_1d(self):
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [0,0,0,2,2,2,4,4,4]
lut = SmoothBivariateSpline(x,y,z,kx=1,ky=1)
assert_array_almost_equal(lut.get_knots(),([1,1,3,3],[1,1,3,3]))
assert_array_almost_equal(lut.get_coeffs(),[0,0,4,4])
assert_almost_equal(lut.get_residual(),0.0)
assert_array_almost_equal(lut([1,1.5,2],[1,1.5]),[[0,0],[1,1],[2,2]])
def test_integral(self):
x = [1,1,1,2,2,2,4,4,4]
y = [1,2,3,1,2,3,1,2,3]
z = array([0,7,8,3,4,7,1,3,4])
with warnings.catch_warnings():
# This seems to fail (ier=1, see ticket 1642).
warnings.simplefilter('ignore', UserWarning)
lut = SmoothBivariateSpline(x, y, z, kx=1, ky=1, s=0)
tx = [1,2,4]
ty = [1,2,3]
tz = lut(tx, ty)
trpz = .25*(diff(tx)[:,None]*diff(ty)[None,:]
* (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum()
assert_almost_equal(lut.integral(tx[0], tx[-1], ty[0], ty[-1]), trpz)
lut2 = SmoothBivariateSpline(x, y, z, kx=2, ky=2, s=0)
assert_almost_equal(lut2.integral(tx[0], tx[-1], ty[0], ty[-1]), trpz,
decimal=0) # the quadratures give 23.75 and 23.85
tz = lut(tx[:-1], ty[:-1])
trpz = .25*(diff(tx[:-1])[:,None]*diff(ty[:-1])[None,:]
* (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum()
assert_almost_equal(lut.integral(tx[0], tx[-2], ty[0], ty[-2]), trpz)
def test_rerun_lwrk2_too_small(self):
# in this setting, lwrk2 is too small in the default run. Here we
# check for equality with the bisplrep/bisplev output because there,
# an automatic re-run of the spline representation is done if ier>10.
x = np.linspace(-2, 2, 80)
y = np.linspace(-2, 2, 80)
z = x + y
xi = np.linspace(-1, 1, 100)
yi = np.linspace(-2, 2, 100)
tck = bisplrep(x, y, z)
res1 = bisplev(xi, yi, tck)
interp_ = SmoothBivariateSpline(x, y, z)
res2 = interp_(xi, yi)
assert_almost_equal(res1, res2)
class TestLSQSphereBivariateSpline(TestCase):
def setUp(self):
# define the input data and coordinates
ntheta, nphi = 70, 90
theta = linspace(0.5/(ntheta - 1), 1 - 0.5/(ntheta - 1), ntheta) * pi
phi = linspace(0.5/(nphi - 1), 1 - 0.5/(nphi - 1), nphi) * 2. * pi
data = ones((theta.shape[0], phi.shape[0]))
# define knots and extract data values at the knots
knotst = theta[::5]
knotsp = phi[::5]
knotdata = data[::5, ::5]
# calculate spline coefficients
lats, lons = meshgrid(theta, phi)
lut_lsq = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
data.T.ravel(), knotst, knotsp)
self.lut_lsq = lut_lsq
self.data = knotdata
self.new_lons, self.new_lats = knotsp, knotst
def test_linear_constant(self):
assert_almost_equal(self.lut_lsq.get_residual(), 0.0)
assert_array_almost_equal(self.lut_lsq(self.new_lats, self.new_lons),
self.data)
def test_empty_input(self):
assert_array_almost_equal(self.lut_lsq([], []), np.zeros((0,0)))
assert_array_almost_equal(self.lut_lsq([], [], grid=False), np.zeros((0,)))
class TestSmoothSphereBivariateSpline(TestCase):
def setUp(self):
theta = array([.25*pi, .25*pi, .25*pi, .5*pi, .5*pi, .5*pi, .75*pi,
.75*pi, .75*pi])
phi = array([.5 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, .5 * pi, pi,
1.5 * pi])
r = array([3, 3, 3, 3, 3, 3, 3, 3, 3])
self.lut = SmoothSphereBivariateSpline(theta, phi, r, s=1E10)
def test_linear_constant(self):
assert_almost_equal(self.lut.get_residual(), 0.)
assert_array_almost_equal(self.lut([1, 1.5, 2],[1, 1.5]),
[[3, 3], [3, 3], [3, 3]])
def test_empty_input(self):
assert_array_almost_equal(self.lut([], []), np.zeros((0,0)))
assert_array_almost_equal(self.lut([], [], grid=False), np.zeros((0,)))
class TestRectBivariateSpline(TestCase):
def test_defaults(self):
x = array([1,2,3,4,5])
y = array([1,2,3,4,5])
z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
lut = RectBivariateSpline(x,y,z)
assert_array_almost_equal(lut(x,y),z)
def test_evaluate(self):
x = array([1,2,3,4,5])
y = array([1,2,3,4,5])
z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
lut = RectBivariateSpline(x,y,z)
xi = [1, 2.3, 5.3, 0.5, 3.3, 1.2, 3]
yi = [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]
zi = lut.ev(xi, yi)
zi2 = array([lut(xp, yp)[0,0] for xp, yp in zip(xi, yi)])
assert_almost_equal(zi, zi2)
def test_derivatives_grid(self):
x = array([1,2,3,4,5])
y = array([1,2,3,4,5])
z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
dx = array([[0,0,-20,0,0],[0,0,13,0,0],[0,0,4,0,0],
[0,0,-11,0,0],[0,0,4,0,0]])/6.
dy = array([[4,-1,0,1,-4],[4,-1,0,1,-4],[0,1.5,0,-1.5,0],
[2,.25,0,-.25,-2],[4,-1,0,1,-4]])
dxdy = array([[40,-25,0,25,-40],[-26,16.25,0,-16.25,26],
[-8,5,0,-5,8],[22,-13.75,0,13.75,-22],[-8,5,0,-5,8]])/6.
lut = RectBivariateSpline(x,y,z)
assert_array_almost_equal(lut(x,y,dx=1),dx)
assert_array_almost_equal(lut(x,y,dy=1),dy)
assert_array_almost_equal(lut(x,y,dx=1,dy=1),dxdy)
def test_derivatives(self):
x = array([1,2,3,4,5])
y = array([1,2,3,4,5])
z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
dx = array([0,0,2./3,0,0])
dy = array([4,-1,0,-.25,-4])
dxdy = array([160,65,0,55,32])/24.
lut = RectBivariateSpline(x,y,z)
assert_array_almost_equal(lut(x,y,dx=1,grid=False),dx)
assert_array_almost_equal(lut(x,y,dy=1,grid=False),dy)
assert_array_almost_equal(lut(x,y,dx=1,dy=1,grid=False),dxdy)
def test_broadcast(self):
x = array([1,2,3,4,5])
y = array([1,2,3,4,5])
z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
lut = RectBivariateSpline(x,y,z)
assert_allclose(lut(x, y), lut(x[:,None], y[None,:], grid=False))
class TestRectSphereBivariateSpline(TestCase):
def test_defaults(self):
y = linspace(0.01, 2*pi-0.01, 7)
x = linspace(0.01, pi-0.01, 7)
z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1],
[1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1],
[1,2,1,2,1,2,1]])
lut = RectSphereBivariateSpline(x,y,z)
assert_array_almost_equal(lut(x,y),z)
def test_evaluate(self):
y = linspace(0.01, 2*pi-0.01, 7)
x = linspace(0.01, pi-0.01, 7)
z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1],
[1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1],
[1,2,1,2,1,2,1]])
lut = RectSphereBivariateSpline(x,y,z)
yi = [0.2, 1, 2.3, 2.35, 3.0, 3.99, 5.25]
xi = [1.5, 0.4, 1.1, 0.45, 0.2345, 1., 0.0001]
zi = lut.ev(xi, yi)
zi2 = array([lut(xp, yp)[0,0] for xp, yp in zip(xi, yi)])
assert_almost_equal(zi, zi2)
def test_derivatives_grid(self):
y = linspace(0.01, 2*pi-0.01, 7)
x = linspace(0.01, pi-0.01, 7)
z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1],
[1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1],
[1,2,1,2,1,2,1]])
lut = RectSphereBivariateSpline(x,y,z)
y = linspace(0.02, 2*pi-0.02, 7)
x = linspace(0.02, pi-0.02, 7)
assert_allclose(lut(x, y, dtheta=1), _numdiff_2d(lut, x, y, dx=1),
rtol=1e-4, atol=1e-4)
assert_allclose(lut(x, y, dphi=1), _numdiff_2d(lut, x, y, dy=1),
rtol=1e-4, atol=1e-4)
assert_allclose(lut(x, y, dtheta=1, dphi=1), _numdiff_2d(lut, x, y, dx=1, dy=1, eps=1e-6),
rtol=1e-3, atol=1e-3)
def test_derivatives(self):
y = linspace(0.01, 2*pi-0.01, 7)
x = linspace(0.01, pi-0.01, 7)
z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1],
[1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1],
[1,2,1,2,1,2,1]])
lut = RectSphereBivariateSpline(x,y,z)
y = linspace(0.02, 2*pi-0.02, 7)
x = linspace(0.02, pi-0.02, 7)
assert_equal(lut(x, y, dtheta=1, grid=False).shape, x.shape)
assert_allclose(lut(x, y, dtheta=1, grid=False),
_numdiff_2d(lambda x,y: lut(x,y,grid=False), x, y, dx=1),
rtol=1e-4, atol=1e-4)
assert_allclose(lut(x, y, dphi=1, grid=False),
_numdiff_2d(lambda x,y: lut(x,y,grid=False), x, y, dy=1),
rtol=1e-4, atol=1e-4)
assert_allclose(lut(x, y, dtheta=1, dphi=1, grid=False),
_numdiff_2d(lambda x,y: lut(x,y,grid=False), x, y, dx=1, dy=1, eps=1e-6),
rtol=1e-3, atol=1e-3)
def _numdiff_2d(func, x, y, dx=0, dy=0, eps=1e-8):
if dx == 0 and dy == 0:
return func(x, y)
elif dx == 1 and dy == 0:
return (func(x + eps, y) - func(x - eps, y)) / (2*eps)
elif dx == 0 and dy == 1:
return (func(x, y + eps) - func(x, y - eps)) / (2*eps)
elif dx == 1 and dy == 1:
return (func(x + eps, y + eps) - func(x - eps, y + eps)
- func(x + eps, y - eps) + func(x - eps, y - eps)) / (2*eps)**2
else:
raise ValueError("invalid derivative order")
if __name__ == "__main__":
run_module_suite()
| 40.342672 | 98 | 0.527111 |
38bd31737fa51388073ef72f196c5c16f3636166 | 1,439 | py | Python | 2-Primitive_Triangle_Drawing/triangle_draw.py | ayengec/OpenGL_with_Python | 858748115aa02f8c7de0f79c2ef23990e00074b4 | [
"Unlicense"
] | null | null | null | 2-Primitive_Triangle_Drawing/triangle_draw.py | ayengec/OpenGL_with_Python | 858748115aa02f8c7de0f79c2ef23990e00074b4 | [
"Unlicense"
] | null | null | null | 2-Primitive_Triangle_Drawing/triangle_draw.py | ayengec/OpenGL_with_Python | 858748115aa02f8c7de0f79c2ef23990e00074b4 | [
"Unlicense"
] | null | null | null | # ayengec
# github OpenGL examples with python
# github.com/ayengec
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import math
def draw_circle():
glClear(GL_COLOR_BUFFER_BIT) # we declare which buffer we want to clear
glColor3f(1, 0.2, 0.3)
triangleAmount = 60 # 12
glBegin(GL_TRIANGLE_FAN)
for i in range(triangleAmount+1):
theta = 2.0 * math.pi * float(i) / float(triangleAmount) #get the current angle
xx = 0.5 * math.cos(theta) #calculate the x component
yy = 0.5 * math.sin(theta) #calculate the y component
glVertex2f(xx + 0.2, yy - 0.4) #output vertex
glEnd() # every drawing statements must be between glBegin and glEnd
glFlush() # force execution of GL commands in finite time
if __name__ == "__main__":
glutInit() # initialize GLUT library
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA) # initial display mode : with Bit mask to select a single buffered window and bit mask to select an RGBA mode window
glutCreateWindow("ayengec_lines") # creates "Square" named window
gluOrtho2D(-1.0, 1.0,-1.0, 1.0) # left, right, bottom, up =>float coordinate ranges in [-1:1]:
glClearColor(0.2, 0.2, 0.2, 1.0) # red, green, blue, alpha # To see different background color as GREY
glutDisplayFunc(draw_circle) # after created window, which shapes will be rendered
glutMainLoop() | 37.868421 | 165 | 0.680334 |
883c7f93557946d88be80959cfbfe709aed727d1 | 7,436 | py | Python | Cython/TestUtils.py | matthew-brett/cython | f69ac182f690fb167259657a1c85d59298c66db4 | [
"Apache-2.0"
] | null | null | null | Cython/TestUtils.py | matthew-brett/cython | f69ac182f690fb167259657a1c85d59298c66db4 | [
"Apache-2.0"
] | null | null | null | Cython/TestUtils.py | matthew-brett/cython | f69ac182f690fb167259657a1c85d59298c66db4 | [
"Apache-2.0"
] | null | null | null | import Cython.Compiler.Errors as Errors
from Cython.CodeWriter import CodeWriter
from Cython.Compiler.TreeFragment import TreeFragment, strip_common_indent
from Cython.Compiler.Visitor import TreeVisitor, VisitorTransform
from Cython.Compiler import TreePath
import unittest
import os, sys
import tempfile
class NodeTypeWriter(TreeVisitor):
def __init__(self):
super(NodeTypeWriter, self).__init__()
self._indents = 0
self.result = []
def visit_Node(self, node):
if len(self.access_path) == 0:
name = u"(root)"
else:
tip = self.access_path[-1]
if tip[2] is not None:
name = u"%s[%d]" % tip[1:3]
else:
name = tip[1]
self.result.append(u" " * self._indents +
u"%s: %s" % (name, node.__class__.__name__))
self._indents += 1
self.visitchildren(node)
self._indents -= 1
def treetypes(root):
"""Returns a string representing the tree by class names.
There's a leading and trailing whitespace so that it can be
compared by simple string comparison while still making test
cases look ok."""
w = NodeTypeWriter()
w.visit(root)
return u"\n".join([u""] + w.result + [u""])
class CythonTest(unittest.TestCase):
def setUp(self):
self.listing_file = Errors.listing_file
self.echo_file = Errors.echo_file
Errors.listing_file = Errors.echo_file = None
def tearDown(self):
Errors.listing_file = self.listing_file
Errors.echo_file = self.echo_file
def assertLines(self, expected, result):
"Checks that the given strings or lists of strings are equal line by line"
if not isinstance(expected, list): expected = expected.split(u"\n")
if not isinstance(result, list): result = result.split(u"\n")
for idx, (expected_line, result_line) in enumerate(zip(expected, result)):
self.assertEqual(expected_line, result_line, "Line %d:\nExp: %s\nGot: %s" % (idx, expected_line, result_line))
self.assertEqual(len(expected), len(result),
"Unmatched lines. Got:\n%s\nExpected:\n%s" % ("\n".join(expected), u"\n".join(result)))
def codeToLines(self, tree):
writer = CodeWriter()
writer.write(tree)
return writer.result.lines
def codeToString(self, tree):
return "\n".join(self.codeToLines(tree))
def assertCode(self, expected, result_tree):
result_lines = self.codeToLines(result_tree)
expected_lines = strip_common_indent(expected.split("\n"))
for idx, (line, expected_line) in enumerate(zip(result_lines, expected_lines)):
self.assertEqual(expected_line, line, "Line %d:\nGot: %s\nExp: %s" % (idx, line, expected_line))
self.assertEqual(len(result_lines), len(expected_lines),
"Unmatched lines. Got:\n%s\nExpected:\n%s" % ("\n".join(result_lines), expected))
def assertNodeExists(self, path, result_tree):
self.assertNotEqual(TreePath.find_first(result_tree, path), None,
"Path '%s' not found in result tree" % path)
def fragment(self, code, pxds={}, pipeline=[]):
"Simply create a tree fragment using the name of the test-case in parse errors."
name = self.id()
if name.startswith("__main__."): name = name[len("__main__."):]
name = name.replace(".", "_")
return TreeFragment(code, name, pxds, pipeline=pipeline)
def treetypes(self, root):
return treetypes(root)
def should_fail(self, func, exc_type=Exception):
"""Calls "func" and fails if it doesn't raise the right exception
(any exception by default). Also returns the exception in question.
"""
try:
func()
self.fail("Expected an exception of type %r" % exc_type)
except exc_type, e:
self.assert_(isinstance(e, exc_type))
return e
def should_not_fail(self, func):
"""Calls func and succeeds if and only if no exception is raised
(i.e. converts exception raising into a failed testcase). Returns
the return value of func."""
try:
return func()
except:
self.fail(str(sys.exc_info()[1]))
class TransformTest(CythonTest):
"""
Utility base class for transform unit tests. It is based around constructing
test trees (either explicitly or by parsing a Cython code string); running
the transform, serialize it using a customized Cython serializer (with
special markup for nodes that cannot be represented in Cython),
and do a string-comparison line-by-line of the result.
To create a test case:
- Call run_pipeline. The pipeline should at least contain the transform you
are testing; pyx should be either a string (passed to the parser to
create a post-parse tree) or a node representing input to pipeline.
The result will be a transformed result.
- Check that the tree is correct. If wanted, assertCode can be used, which
takes a code string as expected, and a ModuleNode in result_tree
(it serializes the ModuleNode to a string and compares line-by-line).
All code strings are first stripped for whitespace lines and then common
indentation.
Plans: One could have a pxd dictionary parameter to run_pipeline.
"""
def run_pipeline(self, pipeline, pyx, pxds={}):
tree = self.fragment(pyx, pxds).root
# Run pipeline
for T in pipeline:
tree = T(tree)
return tree
class TreeAssertVisitor(VisitorTransform):
# actually, a TreeVisitor would be enough, but this needs to run
# as part of the compiler pipeline
def visit_CompilerDirectivesNode(self, node):
directives = node.directives
if 'test_assert_path_exists' in directives:
for path in directives['test_assert_path_exists']:
if TreePath.find_first(node, path) is None:
Errors.error(
node.pos,
"Expected path '%s' not found in result tree" % path)
if 'test_fail_if_path_exists' in directives:
for path in directives['test_fail_if_path_exists']:
if TreePath.find_first(node, path) is not None:
Errors.error(
node.pos,
"Unexpected path '%s' found in result tree" % path)
self.visitchildren(node)
return node
visit_Node = VisitorTransform.recurse_to_children
def unpack_source_tree(tree_file, dir=None):
if dir is None:
dir = tempfile.mkdtemp()
header = []
cur_file = None
f = open(tree_file)
lines = f.readlines()
f.close()
f = None
for line in lines:
if line[:5] == '#####':
filename = line.strip().strip('#').strip().replace('/', os.path.sep)
path = os.path.join(dir, filename)
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
if cur_file is not None:
cur_file.close()
cur_file = open(path, 'w')
elif cur_file is not None:
cur_file.write(line)
else:
header.append(line)
if cur_file is not None:
cur_file.close()
return dir, ''.join(header)
| 38.329897 | 122 | 0.627353 |
06ca29493c2fbc30b27647829f93c61cec26f6e6 | 1,583 | py | Python | deepclustering/arch/classification/dummy.py | jizongFox/deep-clustering-toolbox | 0721cbbb278af027409ed4c115ccc743b6daed1b | [
"MIT"
] | 34 | 2019-08-05T03:48:36.000Z | 2022-03-29T03:04:51.000Z | deepclustering/arch/classification/dummy.py | jizongFox/deep-clustering-toolbox | 0721cbbb278af027409ed4c115ccc743b6daed1b | [
"MIT"
] | 10 | 2019-05-03T21:02:50.000Z | 2021-12-23T08:01:30.000Z | deepclustering/arch/classification/dummy.py | ETS-Research-Repositories/deep-clustering-toolbox | 0721cbbb278af027409ed4c115ccc743b6daed1b | [
"MIT"
] | 5 | 2019-09-29T07:56:03.000Z | 2021-04-22T12:08:50.000Z | from torch import nn
class PlaceholderNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(128, 256, 3)
self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
def forward(self, input):
return input
# return self.avg_pool(self.conv1(input))
class Dummy(nn.Module):
"""
This is a dummy network for debug
"""
def __init__(self, num_channel=3, output_k=10, num_sub_heads=2):
super().__init__()
self.feature = nn.Sequential(
nn.Conv2d(num_channel, 100, 3, padding=1),
nn.BatchNorm2d(100),
nn.ReLU(inplace=True),
nn.MaxPool2d(stride=2, kernel_size=3),
nn.Conv2d(100, 50, 3, 1, 1),
nn.BatchNorm2d(50),
nn.ReLU(inplace=True),
nn.MaxPool2d(stride=2, kernel_size=3),
nn.Conv2d(50, 10, 3, 1, 1),
nn.BatchNorm2d(10),
nn.AdaptiveAvgPool2d((1, 1)),
)
self.num_sub_heads = num_sub_heads
self.classifiers = nn.ModuleList()
for i in range(num_sub_heads):
self.classifiers.append(
nn.Sequential(nn.Linear(10, output_k), nn.Softmax(1))
)
def forward(self, input):
feature = self.feature(input)
feature = feature.view(feature.size(0), -1)
preds = []
for i in range(self.num_sub_heads):
_pred = self.classifiers[i](feature)
preds.append(_pred)
return preds
Dummy_Param = {"num_channel": 3, "output_k": 10, "num_sub_heads": 5}
| 28.781818 | 69 | 0.566014 |
489df86fb6a01783d4751e05f1ff03ff98c0b0c4 | 7,277 | py | Python | projecthosting_upload.py | DanEble/git-cl | 34a69ef307845983c5c25dc8ae47436604f27bd6 | [
"BSD-3-Clause"
] | null | null | null | projecthosting_upload.py | DanEble/git-cl | 34a69ef307845983c5c25dc8ae47436604f27bd6 | [
"BSD-3-Clause"
] | 2 | 2018-06-01T16:56:45.000Z | 2019-11-03T11:25:15.000Z | projecthosting_upload.py | DanEble/git-cl | 34a69ef307845983c5c25dc8ae47436604f27bd6 | [
"BSD-3-Clause"
] | 2 | 2018-06-01T12:19:08.000Z | 2019-11-02T19:28:09.000Z | #!/usr/bin/env python
import sys
import re
import os.path
import allura_issues
# API docs:
# http://code.google.com/p/support/wiki/IssueTrackerAPIPython
import gdata.projecthosting.client
import gdata.projecthosting.data
import gdata.gauth
import gdata.client
import gdata.data
import atom.http_core
import atom.core
def string_is_nonnegative_number(case):
try:
return int(case) >= 0
except:
return False
class PatchBot():
client = gdata.projecthosting.client.ProjectHostingClient()
# you can use mewes for complete junk testing
#PROJECT_NAME = "mewes"
PROJECT_NAME = "lilypond"
username = None
password = None
def get_credentials(self):
# TODO: can we use the coderview cookie for this?
#filename = os.path.expanduser("~/.codereview_upload_cookies")
filename = os.path.expanduser("~/.lilypond-project-hosting-login")
try:
login_data = open(filename).readlines()
self.username = login_data[0]
self.password = login_data[1]
except:
print "Could not find stored credentials"
print " %(filename)s" % locals()
print "Please enter login details manually"
print
import getpass
print "Username (google account name):"
self.username = raw_input().strip()
self.password = getpass.getpass()
def login(self):
try:
self.client.client_login(
self.username, self.password,
source='lilypond-patch-handler', service='code')
except:
print "Incorrect username or password"
sys.exit(1)
def create_issue(self, subject, description):
"""Create an issue."""
issue = self.client.add_issue(
self.PROJECT_NAME,
"Patch: " + subject,
description,
self.username,
owner = self.username,
status = "Started",
labels = ["Type-Enhancement", "Patch-new"])
# get the issue number extracted from the URL
issue_id = int(re.search("[0-9]+", issue.id.text).group(0))
# update the issue to set the owner
return self.update_issue(issue_id, "")
def generate_devel_error(self, issue_id) :
print "WARNING: could not change issue labels;"
if issue_id is None:
print "please email lilypond-devel with a general",
print "description of the problem"
else:
print "please email lilypond-devel with the issue",
print "number: %s" % issue_id
def update_issue(self, issue_id, description):
try:
issue = self.client.update_issue(
self.PROJECT_NAME,
issue_id,
self.username,
comment = description,
owner = self.username,
status = "Started",
labels = ["Patch-new"])
# TODO: this is a bit hack-ish, but I'm new to exceptions
except gdata.client.RequestError as err:
if err.body == "No permission to edit issue":
if description != "":
issue = self.client.update_issue(
self.PROJECT_NAME,
issue_id,
self.username,
comment = description)
self.generate_devel_error(issue_id)
print err.body
elif err.body == "There were no updates performed.":
pass
else:
self.generate_devel_error(issue_id)
print err.body
return None
return issue_id
def find_fix_issue_id(self, text):
splittext = re.findall(r'\w+', text)
issue_id = None
# greedy search for the issue id
for i, word in enumerate(splittext):
if word in ["fix", "issue", "Fix", "Issue"]:
try:
maybe_number = splittext[i+1]
if maybe_number[-1] == ")":
maybe_number = maybe_number[:-1]
issue_id = int(maybe_number)
break
except:
pass
if not issue_id:
try:
maybe_number = re.findall(r'\([0-9]+\)', text)
issue_id = int(maybe_number[0][1:-1])
except:
pass
return issue_id
def query_user(self, issue = None) :
query_string1 = "We were not able to associate this patch with a tracker issue." if issue == None else str(issue)+" will not be used as a tracker number."
print query_string1
info = raw_input("Please enter a valid tracker issue number\n"
"(or enter nothing to create a new issue): ")
while info and (not string_is_nonnegative_number(info)):
info = raw_input("This is an invalid entry. Please enter either an issue number (just digits, no spaces) or nothing to create an issue: ")
if info:
return int(info)
return None
def upload(self, issue, patchset, subject="", description="", issue_id=None):
# NB. issue is the Rietveld issue; issue_id is the Allura issue
if not subject:
subject = "new patch"
# update or create?
if not issue_id:
# Looks for issue number in the description
issue_id = self.find_fix_issue_id(subject+' '+description)
if issue_id:
print "This has been identified with issue "+str(issue_id)+"."
correct = raw_input("Is this correct? [y/n (y)]")
if correct == 'n':
issue_id = None
if not issue_id:
issue_id = self.query_user(issue_id)
code_review_url = "https://codereview.appspot.com/" + issue
if issue_id:
issue_id = allura_issues.update_issue(issue_id, description,
code_review_url)
else:
# If the subject is repeated as the first paragraph of the
# description, eliminate the redundancy.
if description.strip() == subject.strip():
description = ""
elif description.startswith(subject + "\n\n"):
description = description[len(subject):].lstrip("\n")
# An issue number in the subject line is redundant in the
# issue tracker (unlike in the code review). Recognize
# [Xx]+ as a placeholder for a number that was unknown
# when the user entered the subject.
subject = re.sub(r"^\s*Issue\s+#?(\d+|[Xx]+):?\s*", "", subject)
issue_id = allura_issues.create_issue(subject, description,
code_review_url)
return issue_id
# hacky integration
def upload(issue, patchset, subject="", description="", issue_id=None):
patchy = PatchBot()
status = patchy.upload(issue, patchset, subject, description, issue_id)
if status:
print "Tracker issue done: %s" % status
else:
print "Problem with the tracker issue"
return status
| 36.567839 | 162 | 0.56232 |
64263d0911e289f0607f2feb1f29e06951af8f0c | 6,888 | py | Python | shapes_operator/tera_shape_export.py | MovingBlocks/BlenderAddon | 3a261ea12e62fa3dee500bc4ef487786be35e854 | [
"Apache-2.0"
] | 4 | 2018-10-13T07:58:34.000Z | 2020-10-12T19:36:27.000Z | shapes_operator/tera_shape_export.py | MovingBlocks/BlenderAddon | 3a261ea12e62fa3dee500bc4ef487786be35e854 | [
"Apache-2.0"
] | 2 | 2019-12-12T05:36:01.000Z | 2021-04-03T20:38:23.000Z | shapes_operator/tera_shape_export.py | MovingBlocks/BlenderAddon | 3a261ea12e62fa3dee500bc4ef487786be35e854 | [
"Apache-2.0"
] | 6 | 2018-09-27T15:51:46.000Z | 2021-03-21T09:23:37.000Z | import json
import re
from _ctypes import PyObj_FromPtr
import bpy
import bmesh
from bpy.props import BoolProperty, StringProperty
import bpy_extras.io_utils
import json
import datetime
import mathutils
class NoIndent(object):
""" Value wrapper. """
def __init__(self, value):
self.value = value
class Encoder(json.JSONEncoder):
FORMAT_SPEC = '@@{}@@'
regex = re.compile(FORMAT_SPEC.format(r'(\d+)'))
def __init__(self, **kwargs):
# Save copy of any keyword argument values needed for use here.
self.__sort_keys = kwargs.get('sort_keys', None)
super(Encoder, self).__init__(**kwargs)
def default(self, obj):
return (self.FORMAT_SPEC.format(id(obj)) if isinstance(obj, NoIndent)
else super(Encoder, self).default(obj))
def encode(self, obj):
format_spec = self.FORMAT_SPEC # Local var to expedite access.
json_repr = super(Encoder, self).encode(obj) # Default JSON.
# Replace any marked-up object ids in the JSON repr with the
# value returned from the json.dumps() of the corresponding
# wrapped Python object.
for match in self.regex.finditer(json_repr):
# see https://stackoverflow.com/a/15012814/355230
id = int(match.group(1))
no_indent = PyObj_FromPtr(id)
json_obj_repr = json.dumps(
no_indent.value, sort_keys=self.__sort_keys)
# Replace the matched id string with json formatted representation
# of the corresponding Python object.
json_repr = json_repr.replace(
'"{}"'.format(format_spec.format(id)), json_obj_repr)
return json_repr
class TERA_SHAPE_OT_shape_exporter(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):
bl_idname = "tera.export_shape"
bl_label = "Export Terasology Block Shape"
filename_ext = ".shape"
filter_glob: StringProperty(default="*.shape", options={'HIDDEN'})
apply_modifiers: BoolProperty(
name="Apply Modifiers",
description="Apply Modifiers to the exported mesh",
default=True)
@classmethod
def poll(cls, context):
return 0 < context.scene.tera_shape_select_index < len(bpy.data.objects)
def meshify(self, bm):
mesh = bpy.data.meshes.new('temp')
bm.to_mesh(mesh)
result = {}
result['vertices'] = []
result['normals'] = []
result['texcoords'] = []
result['faces'] = []
for vert in mesh.vertices:
result['vertices'].append(
NoIndent([-vert.co.x, vert.co.z, vert.co.y]))
result['normals'].append(
NoIndent([-vert.normal.x, vert.normal.z, vert.normal.y]))
uv_active = mesh.uv_layers.active
result['texcoords'] = [NoIndent([0,0]) for _ in range(0, len(mesh.loops))]
for i, layer in enumerate(uv_active.data):
result['texcoords'][mesh.loops[i].vertex_index] = NoIndent([layer.uv[0], 1.0 - layer.uv[1]])
mesh.calc_loop_triangles()
for tri in mesh.loop_triangles:
result['faces'].append(NoIndent([mesh.loops[i].vertex_index for i in tri.loops]))
bpy.data.meshes.remove(mesh)
return result
def execute(self, context):
path = bpy.path.ensure_ext(self.filepath, self.filename_ext)
if (0 < context.scene.tera_shape_select_index < len(bpy.data.objects)):
selected_object = bpy.data.objects[context.scene.tera_shape_select_index]
shape = selected_object.tera_shape
result = {}
result['displayName'] = shape.display_name
result['author'] = shape.author
now = datetime.datetime.now()
result['exportDate'] = '{:%Y-%m-%d %H:%M:%S}'.format(now)
meshes = {}
is_full_side = {}
for child in selected_object.children:
if(child.type == 'MESH'):
if(child.data.tera_mesh.part not in meshes):
meshes[child.data.tera_mesh.part] = bmesh.new()
is_full_side[child.data.tera_mesh.part] = False
is_full_side[child.data.tera_mesh.part] = (
True if is_full_side[child.data.tera_mesh.part] else child.data.tera_mesh.full_side)
mesh = bpy.data.meshes.new('temp')
temp = bmesh.new()
temp.from_mesh(child.data)
bmesh.ops.transform(temp, matrix=selected_object.matrix_world.inverted() @ child.matrix_world, verts=temp.verts)
temp.to_mesh(mesh)
meshes[child.data.tera_mesh.part].from_mesh(mesh)
bpy.data.meshes.remove(mesh)
temp.free()
for key, value in meshes.items():
# bmesh.ops.transform(value, matrix=matrix_world.inverted(), verts=value.verts)
result[key] = self.meshify(value)
result[key]['fullSide'] = is_full_side[key]
value.free()
result['collision'] = {}
hasColliders = False
if(shape.aabb):
hasColliders = True
if('colliders' not in result['collision']):
result['collision']['colliders'] = []
for aabb in shape.aabb:
result['collision']['colliders'].append({
'type': 'AABB',
'position': NoIndent([aabb.origin[0], aabb.origin[2], aabb.origin[1]]),
'extents': NoIndent([aabb.extent[0], aabb.extent[2], aabb.extent[1]])
})
if (hasColliders == True):
result['collision']["symmetric"] = shape.symmetric
result['collision']['yawSymmetric'] = shape.yaw_symmetric
result['collision']['pitchSymmetric'] = shape.pitch_symmetric
result['collision']['rollSymmetric'] = shape.roll_symmetric
result['collision']['convexHull'] = shape.convex_hull
file = open(path, "w", encoding="utf8")
print("saving complete: %r " % path)
file.write(json.dumps(result, indent=2,
separators=(',', ': '), cls=Encoder))
file.close()
# filepath = self.filepath
# from . import _export_block_shape
# keywords = self.as_keywords(ignore=("filter_glob", "check_existing"))
return {'FINISHED'}
def draw(self, context):
layout = self.layout
layout.row().label(text="Selected Shape")
layout.row().prop(self, "apply_modifiers")
row = self.layout.row()
row.template_list("TERA_SHAPES_UL_shape", "", bpy.data,
"objects", context.scene, "tera_shape_select_index")
| 37.846154 | 132 | 0.58072 |
425df296c4157089653a99e7f9b2274e453fcb1e | 8,761 | py | Python | src/environments/tests/test_permissions.py | nixplay/bullet-train-api | 608422d174443a4d9178d875ccaeb756a771e908 | [
"BSD-3-Clause"
] | null | null | null | src/environments/tests/test_permissions.py | nixplay/bullet-train-api | 608422d174443a4d9178d875ccaeb756a771e908 | [
"BSD-3-Clause"
] | null | null | null | src/environments/tests/test_permissions.py | nixplay/bullet-train-api | 608422d174443a4d9178d875ccaeb756a771e908 | [
"BSD-3-Clause"
] | null | null | null | from unittest import TestCase, mock
import pytest
from environments.models import Environment, UserEnvironmentPermission, Identity
from environments.permissions import EnvironmentPermissions, NestedEnvironmentPermissions
from organisations.models import Organisation, OrganisationRole
from projects.models import Project, UserProjectPermission, ProjectPermissionModel
from users.models import FFAdminUser
mock_view = mock.MagicMock()
mock_request = mock.MagicMock()
environment_permissions = EnvironmentPermissions()
nested_environment_permissions = NestedEnvironmentPermissions()
@pytest.mark.django_db
class EnvironmentPermissionsTestCase(TestCase):
def setUp(self) -> None:
self.organisation = Organisation.objects.create(name='Test')
self.org_admin = FFAdminUser.objects.create(email='admin@test.com')
self.org_admin.add_organisation(self.organisation, OrganisationRole.ADMIN)
self.user = FFAdminUser.objects.create(email='user@test.com')
self.user.add_organisation(self.organisation, OrganisationRole.USER)
self.project = Project.objects.create(name='Test Project', organisation=self.organisation)
self.environment = Environment.objects.create(name='Test Environment', project=self.project)
def test_org_admin_can_create_environment_for_any_project(self):
# Given
mock_view.action = 'create'
mock_view.detail = False
mock_request.user = self.org_admin
mock_request.data = {
'project': self.project.id,
'name': 'Test environment'
}
# When
result = environment_permissions.has_permission(mock_request, mock_view)
# Then
assert result
def test_project_admin_can_create_environment_in_project(self):
# Given
UserProjectPermission.objects.create(user=self.user, project=self.project, admin=True)
mock_request.user = self.user
mock_view.action = 'create'
mock_view.detail = False
mock_request.data = {
'project': self.project.id,
'name': 'Test environment'
}
# When
result = environment_permissions.has_permission(mock_request, mock_view)
# Then
assert result
def test_project_user_with_create_environment_permission_can_create_environment(self):
# Given
create_environment_permission = ProjectPermissionModel.objects.get(key="CREATE_ENVIRONMENT")
user_project_permission = UserProjectPermission.objects.create(user=self.user, project=self.project)
user_project_permission.permissions.set([create_environment_permission])
mock_request.user = self.user
mock_view.action = 'create'
mock_view.detail = False
mock_request.data = {
'project': self.project.id,
'name': 'Test environment'
}
# When
result = environment_permissions.has_permission(mock_request, mock_view)
# Then
assert result
def test_project_user_without_create_environment_permission_cannot_create_environment(self):
# Given
mock_request.user = self.user
mock_view.action = 'create'
mock_view.detail = False
mock_request.data = {
'project': self.project.id,
'name': 'Test environment'
}
# When
result = environment_permissions.has_permission(mock_request, mock_view)
# Then
assert not result
def test_all_users_can_list_environments_for_project(self):
# Given
mock_view.action = 'list'
mock_view.detail = False
mock_request.user = self.user
# When
result = environment_permissions.has_permission(mock_request, mock_view)
# Then
assert result
def test_organisation_admin_can_delete_environment(self):
# Given
mock_view.action = 'delete'
mock_view.detail = True
mock_request.user = self.org_admin
# When
result = environment_permissions.has_object_permission(mock_request, mock_view, self.environment)
# Then
assert result
def test_project_admin_can_delete_environment(self):
# Given
UserProjectPermission.objects.create(user=self.user, project=self.project, admin=True)
mock_request.user = self.user
mock_view.action = 'delete'
mock_view.detail = True
# When
result = environment_permissions.has_object_permission(mock_request, mock_view, self.environment)
# Then
assert result
def test_environment_admin_can_delete_environment(self):
# Given
UserEnvironmentPermission.objects.create(user=self.user, environment=self.environment, admin=True)
mock_request.user = self.user
mock_view.action = 'delete'
mock_view.detail = True
# When
result = environment_permissions.has_object_permission(mock_request, mock_view, self.environment)
# Then
assert result
def test_regular_user_cannot_delete_environment(self):
# Given
mock_request.user = self.user
mock_view.action = 'delete'
mock_view.detail = True
# When
result = environment_permissions.has_object_permission(mock_request, mock_view, self.environment)
# Then
assert not result
@pytest.mark.django_db
class NestedEnvironmentPermissionsTestCase(TestCase):
def setUp(self) -> None:
self.organisation = Organisation.objects.create(name='Test')
self.org_admin = FFAdminUser.objects.create(email='admin@test.com')
self.org_admin.add_organisation(self.organisation, OrganisationRole.ADMIN)
self.user = FFAdminUser.objects.create(email='user@test.com')
self.user.add_organisation(self.organisation, OrganisationRole.USER)
self.project = Project.objects.create(name='Test Project', organisation=self.organisation)
self.environment = Environment.objects.create(name='Test Environment', project=self.project)
self.identity = Identity.objects.create(identifier='test-identity', environment=self.environment)
def test_organisation_admin_has_create_permission(self):
# Given
mock_view.action = 'create'
mock_view.detail = False
mock_request.user = self.org_admin
mock_view.kwargs = {
'environment_api_key': self.environment.api_key
}
# When
result = nested_environment_permissions.has_permission(mock_request, mock_view)
# Then
assert result
def test_environment_admin_has_create_permission(self):
# Given
UserEnvironmentPermission.objects.create(user=self.user, environment=self.environment, admin=True)
mock_view.action = 'create'
mock_view.detail = False
mock_view.kwargs = {
'environment_api_key': self.environment.api_key
}
mock_request.user = self.user
# When
result = nested_environment_permissions.has_permission(mock_request, mock_view)
# Then
assert result
def test_regular_user_does_not_have_create_permission(self):
# Given
mock_view.action = 'create'
mock_view.detail = False
mock_request.user = self.user
mock_view.kwargs = {
'environment_api_key': self.environment.api_key
}
# When
result = nested_environment_permissions.has_permission(mock_request, mock_view)
# Then
assert not result
def test_organisation_admin_has_destroy_permission(self):
# Given
mock_view.action = 'destroy'
mock_view.detail = True
mock_request.user = self.org_admin
# When
result = nested_environment_permissions.has_object_permission(mock_request, mock_view, self.identity)
# Then
assert result
def test_environment_admin_has_destroy_permission(self):
# Given
UserEnvironmentPermission.objects.create(user=self.user, environment=self.environment, admin=True)
mock_view.action = 'destroy'
mock_view.detail = True
mock_request.user = self.user
# When
result = nested_environment_permissions.has_object_permission(mock_request, mock_view, self.identity)
# Then
assert result
def test_regular_user_does_not_have_destroy_permission(self):
# Given
mock_view.action = 'destroy'
mock_view.detail = True
mock_request.user = self.user
# When
result = nested_environment_permissions.has_object_permission(mock_request, mock_view, self.identity)
# Then
assert not result
| 33.311787 | 109 | 0.687364 |
f9bf875b4df682b5402026590f9c6f2997947502 | 3,271 | py | Python | smartrecruiters_python_client/models/user_language.py | roksela/smartrecruiters-python-client | 6d0849d173a3d6718b5f0769098f4c76857f637d | [
"MIT"
] | 5 | 2018-03-27T08:20:13.000Z | 2022-03-30T06:23:38.000Z | smartrecruiters_python_client/models/user_language.py | roksela/smartrecruiters-python-client | 6d0849d173a3d6718b5f0769098f4c76857f637d | [
"MIT"
] | null | null | null | smartrecruiters_python_client/models/user_language.py | roksela/smartrecruiters-python-client | 6d0849d173a3d6718b5f0769098f4c76857f637d | [
"MIT"
] | 2 | 2018-12-05T04:48:37.000Z | 2020-12-17T12:12:12.000Z | # coding: utf-8
"""
Unofficial python library for the SmartRecruiters API
The SmartRecruiters API provides a platform to integrate services or applications, build apps and create fully customizable career sites. It exposes SmartRecruiters functionality and allows to connect and build software enhancing it.
OpenAPI spec version: 1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class UserLanguage(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, code=None):
"""
UserLanguage - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'code': 'UserLanguageCode'
}
self.attribute_map = {
'code': 'code'
}
self._code = code
@property
def code(self):
"""
Gets the code of this UserLanguage.
Language assigned to user account
:return: The code of this UserLanguage.
:rtype: UserLanguageCode
"""
return self._code
@code.setter
def code(self, code):
"""
Sets the code of this UserLanguage.
Language assigned to user account
:param code: The code of this UserLanguage.
:type: UserLanguageCode
"""
if code is None:
raise ValueError("Invalid value for `code`, must not be `None`")
self._code = code
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, UserLanguage):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| 27.258333 | 237 | 0.551819 |
62dd0c7bc03335863348803abc9fad659f2058d7 | 163 | py | Python | mundo 1/030.py | thiagofreitascarneiro/Curso-de-Python---Curso-em-Video | 0342e482780b5a1c6f78cddd51d9bfad785c79fa | [
"MIT"
] | 1 | 2021-08-04T13:21:22.000Z | 2021-08-04T13:21:22.000Z | mundo 1/030.py | thiagofreitascarneiro/Curso-de-Python---Curso-em-Video | 0342e482780b5a1c6f78cddd51d9bfad785c79fa | [
"MIT"
] | null | null | null | mundo 1/030.py | thiagofreitascarneiro/Curso-de-Python---Curso-em-Video | 0342e482780b5a1c6f78cddd51d9bfad785c79fa | [
"MIT"
] | null | null | null | numero = int(input('Digite um numero qualquer:'))
resto = numero%2
if resto == 0:
print(f'O numero {numero} é par')
else:
print(f'numero {numero} é impar') | 27.166667 | 49 | 0.656442 |
28adb924e0a4b7d3aac0d7e3eb255bc448880322 | 1,248 | py | Python | felpy/model/core/detector_test.py | twguest/FELpy | 0ac9dd965b0d8e04dddbf2c9aef5ac137d1f0dfd | [
"Apache-2.0"
] | 1 | 2021-03-15T14:04:19.000Z | 2021-03-15T14:04:19.000Z | felpy/model/core/detector_test.py | twguest/FELpy | 0ac9dd965b0d8e04dddbf2c9aef5ac137d1f0dfd | [
"Apache-2.0"
] | 2 | 2021-11-27T11:55:48.000Z | 2021-11-27T11:56:26.000Z | felpy/model/core/detector_test.py | twguest/FELpy | 0ac9dd965b0d8e04dddbf2c9aef5ac137d1f0dfd | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""
hybrid wpg-felpy detector module
"""
from felpy.model.src.coherent import construct_SA1_pulse
from wpg.srwlib import SRWLDet
from felpy.model.core.beamline import Beamline
from felpy.model.tools import propagation_parameters
from wpg.optical_elements import Drift
class Detector:
def __init__(self, dx, dy, nx, ny):
"""
:param dx: detector pixel size
:param dy: detector pixel size
:param nx: number of pixels
:param ny: number of pixels
"""
self.dx = dx
self.dy = dy
self.nx = nx
self.ny = ny
def detect(self, wfr):
xMin, xMax, yMax, yMin = wfr.get_limits()
idx, idy = xMax-xMin, yMax-yMin
inx, iny = wfr.params.Mesh.nx, wfr.params.Mesh.ny
print(idx,idy)
print((self.dy*self.ny)/idy)
bl = Beamline()
bl.append(Drift(0),
propagation_parameters((self.dx*self.nx)/idx, self.nx/inx, (self.dy*self.ny)/idy, self.ny/iny))
bl.propagate(wfr)
if __name__ == '__main__':
wfr = construct_SA1_pulse(512, 512, 5, 5.0, 0.25)
det = Detector(1e-06, 1e-06, 1024, 1024)
det.detect(wfr) | 25.469388 | 113 | 0.581731 |
9e735a9c4f8ddadc263e85aefe937e45b87be438 | 502 | py | Python | scripts/quest/q31146e.py | Snewmy/swordie | ae01ed4ec0eb20a18730e8cd209eea0b84a8dd17 | [
"MIT"
] | 9 | 2021-04-26T11:59:29.000Z | 2021-12-20T13:15:27.000Z | scripts/quest/q31146e.py | Snewmy/swordie | ae01ed4ec0eb20a18730e8cd209eea0b84a8dd17 | [
"MIT"
] | null | null | null | scripts/quest/q31146e.py | Snewmy/swordie | ae01ed4ec0eb20a18730e8cd209eea0b84a8dd17 | [
"MIT"
] | 6 | 2021-07-14T06:32:05.000Z | 2022-02-06T02:32:56.000Z | # Knight Stronghold: Secret Grove
# Quest: Rescue Neinhart
NEINHEART = 2143001
sm.setSpeakerID(NEINHEART)
sm.completeQuest(parentID)
sm.sendNext("Thank you for saving me, but I'll remain here. My"
"\r\ndissapearance would only make things worse. Besides,"
"\r\nI should be able to do some good from here.")
sm.sendSay("Please tell Alex my decision.")
sm.sendPrev("And please...stop her. There's no way to get the old"
"\r\nCygnus back. We only have one option...") | 38.615385 | 70 | 0.693227 |
e47c507bd5833d6830b99476d5813a043db51ca5 | 8,359 | py | Python | test/functional/feature_proxy.py | orobio/gulden-official | a329faf163b15eabc7ff1d9f07ea87f66df8d27d | [
"MIT"
] | 158 | 2016-01-08T10:38:37.000Z | 2022-02-01T06:28:05.000Z | test/functional/feature_proxy.py | orobio/gulden-official | a329faf163b15eabc7ff1d9f07ea87f66df8d27d | [
"MIT"
] | 196 | 2015-11-19T10:59:24.000Z | 2021-10-07T14:52:13.000Z | test/functional/feature_proxy.py | orobio/gulden-official | a329faf163b15eabc7ff1d9f07ea87f66df8d27d | [
"MIT"
] | 71 | 2016-06-25T23:29:04.000Z | 2022-03-14T10:57:19.000Z | #!/usr/bin/env python3
# Copyright (c) 2015-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test GuldenD with different proxy configuration.
Test plan:
- Start GuldenD's with different proxy configurations
- Use addnode to initiate connections
- Verify that proxies are connected to, and the right connection command is given
- Proxy configurations to test on GuldenD side:
- `-proxy` (proxy everything)
- `-onion` (proxy just onions)
- `-proxyrandomize` Circuit randomization
- Proxy configurations to test on proxy side,
- support no authentication (other proxy)
- support no authentication + user/pass authentication (Tor)
- proxy on IPv6
- Create various proxies (as threads)
- Create GuldenDs that connect to them
- Manipulate the GuldenDs using addnode (onetry) an observe effects
addnode connect to IPv4
addnode connect to IPv6
addnode connect to onion
addnode connect to generic DNS name
"""
import socket
import os
from test_framework.socks5 import Socks5Configuration, Socks5Command, Socks5Server, AddressType
from test_framework.test_framework import GuldenTestFramework
from test_framework.util import (
PORT_MIN,
PORT_RANGE,
assert_equal,
)
from test_framework.netutil import test_ipv6_local
RANGE_BEGIN = PORT_MIN + 2 * PORT_RANGE # Start after p2p and rpc ports
class ProxyTest(GuldenTestFramework):
def set_test_params(self):
self.num_nodes = 4
self.setup_clean_chain = True
def setup_nodes(self):
self.have_ipv6 = test_ipv6_local()
# Create two proxies on different ports
# ... one unauthenticated
self.conf1 = Socks5Configuration()
self.conf1.addr = ('127.0.0.1', RANGE_BEGIN + (os.getpid() % 1000))
self.conf1.unauth = True
self.conf1.auth = False
# ... one supporting authenticated and unauthenticated (Tor)
self.conf2 = Socks5Configuration()
self.conf2.addr = ('127.0.0.1', RANGE_BEGIN + 1000 + (os.getpid() % 1000))
self.conf2.unauth = True
self.conf2.auth = True
if self.have_ipv6:
# ... one on IPv6 with similar configuration
self.conf3 = Socks5Configuration()
self.conf3.af = socket.AF_INET6
self.conf3.addr = ('::1', RANGE_BEGIN + 2000 + (os.getpid() % 1000))
self.conf3.unauth = True
self.conf3.auth = True
else:
self.log.warning("Testing without local IPv6 support")
self.serv1 = Socks5Server(self.conf1)
self.serv1.start()
self.serv2 = Socks5Server(self.conf2)
self.serv2.start()
if self.have_ipv6:
self.serv3 = Socks5Server(self.conf3)
self.serv3.start()
# Note: proxies are not used to connect to local nodes
# this is because the proxy to use is based on CService.GetNetwork(), which return NET_UNROUTABLE for localhost
args = [
['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-proxyrandomize=1'],
['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-onion=%s:%i' % (self.conf2.addr),'-proxyrandomize=0'],
['-listen', '-proxy=%s:%i' % (self.conf2.addr),'-proxyrandomize=1'],
[]
]
if self.have_ipv6:
args[3] = ['-listen', '-proxy=[%s]:%i' % (self.conf3.addr),'-proxyrandomize=0', '-noonion']
self.add_nodes(self.num_nodes, extra_args=args)
self.start_nodes()
def node_test(self, node, proxies, auth, test_onion=True):
rv = []
# Test: outgoing IPv4 connection through node
node.addnode("15.61.23.23:1234", "onetry")
cmd = proxies[0].queue.get()
assert isinstance(cmd, Socks5Command)
# Note: GuldenD's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"15.61.23.23")
assert_equal(cmd.port, 1234)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
if self.have_ipv6:
# Test: outgoing IPv6 connection through node
node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry")
cmd = proxies[1].queue.get()
assert isinstance(cmd, Socks5Command)
# Note: GuldenD's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"1233:3432:2434:2343:3234:2345:6546:4534")
assert_equal(cmd.port, 5443)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
if test_onion:
# Test: outgoing onion connection through node
node.addnode("bitcoinostk4e4re.onion:8333", "onetry")
cmd = proxies[2].queue.get()
assert isinstance(cmd, Socks5Command)
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"bitcoinostk4e4re.onion")
assert_equal(cmd.port, 8333)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
# Test: outgoing DNS name connection through node
node.addnode("node.noumenon:8333", "onetry")
cmd = proxies[3].queue.get()
assert isinstance(cmd, Socks5Command)
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"node.noumenon")
assert_equal(cmd.port, 8333)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
return rv
def run_test(self):
# basic -proxy
self.node_test(self.nodes[0], [self.serv1, self.serv1, self.serv1, self.serv1], False)
# -proxy plus -onion
self.node_test(self.nodes[1], [self.serv1, self.serv1, self.serv2, self.serv1], False)
# -proxy plus -onion, -proxyrandomize
rv = self.node_test(self.nodes[2], [self.serv2, self.serv2, self.serv2, self.serv2], True)
# Check that credentials as used for -proxyrandomize connections are unique
credentials = set((x.username,x.password) for x in rv)
assert_equal(len(credentials), len(rv))
if self.have_ipv6:
# proxy on IPv6 localhost
self.node_test(self.nodes[3], [self.serv3, self.serv3, self.serv3, self.serv3], False, False)
def networks_dict(d):
r = {}
for x in d['networks']:
r[x['name']] = x
return r
# test RPC getnetworkinfo
n0 = networks_dict(self.nodes[0].getnetworkinfo())
for net in ['ipv4','ipv6','onion']:
assert_equal(n0[net]['proxy'], '%s:%i' % (self.conf1.addr))
assert_equal(n0[net]['proxy_randomize_credentials'], True)
assert_equal(n0['onion']['reachable'], True)
n1 = networks_dict(self.nodes[1].getnetworkinfo())
for net in ['ipv4','ipv6']:
assert_equal(n1[net]['proxy'], '%s:%i' % (self.conf1.addr))
assert_equal(n1[net]['proxy_randomize_credentials'], False)
assert_equal(n1['onion']['proxy'], '%s:%i' % (self.conf2.addr))
assert_equal(n1['onion']['proxy_randomize_credentials'], False)
assert_equal(n1['onion']['reachable'], True)
n2 = networks_dict(self.nodes[2].getnetworkinfo())
for net in ['ipv4','ipv6','onion']:
assert_equal(n2[net]['proxy'], '%s:%i' % (self.conf2.addr))
assert_equal(n2[net]['proxy_randomize_credentials'], True)
assert_equal(n2['onion']['reachable'], True)
if self.have_ipv6:
n3 = networks_dict(self.nodes[3].getnetworkinfo())
for net in ['ipv4','ipv6']:
assert_equal(n3[net]['proxy'], '[%s]:%i' % (self.conf3.addr))
assert_equal(n3[net]['proxy_randomize_credentials'], False)
assert_equal(n3['onion']['reachable'], False)
if __name__ == '__main__':
ProxyTest().main()
| 41.381188 | 120 | 0.625793 |
73427622af9efa6dfcd351f236ffacb11bc2a1ad | 769 | py | Python | xcparse/Xcode/XCSchemeActions/BuildableReference.py | samdmarshall/xcparser | 4f78af149127325e60e3785b6e09d6dbfeedc799 | [
"BSD-3-Clause"
] | 59 | 2015-02-27T21:45:37.000Z | 2021-03-16T04:37:40.000Z | xcparse/Xcode/XCSchemeActions/BuildableReference.py | samdmarshall/xcparser | 4f78af149127325e60e3785b6e09d6dbfeedc799 | [
"BSD-3-Clause"
] | 14 | 2015-03-02T18:53:51.000Z | 2016-07-19T23:20:23.000Z | xcparse/Xcode/XCSchemeActions/BuildableReference.py | samdmarshall/xcparser | 4f78af149127325e60e3785b6e09d6dbfeedc799 | [
"BSD-3-Clause"
] | 8 | 2015-03-02T02:32:09.000Z | 2017-07-31T21:14:51.000Z | class BuildableReference(object):
def __init__(self, entry_item):
self.contents = entry_item;
if 'BuildableIdentifier' in self.contents.keys():
self.BuildableIdentifier = self.contents.get('BuildableIdentifier');
if 'BlueprintIdentifier' in self.contents.keys():
self.BlueprintIdentifier = self.contents.get('BlueprintIdentifier');
if 'BuildableName' in self.contents.keys():
self.BuildableName = self.contents.get('BuildableName');
if 'BlueprintName' in self.contents.keys():
self.BlueprintName = self.contents.get('BlueprintName');
if 'ReferencedContainer' in self.contents.keys():
self.ReferencedContainer = self.contents.get('ReferencedContainer'); | 54.928571 | 80 | 0.676203 |
562bba209bc481e62bf55b6e2a19a3688724c98f | 750 | py | Python | DPMailer/urls.py | dphans/DPMailer | 57a0f8575de01a9436b592e73c55d5fe108d6e4d | [
"MIT"
] | null | null | null | DPMailer/urls.py | dphans/DPMailer | 57a0f8575de01a9436b592e73c55d5fe108d6e4d | [
"MIT"
] | null | null | null | DPMailer/urls.py | dphans/DPMailer | 57a0f8575de01a9436b592e73c55d5fe108d6e4d | [
"MIT"
] | null | null | null | """DPMailer URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
| 34.090909 | 77 | 0.709333 |
a6e567ec0aa94f1cf11bc0209b1a5723996f1c91 | 4,857 | py | Python | config.py | Potapov-AA/CaesarCipherWithKeyword | 4bd520418254b56950be079d0fce638039d4e202 | [
"MIT"
] | null | null | null | config.py | Potapov-AA/CaesarCipherWithKeyword | 4bd520418254b56950be079d0fce638039d4e202 | [
"MIT"
] | null | null | null | config.py | Potapov-AA/CaesarCipherWithKeyword | 4bd520418254b56950be079d0fce638039d4e202 | [
"MIT"
] | null | null | null | import re
import time
class CONFIG(object):
# Доступные алфавиты для шифрования
alphaList_En = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
alphaList_Ru = list("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ")
alphaList = object
new_alphaList = object
def __init__(self, choseAlphaList:str, numberKey:str, stringKey:str):
try:
# Выбор алфавита для шифрования
if choseAlphaList.upper() == "RU":
self.alphaList = self.alphaList_Ru.copy()
else:
self.alphaList = self.alphaList_En.copy()
# Числовой ключ и ключ для печати
try:
self.numberKey = int(numberKey) - 1
self.printKey = int(numberKey) - 1
# Проверка на отрицательное значение
if self.numberKey < 0:
self.numberKey = int(len(self.alphaList) - 1)
self.printKey = int(len(self.alphaList) - 1)
# Проверка на значение больше размера алфавита
while self.numberKey > len(self.alphaList) - 1:
self.numberKey -= len(self.alphaList) - 1
except ValueError:
print("Error: Invalid value entered, default number will be used (13)!")
self.numberKey = int(13)
self.printKey = int(13)
time.sleep(2)
# Ключевое слово
if choseAlphaList.upper() == 'RU':
self.stringKey = re.sub("[^А-яа-я]", "", stringKey).upper()
else:
self.stringKey = re.sub("[^A-Za-z]", "", stringKey).upper()
# Проверка на нулевую длину ключевого слова
# Если больше нуля то удаляет повторяющиеся символы и формирует новую строку
if len(self.stringKey) > 0:
for i in self.stringKey:
first = self.stringKey.index(i) + len(i)
self.stringKey = self.stringKey[:first] + self.stringKey[first:].replace(i, "")
# Если передана не корректная строка или строка нулевой длины, то устанавливается слово во умолчанию
else:
if choseAlphaList.upper() == 'RU':
print("Error: Incorrect value entered, the default word (ШУТ) will be used!")
self.stringKey = "ШУТ"
else:
print("Error: Incorrect value entered, the default word (DIPLOMAT) will be used!")
self.stringKey = "DIPLOMAT"
time.sleep(2)
# Алфавит для шифрования
alphaList_update = self.alphaList.copy()# Обновленный алфавит без символов ключевого слова
self.new_alphaList = [None] * len(self.alphaList)# Заготовка для алфавита шифрования
# Удаление встречающихся символов
for i in self.stringKey:
alphaList_update.remove(i)
# Поиск следующий буквы после первой буквы ключевого слова
find_alpha = self.alphaList.index(self.stringKey[0])
while True:
if find_alpha == len(self.alphaList) - 1:
find_alpha = 0
else:
find_alpha += 1
char = self.alphaList[find_alpha]
if char in alphaList_update:
first_alpha = alphaList_update.index(char)
break
# Вставка ключевого слова в алфавит шифрования
for i in self.stringKey:
self.new_alphaList[self.numberKey] = i
if self.numberKey + 1 > len(self.new_alphaList) - 1:
self.numberKey = 0
else:
self.numberKey += 1
# Вставка оставшихся букв алфавита
for i in range(len(self.new_alphaList) - len(self.stringKey)):
try:
self.new_alphaList[self.numberKey] = alphaList_update[first_alpha]
if first_alpha + 1 > len(alphaList_update) - 1:
first_alpha = 0
else:
first_alpha += 1
if self.numberKey + 1 > len(self.new_alphaList) - 1:
self.numberKey = 0
else:
self.numberKey += 1
except Exception:
print("Error: system failed")
except Exception:
print("Error configuration!")
# Вывод на экран текущих конфигураций
def print_conf(self):
try:
print("Alphabet used: {}".format(self.alphaList))
print("Numeric Key: {}".format(self.printKey))
print("Keyword: {} ".format(self.stringKey))
print("Encryption alphabet : {} ".format(self.new_alphaList))
except:
print("Error configuration!") | 41.87069 | 112 | 0.536133 |
dd3274f33c094c7609cba4708c90907b4788a7d2 | 1,282 | py | Python | Search_DnaA_trios/11_score_trio.py | DongMeiJing/DnaA-trios | 573c8664515989c2f1f53b7fcc1c3fb928aadbce | [
"Apache-2.0"
] | null | null | null | Search_DnaA_trios/11_score_trio.py | DongMeiJing/DnaA-trios | 573c8664515989c2f1f53b7fcc1c3fb928aadbce | [
"Apache-2.0"
] | null | null | null | Search_DnaA_trios/11_score_trio.py | DongMeiJing/DnaA-trios | 573c8664515989c2f1f53b7fcc1c3fb928aadbce | [
"Apache-2.0"
] | null | null | null | import pandas as pd
import re
def get_trio_score(trio_list):
GAT_list = ['GAT']
AAT_list = ['AAT']
GAX = re.compile('.AT|GA.')
XAX = re.compile('.A.')
trio_list_new = []
for each_trio in trio_list:
trio_list_new.append(each_trio.upper())
score = 0
for each_trio_upper in trio_list_new:
if each_trio_upper in GAT_list:
score += 4
elif each_trio_upper in AAT_list:
score += 3
elif re.match(GAX, each_trio_upper):
score += 2
elif re.match(XAX, each_trio_upper):
score += 1
else:
print('each_trio_upper error', each_trio_upper)
return(score)
if __name__ == '__main__':
file_trio = r'10_minmismatch_newspacer.csv'
with open(file_trio, 'r') as f_trio:
data_trio = pd.read_csv(f_trio)
for i in data_trio.index:
# print(i)
nc = data_trio.at[i, 'Accession Number']
trio_seq = data_trio.at[i, 'DnaA-trio']
trio_seq_list = re.findall(r'.{3}', trio_seq)
trio_score = get_trio_score(trio_seq_list)
data_trio.at[i, 'trio score'] = trio_score
data_trio.to_csv('11_score_trio.csv', index=False)
| 27.869565 | 60 | 0.570983 |
42e1582169c7d4c7b3d026289c4923d7131bb5cb | 247 | py | Python | Hackerrank_python/7.collections/59.Word Order.py | manish1822510059/Hackerrank | 7c6e4553f033f067e04dc6c756ef90cb43f3c4a8 | [
"MIT"
] | 39 | 2020-09-27T05:32:05.000Z | 2022-01-08T18:04:05.000Z | Hackerrank_python/7.collections/59.Word Order.py | manish1822510059/Hackerrank | 7c6e4553f033f067e04dc6c756ef90cb43f3c4a8 | [
"MIT"
] | 5 | 2020-10-02T13:33:00.000Z | 2021-03-01T14:06:08.000Z | Hackerrank_python/7.collections/59.Word Order.py | manish1822510059/Hackerrank | 7c6e4553f033f067e04dc6c756ef90cb43f3c4a8 | [
"MIT"
] | 6 | 2020-10-03T04:04:55.000Z | 2021-10-18T04:07:53.000Z | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import*
d={}
for i in range(int(input())):
word=input()
if word in d:
d[word]+=1
else:
d[word]=1
print(len(d))
print(*d.values())
| 20.583333 | 69 | 0.607287 |
2da6c1383904273290f5323bbd117e28f5c75558 | 304 | py | Python | exercises/level_1/basic_exercises/common_list.py | eliranM98/python_course | d9431dd6c0f27fca8ca052cc2a821ed0b883136c | [
"MIT"
] | 6 | 2019-03-29T06:14:53.000Z | 2021-10-15T23:42:36.000Z | exercises/level_1/basic_exercises/common_list.py | eliranM98/python_course | d9431dd6c0f27fca8ca052cc2a821ed0b883136c | [
"MIT"
] | 4 | 2019-09-06T10:03:40.000Z | 2022-03-11T23:30:55.000Z | exercises/level_1/basic_exercises/common_list.py | eliranM98/python_course | d9431dd6c0f27fca8ca052cc2a821ed0b883136c | [
"MIT"
] | 12 | 2019-06-20T19:34:52.000Z | 2021-10-15T23:42:39.000Z | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
def intersect(a, b):
# the & is for intersection, which will take the common between the two
return list(set(a) & set(b))
def main():
print(intersect(a, b))
if __name__ == "__main__":
main()
| 19 | 75 | 0.549342 |
010839aeddb6fc580438c259bcecbea9c1b0722e | 1,215 | py | Python | chromewhip/protocol/testing.py | spinda/chromewhip | 4c8089441f0767b91840abf6a076e9f65c83bdbc | [
"MIT"
] | 97 | 2017-07-22T13:12:36.000Z | 2021-03-20T04:03:27.000Z | chromewhip/protocol/testing.py | spinda/chromewhip | 4c8089441f0767b91840abf6a076e9f65c83bdbc | [
"MIT"
] | 15 | 2017-07-20T06:33:01.000Z | 2020-11-06T15:36:18.000Z | chromewhip/protocol/testing.py | spinda/chromewhip | 4c8089441f0767b91840abf6a076e9f65c83bdbc | [
"MIT"
] | 12 | 2017-11-30T17:46:53.000Z | 2020-10-01T17:57:19.000Z | # noinspection PyPep8
# noinspection PyArgumentList
"""
AUTO-GENERATED BY `scripts/generate_protocol.py` using `data/browser_protocol.json`
and `data/js_protocol.json` as inputs! Please do not modify this file.
"""
import logging
from typing import Any, Optional, Union
from chromewhip.helpers import PayloadMixin, BaseEvent, ChromeTypeBase
log = logging.getLogger(__name__)
from chromewhip.protocol import page as Page
class Testing(PayloadMixin):
""" Testing domain is a dumping ground for the capabilities requires for browser or app testing that do not fit other
domains.
"""
@classmethod
def generateTestReport(cls,
message: Union['str'],
group: Optional['str'] = None,
):
"""Generates a report for testing.
:param message: Message to be displayed in the report.
:type message: str
:param group: Specifies the endpoint group to deliver the report to.
:type group: str
"""
return (
cls.build_send_payload("generateTestReport", {
"message": message,
"group": group,
}),
None
)
| 30.375 | 121 | 0.624691 |
8ef81ece736059954ef295510f8431484ff32496 | 2,588 | py | Python | lib/train_utils/lr_scheduler.py | pigtamer/SNIPER | 95a4c773a6e855290504932fb43adeb39f029239 | [
"Apache-2.0"
] | 2,722 | 2018-06-18T10:01:29.000Z | 2022-03-12T09:46:06.000Z | lib/train_utils/lr_scheduler.py | qijiezhao/SNIPER | 714e7399bee1e85854b3895ecaef7b143562eab4 | [
"Apache-2.0"
] | 184 | 2018-06-18T11:35:54.000Z | 2021-10-19T11:31:56.000Z | lib/train_utils/lr_scheduler.py | qijiezhao/SNIPER | 714e7399bee1e85854b3895ecaef7b143562eab4 | [
"Apache-2.0"
] | 486 | 2018-06-18T08:55:24.000Z | 2022-02-21T15:51:39.000Z | # ---------------------------------------------------------------
# SNIPER: Efficient Multi-scale Training
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Modified from https://github.com/msracver/Deformable-ConvNets
# Modified by Mahyar Najibi
# ---------------------------------------------------------------
import logging
from mxnet.lr_scheduler import LRScheduler
class WarmupMultiBatchScheduler(LRScheduler):
"""Reduce learning rate in factor at steps specified in a list
Assume the weight has been updated by n times, then the learning rate will
be
base_lr * factor^(sum((step/n)<=1)) # step is an array
Parameters
----------
step: list of int
schedule learning rate after n updates
factor: float
the factor for reducing the learning rate
"""
def __init__(self, step, factor=1, warmup=False, warmup_lr=0, warmup_step=0):
super(WarmupMultiBatchScheduler, self).__init__()
assert isinstance(step, list) and len(step) >= 1
for i, _step in enumerate(step):
if i != 0 and step[i] <= step[i-1]:
raise ValueError("Schedule step must be an increasing integer list")
if _step < 1:
raise ValueError("Schedule step must be greater or equal than 1 round")
if factor > 1.0:
raise ValueError("Factor must be no more than 1 to make lr reduce")
self.step = step
self.cur_step_ind = 0
self.factor = factor
self.count = 0
self.warmup = warmup
self.warmup_lr = warmup_lr
self.warmup_step = warmup_step
def __call__(self, num_update):
"""
Call to schedule current learning rate
Parameters
----------
num_update: int
the maximal number of updates applied to a weight.
"""
# NOTE: use while rather than if (for continuing training via load_epoch)
if self.warmup and num_update < self.warmup_step:
cur_lr = self.warmup_lr+ num_update*(self.base_lr - self.warmup_lr)/self.warmup_step
return cur_lr
while self.cur_step_ind <= len(self.step)-1:
if num_update > self.step[self.cur_step_ind]:
self.count = self.step[self.cur_step_ind]
self.cur_step_ind += 1
self.base_lr *= self.factor
logging.info("Update[%d]: Change learning rate to %0.5e",
num_update, self.base_lr)
else:
return self.base_lr
return self.base_lr
| 38.626866 | 96 | 0.586553 |
c0a642f94fcfb05adb17c23b07306366a7a3f551 | 2,678 | py | Python | uvicore/auth/authenticators/base.py | coboyoshi/uvicore | 9cfdeeac83000b156fe48f068b4658edaf51c8de | [
"MIT"
] | null | null | null | uvicore/auth/authenticators/base.py | coboyoshi/uvicore | 9cfdeeac83000b156fe48f068b4658edaf51c8de | [
"MIT"
] | null | null | null | uvicore/auth/authenticators/base.py | coboyoshi/uvicore | 9cfdeeac83000b156fe48f068b4658edaf51c8de | [
"MIT"
] | null | null | null | import uvicore
from uvicore.support import module
from uvicore.support.dumper import dump, dd
from uvicore.http.request import HTTPConnection
from uvicore.contracts import UserInfo, UserProvider
from uvicore.typing import Dict, Optional, List, Tuple
from uvicore.contracts import Authenticator as AuthenticatorInterface
@uvicore.service()
class Authenticator(AuthenticatorInterface):
"""Base authenticator class"""
def __init__(self, config: Dict):
self.config = config
@property
def log(self):
return uvicore.log.name('uvicore.auth')
async def retrieve_user(self, username: str, password: str, provider: Dict, request: HTTPConnection, **kwargs) -> Optional[UserInfo]:
"""Retrieve user from User Provider backend"""
# Import user provider defined in auth config
user_provider: UserProvider = module.load(provider.module).object()
# Get user from user provider and validate password. User will be Anonymous
# if user not found, disabled or validation failed
user = await user_provider.retrieve_by_credentials(
# Require parameters
username=username,
password=password,
request=request,
# Pass in options from auth config
**provider.options,
# Pass in options from the calling authenticator
**kwargs,
)
# Do not throw error if no user or not validated here. We let the middleware handle that
return user
async def create_user(self, provider: Dict, request: HTTPConnection, **kwargs):
# Import user provider defined in auth config
user_provider: UserProvider = module.load(provider.module).object()
# Create user from user provider
# Returned user is actual backend user, NOT Auth User object
user = await user_provider.create_user(request, **kwargs)
return user
async def sync_user(self, provider: Dict, request: HTTPConnection, **kwargs):
# Import user provider defined in auth config
user_provider: UserProvider = module.load(provider.module).object()
# Create user from user provider
# Returned user is actual backend user, NOT Auth User object
user = await user_provider.sync_user(request, **kwargs)
return user
def auth_header(self, request) -> Tuple[str, str, str]:
"""Extract authorization header parts"""
authorization = request.headers.get('Authorization')
if not authorization: return (authorization, '', '')
scheme, _, param = authorization.partition(' ')
return authorization, scheme.lower(), param
| 38.811594 | 137 | 0.682599 |
e566b8659222e70ecab14b44a81f31b8d5799266 | 2,123 | py | Python | data/build.py | lbl123456/TMPcode | 2601653bd6fe3e26d65e48b82f41fd4f07026f2c | [
"BSD-2-Clause"
] | null | null | null | data/build.py | lbl123456/TMPcode | 2601653bd6fe3e26d65e48b82f41fd4f07026f2c | [
"BSD-2-Clause"
] | null | null | null | data/build.py | lbl123456/TMPcode | 2601653bd6fe3e26d65e48b82f41fd4f07026f2c | [
"BSD-2-Clause"
] | null | null | null | # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
from torch.utils.data import DataLoader
from .collate_batch import train_collate_fn, val_collate_fn
from .datasets import init_dataset, ImageDataset
from .samplers import RandomIdentitySampler, RandomIdentitySampler_alignedreid # New add by gu
from .transforms import build_transforms
class TwoCropTransform:
"""Create two crops of the same image"""
def __init__(self, transform):
self.transform = transform
def __call__(self, x):
return [self.transform(x), self.transform(x)]
def make_data_loader(cfg):
train_transforms = build_transforms(cfg, is_train=True)
val_transforms = build_transforms(cfg, is_train=False)
num_workers = cfg.DATALOADER.NUM_WORKERS
if len(cfg.DATASETS.NAMES) == 1:
dataset = init_dataset(cfg.DATASETS.NAMES, root=cfg.DATASETS.ROOT_DIR)
else:
# TODO: add multi dataset to train
dataset = init_dataset(cfg.DATASETS.NAMES, root=cfg.DATASETS.ROOT_DIR)
num_classes = dataset.num_train_pids
train_set = ImageDataset(dataset.train,train_transforms )#TwoCropTransform(train_transforms))
if cfg.DATALOADER.SAMPLER == 'softmax':
train_loader = DataLoader(
train_set, batch_size=cfg.SOLVER.IMS_PER_BATCH, shuffle=False, num_workers=num_workers,
#collate_fn=train_collate_fn
)
else:
train_loader = DataLoader(
train_set, batch_size=cfg.SOLVER.IMS_PER_BATCH,
sampler=RandomIdentitySampler(dataset.train, cfg.SOLVER.IMS_PER_BATCH, cfg.DATALOADER.NUM_INSTANCE),
# sampler=RandomIdentitySampler_alignedreid(dataset.train, cfg.DATALOADER.NUM_INSTANCE), # new add by gu
num_workers=num_workers, collate_fn=train_collate_fn
)
val_set = ImageDataset(dataset.query + dataset.gallery, val_transforms)
val_loader = DataLoader(
val_set, batch_size=cfg.TEST.IMS_PER_BATCH, shuffle=False, num_workers=num_workers,
collate_fn=val_collate_fn
)
return train_loader, val_loader, len(dataset.query), num_classes
| 40.826923 | 121 | 0.729628 |
7375f9fc55ee30b43cc1173f38b34b8fa3df6fc8 | 389 | py | Python | first_steps/cup.py | lowrybg/PythonOOP | 1ef5023ca76645d5d96b8c4fb9a54d0f431a1947 | [
"MIT"
] | null | null | null | first_steps/cup.py | lowrybg/PythonOOP | 1ef5023ca76645d5d96b8c4fb9a54d0f431a1947 | [
"MIT"
] | null | null | null | first_steps/cup.py | lowrybg/PythonOOP | 1ef5023ca76645d5d96b8c4fb9a54d0f431a1947 | [
"MIT"
] | null | null | null | class Cup:
def __init__(self, size: int, quantity: int):
self.size = size
self.quantity = quantity
def fill(self, amount: int):
if self.quantity + amount <= self.size:
self.quantity += amount
def status(self):
return self.size - self.quantity
cup = Cup(100, 50)
print(cup.status())
cup.fill(40)
cup.fill(20)
print(cup.status())
| 19.45 | 49 | 0.604113 |
326228677d9b718174cd9d8dc39f5a1e724ba838 | 7,150 | py | Python | tracer/atlas_loader.py | pbotros/TRACER | 269e17ca27fe0fb78c30484d8685d119caab5dbb | [
"MIT"
] | null | null | null | tracer/atlas_loader.py | pbotros/TRACER | 269e17ca27fe0fb78c30484d8685d119caab5dbb | [
"MIT"
] | null | null | null | tracer/atlas_loader.py | pbotros/TRACER | 269e17ca27fe0fb78c30484d8685d119caab5dbb | [
"MIT"
] | null | null | null | import os
import cv2
import nibabel as nib
import numpy as np
def readlabel(file):
"""
Purpose
-------------
Read the atlas label file.
Inputs
-------------
file :
Outputs
-------------
A list contains ...
"""
output_index = []
output_names = []
output_colors = []
output_initials = []
labels = file.readlines()
pure_labels = [x for x in labels if "#" not in x]
for line in pure_labels:
line_labels = line.split()
accessed_mapping = map(line_labels.__getitem__, [0])
L = list(accessed_mapping)
indice = [int(i) for i in L]
accessed_mapping_rgb = map(line_labels.__getitem__, [1, 2, 3])
L_rgb = list(accessed_mapping_rgb)
colorsRGB = [int(i) for i in L_rgb]
output_colors.append(colorsRGB)
output_index.append(indice)
output_names.append(' '.join(line_labels[7:]))
for i in range(len(output_names)):
output_names[i] = output_names[i][1:-1]
output_initials_t = []
for s in output_names[i].split():
output_initials_t.append(s[0])
output_initials.append(' '.join(output_initials_t))
output_index = np.array(output_index) # Use numpy array for in the label file
output_colors = np.array(output_colors) # Use numpy array for in the label file
return [output_index, output_names, output_colors, output_initials]
class AtlasLoader(object):
"""
Purpose
-------------
Load the Waxholm Rat Brain Atlas.
Inputs
-------------
atlas_folder : str, the path of the folder contains all the atlas related data files.
atlas_version : str, specify the version of atlas in use, default is version 3 ('v3').
Outputs
-------------
Atlas object.
"""
def __init__(self, atlas_folder, atlas_version='v4'):
if not os.path.exists(atlas_folder):
raise Exception('Folder path %s does not exist. Please give the correct path.' % atlas_folder)
atlas_data_masked_path = os.path.join(atlas_folder, 'atlas_data_masked.npz')
if os.path.exists(atlas_data_masked_path):
with np.load(atlas_data_masked_path) as temp_data:
self.atlas_data = temp_data['atlas_data']
self.pixdim = temp_data['pixdim']
self.mask_data = temp_data['mask_data']
else:
atlas_path = os.path.join(atlas_folder, 'WHS_SD_rat_T2star_v1.01.nii.gz')
mask_path = os.path.join(atlas_folder, 'WHS_SD_rat_brainmask_v1.01.nii.gz')
if not os.path.exists(atlas_path):
raise Exception('Atlas file %s does not exist. Please download the atlas data.' % atlas_path)
if not os.path.exists(mask_path):
raise Exception('Mask file %s does not exist. Please download the mask data.' % mask_path)
print(f'Precomputed mask {atlas_data_masked_path} not present; computing and caching on disk. This may take awhile...')
# Load Atlas
print('Loading atlas...')
atlas = nib.load(atlas_path)
atlas_header = atlas.header
self.pixdim = atlas_header.get('pixdim')[1]
self.atlas_data = atlas.get_fdata()
# Load Mask
print('Loading mask...')
mask = nib.load(mask_path)
self.mask_data = mask.get_fdata()[:, :, :, 0]
# Remove skull and tissues from atlas_data #
CC = np.where(self.mask_data == 0)
self.atlas_data[CC] = 0
print('Dumping to disk...')
np.savez_compressed(
atlas_data_masked_path,
atlas_data=self.atlas_data,
pixdim=self.pixdim,
mask_data=self.mask_data)
print('Done precomputing mask file.')
# check other path
segmentation_path = os.path.join(atlas_folder, 'WHS_SD_rat_atlas_%s.nii.gz' % atlas_version)
label_path = os.path.join(atlas_folder, 'WHS_SD_rat_atlas_%s.label' % atlas_version)
if not os.path.exists(segmentation_path):
raise Exception('Segmentation file %s does not exist. Please download the segmentation data.' % segmentation_path)
if not os.path.exists(label_path):
raise Exception('Label file %s does not exist. Please download the label data.' % label_path)
# Load Segmentation
segmentation = nib.load(segmentation_path)
self.segmentation_data = segmentation.get_fdata()
# Load Labels
with open(label_path, "r") as labels_item:
self.labels_index, self.labels_name, self.labels_color, self.labels_initial = readlabel(labels_item)
cv_plot_path = os.path.join(atlas_folder, 'cv_plot.npz')
edges_path = os.path.join(atlas_folder, 'Edges.npz')
cv_plot_disp_path = os.path.join(atlas_folder, 'cv_plot_display.npz')
if os.path.exists(cv_plot_path):
self.cv_plot = np.load(cv_plot_path)['cv_plot'] / 255
else:
print('Precomputing cv_plot...')
# Create an inverted map so we can index below quickly
labels_index_flat = np.zeros(np.max(self.labels_index.max()) + 1, dtype=np.int64)
labels_index_flat[self.labels_index.ravel()] = np.arange(self.labels_color.shape[0])
# Atlas in RGB colors according with the label file #
self.cv_plot = self.labels_color[labels_index_flat[self.segmentation_data.astype(np.int64).ravel()]].reshape(tuple(list(self.segmentation_data.shape) + [3]))
np.savez_compressed(cv_plot_path, cv_plot=self.cv_plot)
self.cv_plot = self.cv_plot / 255
if os.path.exists(edges_path):
self.Edges = np.load(edges_path)['Edges']
else:
print('Precomputing edges...')
# Get the edges of the colors defined in the label #
self.Edges = np.empty((512, 1024, 512))
for sl in range(0, 1024):
self.Edges[:, sl, :] = cv2.Canny(np.uint8((self.cv_plot[:, sl, :] * 255).transpose((1, 0, 2))), 100, 200)
np.savez_compressed(edges_path, Edges=self.Edges)
if os.path.exists(cv_plot_disp_path):
self.cv_plot_display = np.load(cv_plot_disp_path)['cv_plot_display']
else:
print('Precomputing cv_plot_disp...')
# Create an inverted map so we can index below quickly
labels_index_flat = np.zeros(np.max(self.labels_index.max()) + 1, dtype=np.int64)
labels_index_flat[self.labels_index.ravel()] = np.arange(self.labels_color.shape[0])
labels_color_augmented = self.labels_color.copy()
labels_color_augmented[0, :] = [128, 128, 128]
# here I create the array to plot the brain regions in the RGB
# of the label file
self.cv_plot_display = labels_color_augmented[labels_index_flat[self.segmentation_data.astype(np.int64).ravel()]].reshape(tuple(list(self.segmentation_data.shape) + [3]))
np.savez_compressed(cv_plot_disp_path, cv_plot_display=self.cv_plot_display)
| 39.502762 | 182 | 0.623357 |
10cd692317be324589abaff1df9fe37b36858228 | 1,015 | py | Python | tests/test_reuters_news.py | chakki-works/chazutsu | 811dedb19e3d670011da3679dc3befe4f1f2c41c | [
"Apache-2.0"
] | 250 | 2017-05-12T07:48:04.000Z | 2022-03-08T02:14:26.000Z | tests/test_reuters_news.py | chakki-works/chazutsu | 811dedb19e3d670011da3679dc3befe4f1f2c41c | [
"Apache-2.0"
] | 10 | 2017-05-26T09:14:59.000Z | 2021-11-15T21:31:20.000Z | tests/test_reuters_news.py | chakki-works/chazutsu | 811dedb19e3d670011da3679dc3befe4f1f2c41c | [
"Apache-2.0"
] | 28 | 2017-05-16T12:58:15.000Z | 2021-10-05T05:26:13.000Z | import os
import sys
import shutil
import unittest
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
import chazutsu.datasets
from tests.dataset_base_test import DatasetTestCase
class TestReutersNews(DatasetTestCase):
def test_topics(self):
r = chazutsu.datasets.ReutersNews(kind="topics").download(directory=self.test_dir, force=True)
self.assertTrue(len(r.data().columns), 3)
print(r.data().columns)
shutil.rmtree(r.root)
def test_industries(self):
r = chazutsu.datasets.ReutersNews().industries().download(directory=self.test_dir, force=True)
self.assertTrue(len(r.data().columns), 3)
print(r.data().columns)
shutil.rmtree(r.root)
def test_regions(self):
r = chazutsu.datasets.ReutersNews().regions().download(directory=self.test_dir, force=True)
self.assertTrue(len(r.data().columns), 2)
print(r.data().columns)
shutil.rmtree(r.root)
if __name__ == "__main__":
unittest.main()
| 29.852941 | 102 | 0.6867 |
27c48f44db34a98db0d35c51bb7992e234589057 | 2,631 | py | Python | examples/testing.py | edblancas/ploomber | f9cec77ba8e69cc13a238cf917914c1f19f37bd3 | [
"Apache-2.0"
] | null | null | null | examples/testing.py | edblancas/ploomber | f9cec77ba8e69cc13a238cf917914c1f19f37bd3 | [
"Apache-2.0"
] | null | null | null | examples/testing.py | edblancas/ploomber | f9cec77ba8e69cc13a238cf917914c1f19f37bd3 | [
"Apache-2.0"
] | null | null | null | """
Acceptance tests
================
Testing is crucial for any data pipeline. Raw data comes from sources where
developers have no control over. Raw data inconsistencies are a common source
for bugs in data pipelines (e.g. a unusual high proportion of NAs in certain
column), but to make progress, a developer must make assumptions about the
input data and such assumptions must be tested every time the pipeline runs
to prevent errors from propagating to downstream tasks. Let's rewrite our
previous pipeline to implement this defensive programming approach:
"""
from pathlib import Path
import tempfile
import pandas as pd
from sqlalchemy import create_engine
from ploomber import DAG
from ploomber.products import File
from ploomber.tasks import PythonCallable, SQLDump
from ploomber.clients import SQLAlchemyClient
###############################################################################
# Setup
tmp_dir = Path(tempfile.mkdtemp())
uri = 'sqlite:///' + str(tmp_dir / 'example.db')
engine = create_engine(uri)
df = pd.DataFrame({'a': [1, 2, 3, 4, 5]})
df.to_sql('example', engine)
###############################################################################
# Pipeline declaration
# ---------------------
dag = DAG()
# the first task dumps data from the db to the local filesystem
task_dump = SQLDump('SELECT * FROM example',
File(tmp_dir / 'example.csv'),
dag,
name='dump',
client=SQLAlchemyClient(uri),
chunksize=None)
# since this task will have an upstream dependency, it has to accept the
# upstream parameter, all tasks must accept a product parameter
def _add_one(upstream, product):
"""Add one to column a
"""
df = pd.read_csv(str(upstream['dump']))
df['a'] = df['a'] + 1
df.to_csv(str(product), index=False)
def check_a_has_no_nas(task):
df = pd.read_csv(str(task.product))
# this print is just here to show that the hook is executed
print('\n\nRunning on_finish hook: checking column has no NAs...\n\n')
assert not df.a.isna().sum()
task_add_one = PythonCallable(_add_one,
File(tmp_dir / 'add_one.csv'),
dag,
name='add_one')
task_add_one.on_finish = check_a_has_no_nas
task_dump >> task_add_one
###############################################################################
# Pipeline plot
# -------------
dag.plot(output='matplotlib')
###############################################################################
# Pipeline build
# -------------
dag.build()
| 31.321429 | 79 | 0.580768 |
589945c511ff83b1014df28cd0f69d03c4af97aa | 47,423 | py | Python | mesonbuild/linkers.py | monwarez/meson | 63814543de6f46fc8aee7d3884a8746c968806ca | [
"Apache-2.0"
] | 1 | 2020-10-22T05:33:27.000Z | 2020-10-22T05:33:27.000Z | mesonbuild/linkers.py | monwarez/meson | 63814543de6f46fc8aee7d3884a8746c968806ca | [
"Apache-2.0"
] | null | null | null | mesonbuild/linkers.py | monwarez/meson | 63814543de6f46fc8aee7d3884a8746c968806ca | [
"Apache-2.0"
] | 1 | 2020-12-07T15:37:35.000Z | 2020-12-07T15:37:35.000Z | # Copyright 2012-2017 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import abc
import os
import typing as T
from . import mesonlib
from .arglist import CompilerArgs
from .envconfig import get_env_var
if T.TYPE_CHECKING:
from .coredata import OptionDictType
from .envconfig import MachineChoice
from .environment import Environment
class StaticLinker:
def __init__(self, exelist: T.List[str]):
self.exelist = exelist
def compiler_args(self, args: T.Optional[T.Iterable[str]] = None) -> CompilerArgs:
return CompilerArgs(self, args)
def can_linker_accept_rsp(self) -> bool:
"""
Determines whether the linker can accept arguments using the @rsp syntax.
"""
return mesonlib.is_windows()
def get_base_link_args(self, options: 'OptionDictType') -> T.List[str]:
"""Like compilers.get_base_link_args, but for the static linker."""
return []
def get_exelist(self) -> T.List[str]:
return self.exelist.copy()
def get_std_link_args(self) -> T.List[str]:
return []
def get_buildtype_linker_args(self, buildtype: str) -> T.List[str]:
return []
def get_output_args(self, target: str) -> T.List[str]:
return[]
def get_coverage_link_args(self) -> T.List[str]:
return []
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str,
rpath_paths: str, build_rpath: str,
install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]:
return ([], set())
def thread_link_flags(self, env: 'Environment') -> T.List[str]:
return []
def openmp_flags(self) -> T.List[str]:
return []
def get_option_link_args(self, options: 'OptionDictType') -> T.List[str]:
return []
@classmethod
def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]:
return args[:]
@classmethod
def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]:
return args[:]
def get_link_debugfile_name(self, targetfile: str) -> str:
return None
def get_link_debugfile_args(self, targetfile: str) -> T.List[str]:
# Static libraries do not have PDB files
return []
def get_always_args(self) -> T.List[str]:
return []
def get_linker_always_args(self) -> T.List[str]:
return []
class VisualStudioLikeLinker:
always_args = ['/NOLOGO']
def __init__(self, machine: str):
self.machine = machine
def get_always_args(self) -> T.List[str]:
return self.always_args.copy()
def get_linker_always_args(self) -> T.List[str]:
return self.always_args.copy()
def get_output_args(self, target: str) -> T.List[str]:
args = [] # type: T.List[str]
if self.machine:
args += ['/MACHINE:' + self.machine]
args += ['/OUT:' + target]
return args
@classmethod
def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]:
from .compilers import VisualStudioCCompiler
return VisualStudioCCompiler.unix_args_to_native(args)
@classmethod
def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]:
from .compilers import VisualStudioCCompiler
return VisualStudioCCompiler.native_args_to_unix(args)
class VisualStudioLinker(VisualStudioLikeLinker, StaticLinker):
"""Microsoft's lib static linker."""
def __init__(self, exelist: T.List[str], machine: str):
StaticLinker.__init__(self, exelist)
VisualStudioLikeLinker.__init__(self, machine)
class IntelVisualStudioLinker(VisualStudioLikeLinker, StaticLinker):
"""Intel's xilib static linker."""
def __init__(self, exelist: T.List[str], machine: str):
StaticLinker.__init__(self, exelist)
VisualStudioLikeLinker.__init__(self, machine)
class ArLinker(StaticLinker):
def __init__(self, exelist: T.List[str]):
super().__init__(exelist)
self.id = 'ar'
pc, stdo = mesonlib.Popen_safe(self.exelist + ['-h'])[0:2]
# Enable deterministic builds if they are available.
if '[D]' in stdo:
self.std_args = ['csrD']
else:
self.std_args = ['csr']
self.can_rsp = '@<' in stdo
def can_linker_accept_rsp(self) -> bool:
return self.can_rsp
def get_std_link_args(self) -> T.List[str]:
return self.std_args
def get_output_args(self, target: str) -> T.List[str]:
return [target]
class ArmarLinker(ArLinker): # lgtm [py/missing-call-to-init]
def __init__(self, exelist: T.List[str]):
StaticLinker.__init__(self, exelist)
self.id = 'armar'
self.std_args = ['-csr']
def can_linker_accept_rsp(self) -> bool:
# armar can't accept arguments using the @rsp syntax
return False
class DLinker(StaticLinker):
def __init__(self, exelist: T.List[str], arch: str):
super().__init__(exelist)
self.id = exelist[0]
self.arch = arch
def get_std_link_args(self) -> T.List[str]:
return ['-lib']
def get_output_args(self, target: str) -> T.List[str]:
return ['-of=' + target]
def get_linker_always_args(self) -> T.List[str]:
if mesonlib.is_windows():
if self.arch == 'x86_64':
return ['-m64']
elif self.arch == 'x86_mscoff' and self.id == 'dmd':
return ['-m32mscoff']
return ['-m32']
return []
class CcrxLinker(StaticLinker):
def __init__(self, exelist: T.List[str]):
super().__init__(exelist)
self.id = 'rlink'
def can_linker_accept_rsp(self) -> bool:
return False
def get_output_args(self, target: str) -> T.List[str]:
return ['-output={}'.format(target)]
def get_linker_always_args(self) -> T.List[str]:
return ['-nologo', '-form=library']
class Xc16Linker(StaticLinker):
def __init__(self, exelist: T.List[str]):
super().__init__(exelist)
self.id = 'xc16-ar'
def can_linker_accept_rsp(self) -> bool:
return False
def get_output_args(self, target: str) -> T.List[str]:
return ['{}'.format(target)]
def get_linker_always_args(self) -> T.List[str]:
return ['rcs']
class CompCertLinker(StaticLinker):
def __init__(self, exelist: T.List[str]):
super().__init__(exelist)
self.id = 'ccomp'
def can_linker_accept_rsp(self) -> bool:
return False
def get_output_args(self, target: str) -> T.List[str]:
return ['-o{}'.format(target)]
class C2000Linker(StaticLinker):
def __init__(self, exelist: T.List[str]):
super().__init__(exelist)
self.id = 'ar2000'
def can_linker_accept_rsp(self) -> bool:
return False
def get_output_args(self, target: str) -> T.List[str]:
return ['{}'.format(target)]
def get_linker_always_args(self) -> T.List[str]:
return ['-r']
class AIXArLinker(ArLinker):
def __init__(self, exelist: T.List[str]):
StaticLinker.__init__(self, exelist)
self.id = 'aixar'
self.std_args = ['-csr', '-Xany']
def can_linker_accept_rsp(self) -> bool:
# AIXAr can't accept arguments using the @rsp syntax
return False
def prepare_rpaths(raw_rpaths: str, build_dir: str, from_dir: str) -> T.List[str]:
# The rpaths we write must be relative if they point to the build dir,
# because otherwise they have different length depending on the build
# directory. This breaks reproducible builds.
internal_format_rpaths = [evaluate_rpath(p, build_dir, from_dir) for p in raw_rpaths]
ordered_rpaths = order_rpaths(internal_format_rpaths)
return ordered_rpaths
def order_rpaths(rpath_list: T.List[str]) -> T.List[str]:
# We want rpaths that point inside our build dir to always override
# those pointing to other places in the file system. This is so built
# binaries prefer our libraries to the ones that may lie somewhere
# in the file system, such as /lib/x86_64-linux-gnu.
#
# The correct thing to do here would be C++'s std::stable_partition.
# Python standard library does not have it, so replicate it with
# sort, which is guaranteed to be stable.
return sorted(rpath_list, key=os.path.isabs)
def evaluate_rpath(p: str, build_dir: str, from_dir: str) -> str:
if p == from_dir:
return '' # relpath errors out in this case
elif os.path.isabs(p):
return p # These can be outside of build dir.
else:
return os.path.relpath(os.path.join(build_dir, p), os.path.join(build_dir, from_dir))
class LinkerEnvVarsMixin(metaclass=abc.ABCMeta):
"""Mixin reading LDFLAGS from the environment."""
@staticmethod
def get_args_from_envvars(for_machine: mesonlib.MachineChoice,
is_cross: bool) -> T.List[str]:
raw_value = get_env_var(for_machine, is_cross, 'LDFLAGS')
if raw_value is not None:
return mesonlib.split_args(raw_value)
else:
return []
class DynamicLinker(LinkerEnvVarsMixin, metaclass=abc.ABCMeta):
"""Base class for dynamic linkers."""
_BUILDTYPE_ARGS = {
'plain': [],
'debug': [],
'debugoptimized': [],
'release': [],
'minsize': [],
'custom': [],
} # type: T.Dict[str, T.List[str]]
@abc.abstractproperty
def id(self) -> str:
pass
def _apply_prefix(self, arg: T.Union[str, T.List[str]]) -> T.List[str]:
args = [arg] if isinstance(arg, str) else arg
if self.prefix_arg is None:
return args
elif isinstance(self.prefix_arg, str):
return [self.prefix_arg + arg for arg in args]
ret = []
for arg in args:
ret += self.prefix_arg + [arg]
return ret
def __init__(self, exelist: T.List[str],
for_machine: mesonlib.MachineChoice, prefix_arg: T.Union[str, T.List[str]],
always_args: T.List[str], *, version: str = 'unknown version'):
self.exelist = exelist
self.for_machine = for_machine
self.version = version
self.prefix_arg = prefix_arg
self.always_args = always_args
self.machine = None # type: T.Optional[str]
def __repr__(self) -> str:
return '<{}: v{} `{}`>'.format(type(self).__name__, self.version, ' '.join(self.exelist))
def get_id(self) -> str:
return self.id
def get_version_string(self) -> str:
return '({} {})'.format(self.id, self.version)
def get_exelist(self) -> T.List[str]:
return self.exelist.copy()
def get_accepts_rsp(self) -> bool:
# rsp files are only used when building on Windows because we want to
# avoid issues with quoting and max argument length
return mesonlib.is_windows()
def get_always_args(self) -> T.List[str]:
return self.always_args.copy()
def get_lib_prefix(self) -> str:
return ''
# XXX: is use_ldflags a compiler or a linker attribute?
def get_option_args(self, options: 'OptionDictType') -> T.List[str]:
return []
def has_multi_arguments(self, args: T.List[str], env: 'Environment') -> T.Tuple[bool, bool]:
m = 'Language {} does not support has_multi_link_arguments.'
raise mesonlib.EnvironmentException(m.format(self.id))
def get_debugfile_name(self, targetfile: str) -> str:
'''Name of debug file written out (see below)'''
return None
def get_debugfile_args(self, targetfile: str) -> T.List[str]:
"""Some compilers (MSVC) write debug into a separate file.
This method takes the target object path and returns a list of
commands to append to the linker invocation to control where that
file is written.
"""
return []
def get_std_shared_lib_args(self) -> T.List[str]:
return []
def get_std_shared_module_args(self, options: 'OptionDictType') -> T.List[str]:
return self.get_std_shared_lib_args()
def get_pie_args(self) -> T.List[str]:
# TODO: this really needs to take a boolean and return the args to
# disable pie, otherwise it only acts to enable pie if pie *isn't* the
# default.
m = 'Linker {} does not support position-independent executable'
raise mesonlib.EnvironmentException(m.format(self.id))
def get_lto_args(self) -> T.List[str]:
return []
def sanitizer_args(self, value: str) -> T.List[str]:
return []
def get_buildtype_args(self, buildtype: str) -> T.List[str]:
# We can override these in children by just overriding the
# _BUILDTYPE_ARGS value.
return self._BUILDTYPE_ARGS[buildtype]
def get_asneeded_args(self) -> T.List[str]:
return []
def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
raise mesonlib.EnvironmentException(
'Linker {} does not support link_whole'.format(self.id))
def get_allow_undefined_args(self) -> T.List[str]:
raise mesonlib.EnvironmentException(
'Linker {} does not support allow undefined'.format(self.id))
@abc.abstractmethod
def get_output_args(self, outname: str) -> T.List[str]:
pass
def get_coverage_args(self) -> T.List[str]:
m = "Linker {} doesn't implement coverage data generation.".format(self.id)
raise mesonlib.EnvironmentException(m)
@abc.abstractmethod
def get_search_args(self, dirname: str) -> T.List[str]:
pass
def export_dynamic_args(self, env: 'Environment') -> T.List[str]:
return []
def import_library_args(self, implibname: str) -> T.List[str]:
"""The name of the outputted import library.
This implementation is used only on Windows by compilers that use GNU ld
"""
return []
def thread_flags(self, env: 'Environment') -> T.List[str]:
return []
def no_undefined_args(self) -> T.List[str]:
"""Arguments to error if there are any undefined symbols at link time.
This is the inverse of get_allow_undefined_args().
TODO: A future cleanup might merge this and
get_allow_undefined_args() into a single method taking a
boolean
"""
return []
def fatal_warnings(self) -> T.List[str]:
"""Arguments to make all warnings errors."""
return []
def headerpad_args(self) -> T.List[str]:
# Only used by the Apple linker
return []
def bitcode_args(self) -> T.List[str]:
raise mesonlib.MesonException('This linker does not support bitcode bundles')
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str,
rpath_paths: str, build_rpath: str,
install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]:
return ([], set())
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
return []
class PosixDynamicLinkerMixin:
"""Mixin class for POSIX-ish linkers.
This is obviously a pretty small subset of the linker interface, but
enough dynamic linkers that meson supports are POSIX-like but not
GNU-like that it makes sense to split this out.
"""
def get_output_args(self, outname: str) -> T.List[str]:
return ['-o', outname]
def get_std_shared_lib_args(self) -> T.List[str]:
return ['-shared']
def get_search_args(self, dirname: str) -> T.List[str]:
return ['-L' + dirname]
class GnuLikeDynamicLinkerMixin:
"""Mixin class for dynamic linkers that provides gnu-like interface.
This acts as a base for the GNU linkers (bfd and gold), LLVM's lld, and
other linkers like GNU-ld.
"""
if T.TYPE_CHECKING:
for_machine = MachineChoice.HOST
def _apply_prefix(self, arg: T.Union[str, T.List[str]]) -> T.List[str]: ...
_BUILDTYPE_ARGS = {
'plain': [],
'debug': [],
'debugoptimized': [],
'release': ['-O1'],
'minsize': [],
'custom': [],
} # type: T.Dict[str, T.List[str]]
def get_buildtype_args(self, buildtype: str) -> T.List[str]:
# We can override these in children by just overriding the
# _BUILDTYPE_ARGS value.
return mesonlib.listify([self._apply_prefix(a) for a in self._BUILDTYPE_ARGS[buildtype]])
def get_pie_args(self) -> T.List[str]:
return ['-pie']
def get_asneeded_args(self) -> T.List[str]:
return self._apply_prefix('--as-needed')
def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
if not args:
return args
return self._apply_prefix('--whole-archive') + args + self._apply_prefix('--no-whole-archive')
def get_allow_undefined_args(self) -> T.List[str]:
return self._apply_prefix('--allow-shlib-undefined')
def get_lto_args(self) -> T.List[str]:
return ['-flto']
def sanitizer_args(self, value: str) -> T.List[str]:
if value == 'none':
return []
return ['-fsanitize=' + value]
def get_coverage_args(self) -> T.List[str]:
return ['--coverage']
def export_dynamic_args(self, env: 'Environment') -> T.List[str]:
m = env.machines[self.for_machine]
if m.is_windows() or m.is_cygwin():
return self._apply_prefix('--export-all-symbols')
return self._apply_prefix('-export-dynamic')
def import_library_args(self, implibname: str) -> T.List[str]:
return self._apply_prefix('--out-implib=' + implibname)
def thread_flags(self, env: 'Environment') -> T.List[str]:
if env.machines[self.for_machine].is_haiku():
return []
return ['-pthread']
def no_undefined_args(self) -> T.List[str]:
return self._apply_prefix('--no-undefined')
def fatal_warnings(self) -> T.List[str]:
return self._apply_prefix('--fatal-warnings')
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
m = env.machines[self.for_machine]
if m.is_windows() or m.is_cygwin():
# For PE/COFF the soname argument has no effect
return []
sostr = '' if soversion is None else '.' + soversion
return self._apply_prefix('-soname,{}{}.{}{}'.format(prefix, shlib_name, suffix, sostr))
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str,
rpath_paths: str, build_rpath: str,
install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]:
m = env.machines[self.for_machine]
if m.is_windows() or m.is_cygwin():
return ([], set())
if not rpath_paths and not install_rpath and not build_rpath:
return ([], set())
args = []
origin_placeholder = '$ORIGIN'
processed_rpaths = prepare_rpaths(rpath_paths, build_dir, from_dir)
# Need to deduplicate rpaths, as macOS's install_name_tool
# is *very* allergic to duplicate -delete_rpath arguments
# when calling depfixer on installation.
all_paths = mesonlib.OrderedSet([os.path.join(origin_placeholder, p) for p in processed_rpaths])
rpath_dirs_to_remove = set()
for p in all_paths:
rpath_dirs_to_remove.add(p.encode('utf8'))
# Build_rpath is used as-is (it is usually absolute).
if build_rpath != '':
all_paths.add(build_rpath)
for p in build_rpath.split(':'):
rpath_dirs_to_remove.add(p.encode('utf8'))
# TODO: should this actually be "for (dragonfly|open)bsd"?
if mesonlib.is_dragonflybsd() or mesonlib.is_openbsd():
# This argument instructs the compiler to record the value of
# ORIGIN in the .dynamic section of the elf. On Linux this is done
# by default, but is not on dragonfly/openbsd for some reason. Without this
# $ORIGIN in the runtime path will be undefined and any binaries
# linked against local libraries will fail to resolve them.
args.extend(self._apply_prefix('-z,origin'))
# In order to avoid relinking for RPATH removal, the binary needs to contain just
# enough space in the ELF header to hold the final installation RPATH.
paths = ':'.join(all_paths)
if len(paths) < len(install_rpath):
padding = 'X' * (len(install_rpath) - len(paths))
if not paths:
paths = padding
else:
paths = paths + ':' + padding
args.extend(self._apply_prefix('-rpath,' + paths))
# TODO: should this actually be "for solaris/sunos"?
if mesonlib.is_sunos():
return (args, rpath_dirs_to_remove)
# Rpaths to use while linking must be absolute. These are not
# written to the binary. Needed only with GNU ld:
# https://sourceware.org/bugzilla/show_bug.cgi?id=16936
# Not needed on Windows or other platforms that don't use RPATH
# https://github.com/mesonbuild/meson/issues/1897
#
# In addition, this linker option tends to be quite long and some
# compilers have trouble dealing with it. That's why we will include
# one option per folder, like this:
#
# -Wl,-rpath-link,/path/to/folder1 -Wl,-rpath,/path/to/folder2 ...
#
# ...instead of just one single looooong option, like this:
#
# -Wl,-rpath-link,/path/to/folder1:/path/to/folder2:...
for p in rpath_paths:
args.extend(self._apply_prefix('-rpath-link,' + os.path.join(build_dir, p)))
return (args, rpath_dirs_to_remove)
class AppleDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
"""Apple's ld implementation."""
id = 'ld64'
def get_asneeded_args(self) -> T.List[str]:
return self._apply_prefix('-dead_strip_dylibs')
def get_allow_undefined_args(self) -> T.List[str]:
return self._apply_prefix('-undefined,dynamic_lookup')
def get_std_shared_module_args(self, options: 'OptionDictType') -> T.List[str]:
return ['-bundle'] + self._apply_prefix('-undefined,dynamic_lookup')
def get_pie_args(self) -> T.List[str]:
return []
def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
result = [] # type: T.List[str]
for a in args:
result.extend(self._apply_prefix('-force_load'))
result.append(a)
return result
def get_coverage_args(self) -> T.List[str]:
return ['--coverage']
def sanitizer_args(self, value: str) -> T.List[str]:
if value == 'none':
return []
return ['-fsanitize=' + value]
def no_undefined_args(self) -> T.List[str]:
return self._apply_prefix('-undefined,error')
def headerpad_args(self) -> T.List[str]:
return self._apply_prefix('-headerpad_max_install_names')
def bitcode_args(self) -> T.List[str]:
return self._apply_prefix('-bitcode_bundle')
def fatal_warnings(self) -> T.List[str]:
return self._apply_prefix('-fatal_warnings')
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
if is_shared_module:
return []
install_name = ['@rpath/', prefix, shlib_name]
if soversion is not None:
install_name.append('.' + soversion)
install_name.append('.dylib')
args = ['-install_name', ''.join(install_name)]
if darwin_versions:
args.extend(['-compatibility_version', darwin_versions[0],
'-current_version', darwin_versions[1]])
return args
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str,
rpath_paths: str, build_rpath: str,
install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]:
if not rpath_paths and not install_rpath and not build_rpath:
return ([], set())
args = []
# @loader_path is the equivalent of $ORIGIN on macOS
# https://stackoverflow.com/q/26280738
origin_placeholder = '@loader_path'
processed_rpaths = prepare_rpaths(rpath_paths, build_dir, from_dir)
all_paths = mesonlib.OrderedSet([os.path.join(origin_placeholder, p) for p in processed_rpaths])
if build_rpath != '':
all_paths.add(build_rpath)
for rp in all_paths:
args.extend(self._apply_prefix('-rpath,' + rp))
return (args, set())
class GnuDynamicLinker(GnuLikeDynamicLinkerMixin, PosixDynamicLinkerMixin, DynamicLinker):
"""Representation of GNU ld.bfd and ld.gold."""
def get_accepts_rsp(self) -> bool:
return True
class GnuGoldDynamicLinker(GnuDynamicLinker):
id = 'ld.gold'
class GnuBFDDynamicLinker(GnuDynamicLinker):
id = 'ld.bfd'
class LLVMDynamicLinker(GnuLikeDynamicLinkerMixin, PosixDynamicLinkerMixin, DynamicLinker):
"""Representation of LLVM's ld.lld linker.
This is only the gnu-like linker, not the apple like or link.exe like
linkers.
"""
id = 'ld.lld'
def __init__(self, exelist: T.List[str],
for_machine: mesonlib.MachineChoice, prefix_arg: T.Union[str, T.List[str]],
always_args: T.List[str], *, version: str = 'unknown version'):
super().__init__(exelist, for_machine, prefix_arg, always_args, version=version)
# Some targets don't seem to support this argument (windows, wasm, ...)
_, _, e = mesonlib.Popen_safe(self.exelist + self._apply_prefix('--allow-shlib-undefined'))
self.has_allow_shlib_undefined = not ('unknown argument: --allow-shlib-undefined' in e)
def get_allow_undefined_args(self) -> T.List[str]:
if self.has_allow_shlib_undefined:
return self._apply_prefix('--allow-shlib-undefined')
return []
class WASMDynamicLinker(GnuLikeDynamicLinkerMixin, PosixDynamicLinkerMixin, DynamicLinker):
"""Emscripten's wasm-ld."""
id = 'ld.wasm'
def get_allow_undefined_args(self) -> T.List[str]:
return ['-s', 'ERROR_ON_UNDEFINED_SYMBOLS=0']
def no_undefined_args(self) -> T.List[str]:
return ['-s', 'ERROR_ON_UNDEFINED_SYMBOLS=1']
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
raise mesonlib.MesonException('{} does not support shared libraries.'.format(self.id))
def get_asneeded_args(self) -> T.List[str]:
return []
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str,
rpath_paths: str, build_rpath: str,
install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]:
return ([], set())
class CcrxDynamicLinker(DynamicLinker):
"""Linker for Renesis CCrx compiler."""
id = 'rlink'
def __init__(self, for_machine: mesonlib.MachineChoice,
*, version: str = 'unknown version'):
super().__init__(['rlink.exe'], for_machine, '', [],
version=version)
def get_accepts_rsp(self) -> bool:
return False
def get_lib_prefix(self) -> str:
return '-lib='
def get_std_shared_lib_args(self) -> T.List[str]:
return []
def get_output_args(self, outputname: str) -> T.List[str]:
return ['-output={}'.format(outputname)]
def get_search_args(self, dirname: str) -> 'T.NoReturn':
raise EnvironmentError('rlink.exe does not have a search dir argument')
def get_allow_undefined_args(self) -> T.List[str]:
return []
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
return []
class Xc16DynamicLinker(DynamicLinker):
"""Linker for Microchip XC16 compiler."""
id = 'xc16-gcc'
def __init__(self, for_machine: mesonlib.MachineChoice,
*, version: str = 'unknown version'):
super().__init__(['xc16-gcc.exe'], for_machine, '', [],
version=version)
def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
if not args:
return args
return self._apply_prefix('--start-group') + args + self._apply_prefix('--end-group')
def get_accepts_rsp(self) -> bool:
return False
def get_lib_prefix(self) -> str:
return ''
def get_std_shared_lib_args(self) -> T.List[str]:
return []
def get_output_args(self, outputname: str) -> T.List[str]:
return ['-o{}'.format(outputname)]
def get_search_args(self, dirname: str) -> 'T.NoReturn':
raise EnvironmentError('xc16-gcc.exe does not have a search dir argument')
def get_allow_undefined_args(self) -> T.List[str]:
return []
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
return []
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str,
rpath_paths: str, build_rpath: str,
install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]:
return ([], set())
class CompCertDynamicLinker(DynamicLinker):
"""Linker for CompCert C compiler."""
id = 'ccomp'
def __init__(self, for_machine: mesonlib.MachineChoice,
*, version: str = 'unknown version'):
super().__init__(['ccomp'], for_machine, '', [],
version=version)
def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
if not args:
return args
return self._apply_prefix('-Wl,--whole-archive') + args + self._apply_prefix('-Wl,--no-whole-archive')
def get_accepts_rsp(self) -> bool:
return False
def get_lib_prefix(self) -> str:
return ''
def get_std_shared_lib_args(self) -> T.List[str]:
return []
def get_output_args(self, outputname: str) -> T.List[str]:
return ['-o{}'.format(outputname)]
def get_search_args(self, dirname: str) -> T.List[str]:
return ['-L{}'.format(dirname)]
def get_allow_undefined_args(self) -> T.List[str]:
return []
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
raise mesonlib.MesonException('{} does not support shared libraries.'.format(self.id))
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str,
rpath_paths: str, build_rpath: str,
install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]:
return ([], set())
class C2000DynamicLinker(DynamicLinker):
"""Linker for Texas Instruments C2000 compiler."""
id = 'cl2000'
def __init__(self, for_machine: mesonlib.MachineChoice,
*, version: str = 'unknown version'):
super().__init__(['cl2000.exe'], for_machine, '', [],
version=version)
def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
if not args:
return args
return self._apply_prefix('--start-group') + args + self._apply_prefix('--end-group')
def get_accepts_rsp(self) -> bool:
return False
def get_lib_prefix(self) -> str:
return '-l='
def get_std_shared_lib_args(self) -> T.List[str]:
return []
def get_output_args(self, outputname: str) -> T.List[str]:
return ['-z', '--output_file={}'.format(outputname)]
def get_search_args(self, dirname: str) -> 'T.NoReturn':
raise EnvironmentError('cl2000.exe does not have a search dir argument')
def get_allow_undefined_args(self) -> T.List[str]:
return []
def get_always_args(self) -> T.List[str]:
return []
class ArmDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
"""Linker for the ARM compiler."""
id = 'armlink'
def __init__(self, for_machine: mesonlib.MachineChoice,
*, version: str = 'unknown version'):
super().__init__(['armlink'], for_machine, '', [],
version=version)
def get_accepts_rsp(self) -> bool:
return False
def get_std_shared_lib_args(self) -> 'T.NoReturn':
raise mesonlib.MesonException('The Arm Linkers do not support shared libraries')
def get_allow_undefined_args(self) -> T.List[str]:
return []
class ArmClangDynamicLinker(ArmDynamicLinker):
"""Linker used with ARM's clang fork.
The interface is similar enough to the old ARM ld that it inherits and
extends a few things as needed.
"""
def export_dynamic_args(self, env: 'Environment') -> T.List[str]:
return ['--export_dynamic']
def import_library_args(self, implibname: str) -> T.List[str]:
return ['--symdefs=' + implibname]
class QualcommLLVMDynamicLinker(LLVMDynamicLinker):
"""ARM Linker from Snapdragon LLVM ARM Compiler."""
id = 'ld.qcld'
class PGIDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
"""PGI linker."""
id = 'pgi'
def get_allow_undefined_args(self) -> T.List[str]:
return []
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
return []
def get_std_shared_lib_args(self) -> T.List[str]:
# PGI -shared is Linux only.
if mesonlib.is_windows():
return ['-Bdynamic', '-Mmakedll']
elif mesonlib.is_linux():
return ['-shared']
return []
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str,
rpath_paths: str, build_rpath: str,
install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]:
if not env.machines[self.for_machine].is_windows():
return (['-R' + os.path.join(build_dir, p) for p in rpath_paths], set())
return ([], set())
NvidiaHPC_DynamicLinker = PGIDynamicLinker
class PGIStaticLinker(StaticLinker):
def __init__(self, exelist: T.List[str]):
super().__init__(exelist)
self.id = 'ar'
self.std_args = ['-r']
def get_std_link_args(self) -> T.List[str]:
return self.std_args
def get_output_args(self, target: str) -> T.List[str]:
return [target]
NvidiaHPC_StaticLinker = PGIStaticLinker
class VisualStudioLikeLinkerMixin:
"""Mixin class for for dynamic linkers that act like Microsoft's link.exe."""
if T.TYPE_CHECKING:
for_machine = MachineChoice.HOST
def _apply_prefix(self, arg: T.Union[str, T.List[str]]) -> T.List[str]: ...
_BUILDTYPE_ARGS = {
'plain': [],
'debug': [],
'debugoptimized': [],
# The otherwise implicit REF and ICF linker optimisations are disabled by
# /DEBUG. REF implies ICF.
'release': ['/OPT:REF'],
'minsize': ['/INCREMENTAL:NO', '/OPT:REF'],
'custom': [],
} # type: T.Dict[str, T.List[str]]
def __init__(self, exelist: T.List[str], for_machine: mesonlib.MachineChoice,
prefix_arg: T.Union[str, T.List[str]], always_args: T.List[str], *,
version: str = 'unknown version', direct: bool = True, machine: str = 'x86'):
# There's no way I can find to make mypy understand what's going on here
super().__init__(exelist, for_machine, prefix_arg, always_args, version=version) # type: ignore
self.machine = machine
self.direct = direct
def get_buildtype_args(self, buildtype: str) -> T.List[str]:
return mesonlib.listify([self._apply_prefix(a) for a in self._BUILDTYPE_ARGS[buildtype]])
def invoked_by_compiler(self) -> bool:
return not self.direct
def get_output_args(self, outputname: str) -> T.List[str]:
return self._apply_prefix(['/MACHINE:' + self.machine, '/OUT:' + outputname])
def get_always_args(self) -> T.List[str]:
parent = super().get_always_args() # type: ignore
return self._apply_prefix('/nologo') + T.cast(T.List[str], parent)
def get_search_args(self, dirname: str) -> T.List[str]:
return self._apply_prefix('/LIBPATH:' + dirname)
def get_std_shared_lib_args(self) -> T.List[str]:
return self._apply_prefix('/DLL')
def get_debugfile_name(self, targetfile: str) -> str:
basename = targetfile.rsplit('.', maxsplit=1)[0]
return basename + '.pdb'
def get_debugfile_args(self, targetfile: str) -> T.List[str]:
return self._apply_prefix(['/DEBUG', '/PDB:' + self.get_debugfile_name(targetfile)])
def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
# Only since VS2015
args = mesonlib.listify(args)
l = [] # T.List[str]
for a in args:
l.extend(self._apply_prefix('/WHOLEARCHIVE:' + a))
return l
def get_allow_undefined_args(self) -> T.List[str]:
return []
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
return []
def import_library_args(self, implibname: str) -> T.List[str]:
"""The command to generate the import library."""
return self._apply_prefix(['/IMPLIB:' + implibname])
class MSVCDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker):
"""Microsoft's Link.exe."""
id = 'link'
def __init__(self, for_machine: mesonlib.MachineChoice, always_args: T.List[str], *,
exelist: T.Optional[T.List[str]] = None,
prefix: T.Union[str, T.List[str]] = '',
machine: str = 'x86', version: str = 'unknown version',
direct: bool = True):
super().__init__(exelist or ['link.exe'], for_machine,
prefix, always_args, machine=machine, version=version, direct=direct)
def get_always_args(self) -> T.List[str]:
return self._apply_prefix(['/nologo', '/release']) + super().get_always_args()
class ClangClDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker):
"""Clang's lld-link.exe."""
id = 'lld-link'
def __init__(self, for_machine: mesonlib.MachineChoice, always_args: T.List[str], *,
exelist: T.Optional[T.List[str]] = None,
prefix: T.Union[str, T.List[str]] = '',
machine: str = 'x86', version: str = 'unknown version',
direct: bool = True):
super().__init__(exelist or ['lld-link.exe'], for_machine,
prefix, always_args, machine=machine, version=version, direct=direct)
class XilinkDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker):
"""Intel's Xilink.exe."""
id = 'xilink'
def __init__(self, for_machine: mesonlib.MachineChoice, always_args: T.List[str], *,
exelist: T.Optional[T.List[str]] = None,
prefix: T.Union[str, T.List[str]] = '',
machine: str = 'x86', version: str = 'unknown version',
direct: bool = True):
super().__init__(['xilink.exe'], for_machine, '', always_args, version=version)
class SolarisDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
"""Sys-V derived linker used on Solaris and OpenSolaris."""
id = 'ld.solaris'
def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
if not args:
return args
return self._apply_prefix('--whole-archive') + args + self._apply_prefix('--no-whole-archive')
def get_pie_args(self) -> T.List[str]:
# Available in Solaris 11.2 and later
pc, stdo, stde = mesonlib.Popen_safe(self.exelist + self._apply_prefix('-zhelp'))
for line in (stdo + stde).split('\n'):
if '-z type' in line:
if 'pie' in line:
return ['-z', 'type=pie']
break
return []
def get_asneeded_args(self) -> T.List[str]:
return self._apply_prefix(['-z', 'ignore'])
def no_undefined_args(self) -> T.List[str]:
return ['-z', 'defs']
def get_allow_undefined_args(self) -> T.List[str]:
return ['-z', 'nodefs']
def fatal_warnings(self) -> T.List[str]:
return ['-z', 'fatal-warnings']
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str,
rpath_paths: str, build_rpath: str,
install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]:
if not rpath_paths and not install_rpath and not build_rpath:
return ([], set())
processed_rpaths = prepare_rpaths(rpath_paths, build_dir, from_dir)
all_paths = mesonlib.OrderedSet([os.path.join('$ORIGIN', p) for p in processed_rpaths])
if build_rpath != '':
all_paths.add(build_rpath)
# In order to avoid relinking for RPATH removal, the binary needs to contain just
# enough space in the ELF header to hold the final installation RPATH.
paths = ':'.join(all_paths)
if len(paths) < len(install_rpath):
padding = 'X' * (len(install_rpath) - len(paths))
if not paths:
paths = padding
else:
paths = paths + ':' + padding
return (self._apply_prefix('-rpath,{}'.format(paths)), set())
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
sostr = '' if soversion is None else '.' + soversion
return self._apply_prefix('-soname,{}{}.{}{}'.format(prefix, shlib_name, suffix, sostr))
class AIXDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
"""Sys-V derived linker used on AIX"""
id = 'ld.aix'
def get_always_args(self) -> T.List[str]:
return self._apply_prefix(['-bsvr4', '-bnoipath', '-bbigtoc']) + super().get_always_args()
def no_undefined_args(self) -> T.List[str]:
return self._apply_prefix(['-z', 'defs'])
def get_allow_undefined_args(self) -> T.List[str]:
return self._apply_prefix(['-z', 'nodefs'])
def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str,
rpath_paths: str, build_rpath: str,
install_rpath: str) -> T.Tuple[T.List[str], T.Set[bytes]]:
all_paths = mesonlib.OrderedSet(['/opt/freeware/lib']) # for libgcc_s.a
for p in rpath_paths:
all_paths.add(os.path.join(build_dir, p))
if build_rpath != '':
all_paths.add(build_rpath)
if install_rpath != '':
all_paths.add(install_rpath)
return (self._apply_prefix([x for p in all_paths for x in ('-R', p)]), set())
def thread_flags(self, env: 'Environment') -> T.List[str]:
return ['-pthread']
class OptlinkDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker):
"""Digital Mars dynamic linker for windows."""
id = 'optlink'
def __init__(self, exelist: T.List[str], for_machine: mesonlib.MachineChoice,
*, version: str = 'unknown version'):
# Use optlink instead of link so we don't interfer with other link.exe
# implementations.
super().__init__(exelist, for_machine, '', [], version=version)
def get_allow_undefined_args(self) -> T.List[str]:
return []
def get_debugfile_args(self, targetfile: str) -> T.List[str]:
# Optlink does not generate pdb files.
return []
def get_always_args(self) -> T.List[str]:
return []
class CudaLinker(PosixDynamicLinkerMixin, DynamicLinker):
"""Cuda linker (nvlink)"""
id = 'nvlink'
@staticmethod
def parse_version() -> str:
version_cmd = ['nvlink', '--version']
try:
_, out, _ = mesonlib.Popen_safe(version_cmd)
except OSError:
return 'unknown version'
# Output example:
# nvlink: NVIDIA (R) Cuda linker
# Copyright (c) 2005-2018 NVIDIA Corporation
# Built on Sun_Sep_30_21:09:22_CDT_2018
# Cuda compilation tools, release 10.0, V10.0.166
# we need the most verbose version output. Luckily starting with V
return out.strip().split('V')[-1]
def get_accepts_rsp(self) -> bool:
# nvcc does not support response files
return False
def get_lib_prefix(self) -> str:
if not mesonlib.is_windows():
return ''
# nvcc doesn't recognize Meson's default .a extension for static libraries on
# Windows and passes it to cl as an object file, resulting in 'warning D9024 :
# unrecognized source file type 'xxx.a', object file assumed'.
#
# nvcc's --library= option doesn't help: it takes the library name without the
# extension and assumes that the extension on Windows is .lib; prefixing the
# library with -Xlinker= seems to work.
from .compilers import CudaCompiler
return CudaCompiler.LINKER_PREFIX
def fatal_warnings(self) -> T.List[str]:
return ['--warning-as-error']
def get_allow_undefined_args(self) -> T.List[str]:
return []
def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
suffix: str, soversion: str, darwin_versions: T.Tuple[str, str],
is_shared_module: bool) -> T.List[str]:
return []
| 35.28497 | 110 | 0.618645 |
02b07f6484b8331ff818e0241489e9c5c0989cb0 | 2,430 | py | Python | homework/course_design_17231039/keywords.py | hiyouga/PY-Learning | 296f08e7964845c314874906039f244010d5422a | [
"MIT"
] | 2 | 2017-12-09T14:41:29.000Z | 2017-12-27T11:12:16.000Z | homework/course_design_17231039/keywords.py | hiyouga/PY-Learning | 296f08e7964845c314874906039f244010d5422a | [
"MIT"
] | null | null | null | homework/course_design_17231039/keywords.py | hiyouga/PY-Learning | 296f08e7964845c314874906039f244010d5422a | [
"MIT"
] | null | null | null | import json
import jieba
import pickle
from gensim.models import LdaModel, TfidfModel
from gensim.corpora import Dictionary
from wordcloud import WordCloud
with open('pagerank.json', 'r') as f:
pages = json.loads(f.read())
f.close()
pagelist = list(pages.keys())
contents = []
word_stats = {}
def std_fn(s):
return s.replace(':', '').replace('/', '-')
for page in pagelist:
with open('./corpus/'+std_fn(page)+'.txt', 'r') as f:
contents.append(f.read())
print('Starting jieba module')
jieba.load_userdict("userdict.txt")
train = []
skiplist = ['', '\n', ',', '。', ':', ';', '!', '?', '《', '》', '“', '”', '、', '(', ')', '&', '|', '▲', '·', '↓']
stopwords = [line.strip() for line in open('stopwords.txt', 'r', encoding='utf-8').readlines()]
for content in contents:
seg_list = jieba.lcut(content, cut_all = False)
result = []
for seg in seg_list:
seg = ''.join(seg.split())
if len(seg) > 1 and seg not in skiplist and seg not in stopwords:
result.append(seg)
train.append(result)
print('Starting gensim module')
dictionary = Dictionary(train)
corpus = [dictionary.doc2bow(text) for text in train]
tfidf = TfidfModel(corpus)
corpus_tfidf = tfidf[corpus]
lda_model = LdaModel(corpus=corpus_tfidf, id2word=dictionary, num_topics=50)
corpus_lda = lda_model[corpus_tfidf]
topic_list = []
for i in range(lda_model.num_topics):
topic_list.append(lda_model.show_topic(i))
word_index = {}
for i in range(len(pagelist)):
theme, dist = sorted(corpus_lda[i], key=lambda x:x[1], reverse=True)[0]
#print(lda_model.print_topic(theme))
weight = pages[pagelist[i]]*1e5
for topic_word, likelihood in topic_list[theme]:
if topic_word in word_stats.keys():
word_stats[topic_word] += likelihood * weight
word_index[topic_word].append((dist * likelihood, pagelist[i]))
else:
word_stats[topic_word] = likelihood * weight
word_index[topic_word] = [(dist * likelihood, pagelist[i])]
cloud = WordCloud(
font_path = 'simhei.ttf',
width = 400,
height = 100,
background_color = 'white',
mode = "RGBA",
scale = 2,
max_words = 50,
max_font_size = 40
)
wcloud = cloud.generate_from_frequencies(word_stats)
wcloud.to_file('wordcloud.gif')
for k, v in word_index.items():
v.sort(reverse = True)
pickle.dump(word_index, open('word_index.dic', 'wb'))
print('Completed!') | 31.558442 | 111 | 0.647737 |
4d54920d691e7df4343b9938e59d8be1c591af2c | 22,629 | py | Python | adles/vsphere/vsphere_class.py | devAmoghS/ADLES | bcfd5bc16c6222153ba56438a735ebb707a2b512 | [
"Apache-2.0"
] | null | null | null | adles/vsphere/vsphere_class.py | devAmoghS/ADLES | bcfd5bc16c6222153ba56438a735ebb707a2b512 | [
"Apache-2.0"
] | null | null | null | adles/vsphere/vsphere_class.py | devAmoghS/ADLES | bcfd5bc16c6222153ba56438a735ebb707a2b512 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from pyVim.connect import SmartConnect, SmartConnectNoSSL, Disconnect
from pyVmomi import vim, vmodl
class Vsphere:
""" Maintains connection, logging, and constants for a vSphere instance """
__version__ = "1.0.2"
def __init__(self, username=None, password=None, hostname=None,
datacenter=None, datastore=None,
port=443, use_ssl=False):
"""
Connects to a vCenter server and initializes a class instance.
:param str username: Username of account to login with
[default: prompt user]
:param str password: Password of account to login with
[default: prompt user]
:param str hostname: DNS hostname or IP address of vCenter instance
[default: prompt user]
:param str datastore: Name of datastore to use
[default: first datastore found on server]
:param str datacenter: Name of datacenter to use
[default: First datacenter found on server]
:param int port: Port used to connect to vCenter instance
:param bool use_ssl: If SSL should be used to connect
:raises LookupError: if a datacenter or datastore cannot be found
"""
self._log = logging.getLogger('Vsphere')
self._log.debug("Initializing Vsphere %s\nDatacenter: %s"
"\tDatastore: %s\tSSL: %s",
Vsphere.__version__, datacenter, datastore, use_ssl)
if username is None:
username = str(input("Enter username for vSphere: "))
if password is None:
from getpass import getpass
password = str(getpass("Enter password for %s: " % username))
if hostname is None:
hostname = str(input("Enter hostname for vSphere: "))
try:
self._log.info("Connecting to vSphere: %s@%s:%d",
username, hostname, port)
if use_ssl: # Connect to server using SSL certificate verification
self._server = SmartConnect(host=hostname, user=username,
pwd=password, port=port)
else:
self._server = SmartConnectNoSSL(host=hostname, user=username,
pwd=password, port=port)
except vim.fault.InvalidLogin:
self._log.error("Invalid vSphere login credentials for user %s",
username)
exit(1)
except Exception as e:
self._log.exception("Error connecting to vSphere: %s", str(e))
exit(1)
# Ensure connection to server is closed on program exit
from atexit import register
register(Disconnect, self._server)
self._log.info("Connected to vSphere host %s:%d", hostname, port)
self._log.debug("Current server time: %s",
str(self._server.CurrentTime()))
self.username = username
self.hostname = hostname
self.port = port
self.content = self._server.RetrieveContent()
self.auth = self.content.authorizationManager
self.user_dir = self.content.userDirectory
self.search_index = self.content.searchIndex
self.datacenter = self.get_item(vim.Datacenter, name=datacenter)
if not self.datacenter:
raise LookupError("Could not find a Datacenter to initialize with!")
self.datastore = self.get_datastore(datastore)
if not self.datastore:
raise LookupError("Could not find a Datastore to initialize with!")
self._log.debug("Finished initializing vSphere")
# From: create_folder_in_datacenter.py in pyvmomi-community-samples
def create_folder(self, folder_name, create_in=None):
"""
Creates a VM folder in the specified folder.
:param str folder_name: Name of folder to create
:param create_in: Folder to create the new folder in
[default: root folder of datacenter]
:type create_in: str or vim.Folder
:return: The created folder
:rtype: vim.Folder
"""
if create_in:
if isinstance(create_in, str): # Lookup create_in on the server
self._log.debug("Retrieving parent folder '%s' from server",
create_in)
parent = self.get_folder(folder_name=create_in)
else:
parent = create_in # Already vim.Folder, so we just assign it
else:
parent = self.content.rootFolder # Default to server root folder
return parent.create(folder_name)
def set_motd(self, message):
"""
Sets vCenter server Message of the Day (MOTD).
:param str message: Message to set
"""
self._log.info("Setting vCenter MOTD to %s", message)
self.content.sessionManager.UpdateServiceMessage(message=str(message))
def map_items(self, vimtypes, func, name=None,
container=None, recursive=True):
"""
Apply a function to item(s) in a container.
:param list vimtypes: List of vimtype objects to look for
:param func: Function to apply
:param str name: Name of item to apply to
:param container: Container to search in [default: content.rootFolder]
:param bool recursive: Whether to recursively descend
:return: List of values returned from the function call(s)
:rtype: list
"""
contain = (self.content.rootFolder if not container else container)
con_view = self.content.viewManager.CreateContainerView(contain,
vimtypes,
recursive)
returns = []
for item in con_view.view:
if name:
if hasattr(item, 'name') and item.name.lower() == name.lower():
returns.append(func(item))
else:
returns.append(func(item))
con_view.Destroy()
return returns
def set_entity_permissions(self, entity, permission):
"""
Defines or updates rule(s) for the given user or group on the entity.
:param entity: The entity on which to set permissions
:type entity: vim.ManagedEntity
:param permission: The permission to set
:type permission: vim.AuthorizationManager.Permission
"""
try:
self.auth.SetEntityPermissions(entity=entity, permission=permission)
except vim.fault.UserNotFound as e:
self._log.error("Could not find user '%s' to set permission "
"'%s' on entity '%s'",
e.principal, str(permission), entity.name)
except vim.fault.NotFound:
self._log.error("Invalid role ID for permission '%s'",
str(permission))
except vmodl.fault.ManagedObjectNotFound as e:
self._log.error("Entity '%s' does not exist to set permission on",
str(e.obj))
except vim.fault.NoPermission as e:
self._log.error("Could not set permissions for entity '%s': "
"the current session does not have privilege '%s' "
"to set permissions for the entity '%s'",
entity.name, e.privilegeId, e.object)
except vmodl.fault.InvalidArgument as e:
self._log.error("Invalid argument to set permission '%s' "
"on entity '%s': %s",
entity.name, str(permission), str(e))
except Exception as e:
self._log.exception("Unknown error while setting permissions "
"for entity '%s': %s",
entity.name, str(e))
def get_entity_permissions(self, entity, inherited=True):
"""
Gets permissions defined on or effective on a managed entity.
:param entity: The entity to get permissions for
:type entity: vim.ManagedEntity
:param bool inherited: Include propagating permissions
defined in parent
:return: The permissions for the entity
:rtype: vim.AuthorizationManager.Permission or None
"""
try:
return self.auth.RetrieveEntityPermissions(entity=entity,
inherited=inherited)
except vmodl.fault.ManagedObjectNotFound as e:
self._log.error("Couldn't find entity '%s' to get permissions from",
str(e.obj))
return None
def get_role_permissions(self, role_id):
"""
Gets all permissions that use a particular role.
:param int role_id: ID of the role
:return: The role permissions
:rtype: vim.AuthorizationManager.Permission or None
"""
try:
return self.auth.RetrieveRolePermissions(roleId=int(role_id))
except vim.fault.NotFound:
self._log.error("Role ID %s does not exist", str(role_id))
return None
def get_users(self, search='', domain='', exact=False,
belong_to_group=None, have_user=None,
find_users=True, find_groups=False):
"""
Returns a list of the users and groups defined for the server
.. note:: You must hold the Authorization.ModifyPermissions
privilege to invoke this method.
:param str search: Case insensitive substring used to filter results
[default: all users]
:param str domain: Domain to be searched [default: local machine]
:param bool exact: Search should match user/group name exactly
:param str belong_to_group: Only find users/groups that directly belong
to this group
:param str have_user: Only find groups that directly contain this user
:param bool find_users: Include users in results
:param bool find_groups: Include groups in results
:return: The users and groups defined for the server
:rtype: list(vim.UserSearchResult) or None
"""
# See for reference: pyvmomi/docs/vim/UserDirectory.rst
kwargs = {"searchStr": search, "exactMatch": exact,
"findUsers": find_users, "findGroups": find_groups}
if domain != '':
kwargs["domain"] = domain
if belong_to_group is not None:
kwargs["belongsToGroup"] = belong_to_group
if have_user is not None:
kwargs["belongsToUser"] = have_user
try:
return self.user_dir.RetrieveUserGroups(**kwargs)
except vim.fault.NotFound:
self._log.warning("Could not find domain, group or user "
"in call to get_users"
"\nkwargs: %s", str(kwargs))
return None
except vmodl.fault.NotSupported:
self._log.error("System doesn't support domains or "
"by-membership queries for get_users")
return None
def get_info(self):
"""
Retrieves and formats basic information about the vSphere instance.
:return: formatted server information
:rtype: str
"""
about = self.content.about
info_string = "\n"
info_string += "Host address: %s:%d\n" % (self.hostname, self.port)
info_string += "Datacenter : %s\n" % self.datacenter.name
info_string += "Datastore : %s\n" % self.datastore.name
info_string += "Full name : %s\n" % about.fullName
info_string += "Vendor : %s\n" % about.vendor
info_string += "Version : %s\n" % about.version
info_string += "API type : %s\n" % about.apiType
info_string += "API version : %s\n" % about.apiVersion
info_string += "OS type : %s" % about.osType
return info_string
def get_folder(self, folder_name=None):
"""
Finds and returns the named Folder.
:param str folder_name: Name of folder [default: Datacenter vmFolder]
:return: The folder found
:rtype: vim.Folder
"""
if folder_name: # Try to find the named folder in the datacenter
return self.get_obj(self.datacenter, [vim.Folder], folder_name)
else: # Default to the VM folder in the datacenter
# Reference: pyvmomi/docs/vim/Datacenter.rst
self._log.warning("Could not find folder '%s' in Datacenter '%s', "
"defaulting to vmFolder",
folder_name, self.datacenter.name)
return self.datacenter.vmFolder
def get_vm(self, vm_name):
"""
Finds and returns the named VM.
:param str vm_name: Name of the VM
:return: The VM found
:rtype: vim.VirtualMachine or None
"""
return self.get_item(vim.VirtualMachine, vm_name)
def get_network(self, network_name, distributed=False):
"""
Finds and returns the named Network.
:param str network_name: Name or path of the Network
:param bool distributed: If the Network is a Distributed PortGroup
:return: The network found
:rtype: vim.Network or vim.dvs.DistributedVirtualPortgroup or None
"""
if not distributed:
return self.get_obj(container=self.datacenter.networkFolder,
vimtypes=[vim.Network],
name=str(network_name), recursive=True)
else:
return self.get_item(vim.dvs.DistributedVirtualPortgroup,
network_name)
def get_host(self, host_name=None):
"""
Finds and returns the named Host System.
:param str host_name: Name of the host
[default: first host found in datacenter]
:return: The host found
:rtype: vim.HostSystem or None
"""
return self.get_item(vim.HostSystem, host_name)
def get_cluster(self, cluster_name=None):
"""
Finds and returns the named Cluster.
:param str cluster_name: Name of the cluster
[default: first cluster found in datacenter]
:return: The cluster found
:rtype: vim.ClusterComputeResource or None
"""
return self.get_item(cluster_name, vim.ClusterComputeResource)
def get_clusters(self):
"""
Get all the clusters associated with the vCenter server.
:return: All clusters associated with the vCenter server
:rtype: list(vim.ClusterComputeResource)
"""
return self.get_objs(self.content.rootFolder,
[vim.ClusterComputeResource])
def get_datastore(self, datastore_name=None):
"""
Finds and returns the named Datastore.
:param str datastore_name: Name of the datastore
[default: first datastore in datacenter]
:return: The datastore found
:rtype: vim.Datastore or None
"""
return self.datacenter.datastoreFolder.get(datastore_name)
def get_pool(self, pool_name=None):
"""
Finds and returns the named vim.ResourcePool.
:param str pool_name: Name of the resource pool
[default: first pool found in datacenter]
:return: The resource pool found
:rtype: vim.ResourcePool or None
"""
return self.get_item(vim.ResourcePool, pool_name)
def get_all_vms(self):
"""
Finds and returns all VMs registered in the Datacenter.
:return: All VMs in the Datacenter defined for the class
:rtype: list(vim.VirtualMachine)
"""
return self.get_objs(self.datacenter.vmFolder, [vim.VirtualMachine])
def get_obj(self, container, vimtypes, name, recursive=True):
"""
Finds and returns named vim object of specified type.
:param container: Container to search in
:param list vimtypes: vimtype objects to look for
:param str name: Name of the object
:param bool recursive: Recursively search for the item
:return: Object found with the specified name
:rtype: vimtype or None
"""
con_view = self.content.viewManager.CreateContainerView(container,
vimtypes,
recursive)
obj = None
for item in con_view.view:
if item.name.lower() == name.lower():
obj = item
break
con_view.Destroy()
return obj
# From: https://github.com/sijis/pyvmomi-examples/vmutils.py
def get_objs(self, container, vimtypes, recursive=True):
"""
Get all the vim objects associated with a given type.
:param container: Container to search in
:param list vimtypes: Objects to search for
:param bool recursive: Recursively search for the item
:return: All vimtype objects found
:rtype: list(vimtype) or None
"""
objs = []
con_view = self.content.viewManager.CreateContainerView(container,
vimtypes,
recursive)
for item in con_view.view:
objs.append(item)
con_view.Destroy()
return objs
def get_item(self, vimtype, name=None, container=None, recursive=True):
"""
Get a item of specified name and type.
Intended to be simple version of :meth: get_obj
:param vimtype: Type of item
:type vimtype: vimtype
:param str name: Name of item
:param container: Container to search in
[default: vCenter server content root folder]
:param bool recursive: Recursively search for the item
:return: The item found
:rtype: vimtype or None
"""
contain = (self.content.rootFolder if not container else container)
if not name:
return self.get_objs(contain, [vimtype], recursive)[0]
else:
return self.get_obj(contain, [vimtype], name, recursive)
def find_by_uuid(self, uuid, instance_uuid=True):
"""
Find a VM in the datacenter with the given Instance or BIOS UUID.
:param str uuid: UUID to search for (Instance or BIOS for VMs)
:param bool instance_uuid: If True, search by VM Instance UUID,
otherwise search by BIOS UUID
:return: The VM found
:rtype: vim.VirtualMachine or None
"""
return self.search_index.FindByUuid(datacenter=self.datacenter,
uuid=str(uuid), vmSearch=True,
instanceUuid=instance_uuid)
def find_by_ds_path(self, path):
"""
Finds a VM by it's location on a Datastore.
:param str path: Path to the VM's .vmx file on the Datastore
:return: The VM found
:rtype: vim.VirtualMachine or None
"""
try:
return self.search_index.FindByDatastorePath(
datacenter=self.datacenter, path=str(path))
except vim.fault.InvalidDatastore:
self._log.error("Invalid datastore in path: %s", str(path))
return None
def find_by_ip(self, ip, vm_search=True):
"""
Find a VM or Host using a IP address.
:param str ip: IP address string as returned by VMware Tools ipAddress
:param vm_search: Search for VMs if True, Hosts if False
:return: The VM or host found
:rtype: vim.VirtualMachine or vim.HostSystem or None
"""
return self.search_index.FindByIp(datacenter=self.datacenter,
ip=str(ip), vmSearch=vm_search)
def find_by_hostname(self, hostname, vm_search=True):
"""
Find a VM or Host using a Fully-Qualified Domain Name (FQDN).
:param str hostname: FQDN of the VM to find
:param vm_search: Search for VMs if True, Hosts if False
:return: The VM or host found
:rtype: vim.VirtualMachine or vim.HostSystem or None
"""
return self.search_index.FindByDnsName(datacenter=self.datacenter,
dnsName=hostname,
vmSearch=vm_search)
def find_by_inv_path(self, path, datacenter=None):
"""
Finds a vim.ManagedEntity (VM, host, folder, etc) in a inventory.
:param str path: Path to the entity. This must include the hidden
Vsphere folder for the type: vm | network | datastore | host
Example: "vm/some-things/more-things/vm-name"
:param str datacenter: Name of datacenter to search in
[default: instance's datacenter]
:return: The entity found
:rtype: vim.ManagedEntity or None
"""
if datacenter is None:
datacenter = self.datacenter.name
full_path = datacenter + "/" + str(path)
return self.search_index.FindByInventoryPath(inventoryPath=full_path)
def __repr__(self):
return "vSphere(%s, %s, %s:%s)" % (self.datacenter.name,
self.datastore.name,
self.hostname, self.port)
def __str__(self):
return str(self.get_info())
def __hash__(self):
return hash((self.hostname, self.port, self.username))
def __eq__(self, other):
return isinstance(other, self.__class__) \
and self.hostname == other.hostname \
and self.port == other.port \
and self.username == other.username
def __ne__(self, other):
return not self.__eq__(other)
| 41.445055 | 80 | 0.592602 |
68c0d3ad84ba9f681f2ded0e4517bd7ea420cab7 | 2,386 | py | Python | platform-tools/systrace/catapult/devil/devil/android/crash_handler_devicetest.py | NBPS-Robotics/FTC-Code-Team-9987---2022 | 180538f3ebd234635fa88f96ae7cf7441df6a246 | [
"MIT"
] | 7 | 2021-06-02T06:55:50.000Z | 2022-03-29T10:32:33.000Z | platform-tools/systrace/catapult/devil/devil/android/crash_handler_devicetest.py | NBPS-Robotics/FTC-Code-Team-9987---2022 | 180538f3ebd234635fa88f96ae7cf7441df6a246 | [
"MIT"
] | 7 | 2020-07-19T11:24:45.000Z | 2022-03-02T07:11:57.000Z | platform-tools/systrace/catapult/devil/devil/android/crash_handler_devicetest.py | NBPS-Robotics/FTC-Code-Team-9987---2022 | 180538f3ebd234635fa88f96ae7cf7441df6a246 | [
"MIT"
] | 1 | 2020-07-24T18:22:03.000Z | 2020-07-24T18:22:03.000Z | #!/usr/bin/env python
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
import unittest
if __name__ == '__main__':
sys.path.append(
os.path.abspath(os.path.join(
os.path.dirname(__file__),
'..',
'..',
)))
from devil.android import crash_handler
from devil.android import device_errors
from devil.android import device_utils
from devil.android import device_temp_file
from devil.android import device_test_case
from devil.utils import cmd_helper
from devil.utils import reraiser_thread
from devil.utils import timeout_retry
class DeviceCrashTest(device_test_case.DeviceTestCase):
def setUp(self):
super(DeviceCrashTest, self).setUp()
self.device = device_utils.DeviceUtils(self.serial)
def testCrashDuringCommand(self):
self.device.EnableRoot()
with device_temp_file.DeviceTempFile(self.device.adb) as trigger_file:
trigger_text = 'hello world'
def victim():
trigger_cmd = 'echo -n %s > %s; sleep 20' % (cmd_helper.SingleQuote(
trigger_text), cmd_helper.SingleQuote(trigger_file.name))
crash_handler.RetryOnSystemCrash(
lambda d: d.RunShellCommand(
trigger_cmd,
shell=True,
check_return=True,
retries=1,
as_root=True,
timeout=180),
device=self.device)
self.assertEquals(
trigger_text,
self.device.ReadFile(trigger_file.name, retries=0).strip())
return True
def crasher():
def ready_to_crash():
try:
return trigger_text == self.device.ReadFile(
trigger_file.name, retries=0).strip()
except device_errors.CommandFailedError:
return False
timeout_retry.WaitFor(ready_to_crash, wait_period=2, max_tries=10)
if not ready_to_crash():
return False
self.device.adb.Shell(
'echo c > /proc/sysrq-trigger',
expect_status=None,
timeout=60,
retries=0)
return True
self.assertEquals([True, True], reraiser_thread.RunAsync([crasher, victim]))
if __name__ == '__main__':
device_test_case.PrepareDevices()
unittest.main()
| 29.825 | 80 | 0.648365 |
f7591892a21c17f2024fa7e993cd4a2d0221fef7 | 4,016 | py | Python | tests/test_manage.py | james-portman/openstack-ansible | 882d98c94b6e429dec9d66d26722ed457e3b18b9 | [
"Apache-2.0"
] | null | null | null | tests/test_manage.py | james-portman/openstack-ansible | 882d98c94b6e429dec9d66d26722ed457e3b18b9 | [
"Apache-2.0"
] | null | null | null | tests/test_manage.py | james-portman/openstack-ansible | 882d98c94b6e429dec9d66d26722ed457e3b18b9 | [
"Apache-2.0"
] | 1 | 2018-05-21T18:41:51.000Z | 2018-05-21T18:41:51.000Z | #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from os import path
import test_inventory
import unittest
TARGET_DIR = path.join(os.getcwd(), 'tests', 'inventory')
from osa_toolkit import manage as mi
def setUpModule():
test_inventory.make_config()
def tearDownModule():
os.remove(test_inventory.USER_CONFIG_FILE)
class TestExportFunction(unittest.TestCase):
def setUp(self):
self.inv = test_inventory.get_inventory()
def tearDown(self):
test_inventory.cleanup()
def test_host_is_present(self):
host_inv = mi.export_host_info(self.inv)['hosts']
self.assertIn('aio1', host_inv.keys())
def test_groups_added(self):
host_inv = mi.export_host_info(self.inv)['hosts']
self.assertIn('groups', host_inv['aio1'].keys())
def test_variables_added(self):
host_inv = mi.export_host_info(self.inv)['hosts']
self.assertIn('hostvars', host_inv['aio1'].keys())
def test_number_of_hosts(self):
host_inv = mi.export_host_info(self.inv)['hosts']
self.assertEqual(len(self.inv['_meta']['hostvars']),
len(host_inv))
def test_all_information_added(self):
all_info = mi.export_host_info(self.inv)['all']
self.assertIn('provider_networks', all_info)
def test_all_lb_information(self):
all_info = mi.export_host_info(self.inv)['all']
inv_all = self.inv['all']['vars']
self.assertEqual(inv_all['internal_lb_vip_address'],
all_info['internal_lb_vip_address'])
class TestRemoveIpfunction(unittest.TestCase):
def setUp(self):
self.inv = test_inventory.get_inventory()
def tearDown(self):
test_inventory.cleanup()
def test_ips_removed(self):
mi.remove_ip_addresses(self.inv)
mi.remove_ip_addresses(self.inv, TARGET_DIR)
hostvars = self.inv['_meta']['hostvars']
for host, variables in hostvars.items():
has_networks = 'container_networks' in variables
if variables.get('is_metal', False):
continue
self.assertFalse(has_networks)
def test_inventory_item_removed(self):
inventory = self.inv
# Make sure we have log_hosts in the original inventory
self.assertIn('log_hosts', inventory)
mi.remove_inventory_item("log_hosts", inventory)
mi.remove_inventory_item("log_hosts", inventory, TARGET_DIR)
# Now make sure it's gone
self.assertIn('log_hosts', inventory)
def test_metal_ips_kept(self):
mi.remove_ip_addresses(self.inv)
hostvars = self.inv['_meta']['hostvars']
for host, variables in hostvars.items():
has_networks = 'container_networks' in variables
if not variables.get('is_metal', False):
continue
self.assertTrue(has_networks)
def test_ansible_host_vars_removed(self):
mi.remove_ip_addresses(self.inv)
hostvars = self.inv['_meta']['hostvars']
for host, variables in hostvars.items():
has_host = 'ansible_host' in variables
if variables.get('is_metal', False):
continue
self.assertFalse(has_host)
def test_multiple_calls(self):
"""Removal should fail silently if keys are absent."""
mi.remove_ip_addresses(self.inv)
mi.remove_ip_addresses(self.inv)
if __name__ == '__main__':
unittest.main(catchbreak=True)
| 31.622047 | 75 | 0.668327 |
95151cffb0e4f65d38105df09f0a846878331493 | 27,244 | py | Python | test/functional/rpc_psbt.py | CounosH/cch | 880f3890127951cba9f6b235193d8c9a9536e075 | [
"MIT"
] | null | null | null | test/functional/rpc_psbt.py | CounosH/cch | 880f3890127951cba9f6b235193d8c9a9536e075 | [
"MIT"
] | null | null | null | test/functional/rpc_psbt.py | CounosH/cch | 880f3890127951cba9f6b235193d8c9a9536e075 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2018-2019 The CounosH Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the Partially Signed Transaction RPCs.
"""
from decimal import Decimal
from test_framework.test_framework import CounosHTestFramework
from test_framework.util import (
assert_equal,
assert_greater_than,
assert_raises_rpc_error,
connect_nodes,
disconnect_nodes,
find_output,
)
import json
import os
MAX_BIP125_RBF_SEQUENCE = 0xfffffffd
# Create one-input, one-output, no-fee transaction:
class PSBTTest(CounosHTestFramework):
def set_test_params(self):
self.setup_clean_chain = False
self.num_nodes = 3
self.extra_args = [
["-walletrbf=1"],
["-walletrbf=0"],
[]
]
self.supports_cli = False
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
# TODO: Re-enable this test with segwit v1
def test_utxo_conversion(self):
mining_node = self.nodes[2]
offline_node = self.nodes[0]
online_node = self.nodes[1]
# Disconnect offline node from others
disconnect_nodes(offline_node, 1)
disconnect_nodes(online_node, 0)
disconnect_nodes(offline_node, 2)
disconnect_nodes(mining_node, 0)
# Mine a transaction that credits the offline address
offline_addr = offline_node.getnewaddress(address_type="p2sh-segwit")
online_addr = online_node.getnewaddress(address_type="p2sh-segwit")
online_node.importaddress(offline_addr, "", False)
mining_node.sendtoaddress(address=offline_addr, amount=1.0)
mining_node.generate(nblocks=1)
self.sync_blocks([mining_node, online_node])
# Construct an unsigned PSBT on the online node (who doesn't know the output is Segwit, so will include a non-witness UTXO)
utxos = online_node.listunspent(addresses=[offline_addr])
raw = online_node.createrawtransaction([{"txid":utxos[0]["txid"], "vout":utxos[0]["vout"]}],[{online_addr:0.9999}])
psbt = online_node.walletprocesspsbt(online_node.converttopsbt(raw))["psbt"]
assert "non_witness_utxo" in mining_node.decodepsbt(psbt)["inputs"][0]
# Have the offline node sign the PSBT (which will update the UTXO to segwit)
signed_psbt = offline_node.walletprocesspsbt(psbt)["psbt"]
assert "witness_utxo" in mining_node.decodepsbt(signed_psbt)["inputs"][0]
# Make sure we can mine the resulting transaction
txid = mining_node.sendrawtransaction(mining_node.finalizepsbt(signed_psbt)["hex"])
mining_node.generate(1)
self.sync_blocks([mining_node, online_node])
assert_equal(online_node.gettxout(txid,0)["confirmations"], 1)
# Reconnect
connect_nodes(self.nodes[0], 1)
connect_nodes(self.nodes[0], 2)
def run_test(self):
# Create and fund a raw tx for sending 10 CCH
psbtx1 = self.nodes[0].walletcreatefundedpsbt([], {self.nodes[2].getnewaddress():10})['psbt']
# Node 1 should not be able to add anything to it but still return the psbtx same as before
psbtx = self.nodes[1].walletprocesspsbt(psbtx1)['psbt']
assert_equal(psbtx1, psbtx)
# Sign the transaction and send
signed_tx = self.nodes[0].walletprocesspsbt(psbtx)['psbt']
final_tx = self.nodes[0].finalizepsbt(signed_tx)['hex']
self.nodes[0].sendrawtransaction(final_tx)
# Create p2sh, p2wpkh, and p2wsh addresses
pubkey0 = self.nodes[0].getaddressinfo(self.nodes[0].getnewaddress())['pubkey']
pubkey1 = self.nodes[1].getaddressinfo(self.nodes[1].getnewaddress())['pubkey']
pubkey2 = self.nodes[2].getaddressinfo(self.nodes[2].getnewaddress())['pubkey']
p2sh = self.nodes[1].addmultisigaddress(2, [pubkey0, pubkey1, pubkey2], "", "legacy")['address']
p2wsh = self.nodes[1].addmultisigaddress(2, [pubkey0, pubkey1, pubkey2], "", "bech32")['address']
p2sh_p2wsh = self.nodes[1].addmultisigaddress(2, [pubkey0, pubkey1, pubkey2], "", "p2sh-segwit")['address']
p2wpkh = self.nodes[1].getnewaddress("", "bech32")
p2pkh = self.nodes[1].getnewaddress("", "legacy")
p2sh_p2wpkh = self.nodes[1].getnewaddress("", "p2sh-segwit")
# fund those addresses
rawtx = self.nodes[0].createrawtransaction([], {p2sh:10, p2wsh:10, p2wpkh:10, p2sh_p2wsh:10, p2sh_p2wpkh:10, p2pkh:10})
rawtx = self.nodes[0].fundrawtransaction(rawtx, {"changePosition":3})
signed_tx = self.nodes[0].signrawtransactionwithwallet(rawtx['hex'])['hex']
txid = self.nodes[0].sendrawtransaction(signed_tx)
self.nodes[0].generate(6)
self.sync_all()
# Find the output pos
p2sh_pos = -1
p2wsh_pos = -1
p2wpkh_pos = -1
p2pkh_pos = -1
p2sh_p2wsh_pos = -1
p2sh_p2wpkh_pos = -1
decoded = self.nodes[0].decoderawtransaction(signed_tx)
for out in decoded['vout']:
if out['scriptPubKey']['addresses'][0] == p2sh:
p2sh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2wsh:
p2wsh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2wpkh:
p2wpkh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2sh_p2wsh:
p2sh_p2wsh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2sh_p2wpkh:
p2sh_p2wpkh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2pkh:
p2pkh_pos = out['n']
# spend single key from node 1
rawtx = self.nodes[1].walletcreatefundedpsbt([{"txid":txid,"vout":p2wpkh_pos},{"txid":txid,"vout":p2sh_p2wpkh_pos},{"txid":txid,"vout":p2pkh_pos}], {self.nodes[1].getnewaddress():29.99})['psbt']
walletprocesspsbt_out = self.nodes[1].walletprocesspsbt(rawtx)
# Make sure it has both types of UTXOs
decoded = self.nodes[1].decodepsbt(walletprocesspsbt_out['psbt'])
assert 'non_witness_utxo' in decoded['inputs'][0]
assert 'witness_utxo' in decoded['inputs'][0]
assert_equal(walletprocesspsbt_out['complete'], True)
self.nodes[1].sendrawtransaction(self.nodes[1].finalizepsbt(walletprocesspsbt_out['psbt'])['hex'])
# feeRate of 0.1 CCH / KB produces a total fee slightly below -maxtxfee (~0.05280000):
res = self.nodes[1].walletcreatefundedpsbt([{"txid":txid,"vout":p2wpkh_pos},{"txid":txid,"vout":p2sh_p2wpkh_pos},{"txid":txid,"vout":p2pkh_pos}], {self.nodes[1].getnewaddress():29.99}, 0, {"feeRate": 0.1})
assert_greater_than(res["fee"], 0.05)
assert_greater_than(0.06, res["fee"])
# feeRate of 10 CCH / KB produces a total fee well above -maxtxfee
# previously this was silently capped at -maxtxfee
assert_raises_rpc_error(-4, "Fee exceeds maximum configured by -maxtxfee", self.nodes[1].walletcreatefundedpsbt, [{"txid":txid,"vout":p2wpkh_pos},{"txid":txid,"vout":p2sh_p2wpkh_pos},{"txid":txid,"vout":p2pkh_pos}], {self.nodes[1].getnewaddress():29.99}, 0, {"feeRate": 10})
# partially sign multisig things with node 1
psbtx = self.nodes[1].walletcreatefundedpsbt([{"txid":txid,"vout":p2wsh_pos},{"txid":txid,"vout":p2sh_pos},{"txid":txid,"vout":p2sh_p2wsh_pos}], {self.nodes[1].getnewaddress():29.99})['psbt']
walletprocesspsbt_out = self.nodes[1].walletprocesspsbt(psbtx)
psbtx = walletprocesspsbt_out['psbt']
assert_equal(walletprocesspsbt_out['complete'], False)
# partially sign with node 2. This should be complete and sendable
walletprocesspsbt_out = self.nodes[2].walletprocesspsbt(psbtx)
assert_equal(walletprocesspsbt_out['complete'], True)
self.nodes[2].sendrawtransaction(self.nodes[2].finalizepsbt(walletprocesspsbt_out['psbt'])['hex'])
# check that walletprocesspsbt fails to decode a non-psbt
rawtx = self.nodes[1].createrawtransaction([{"txid":txid,"vout":p2wpkh_pos}], {self.nodes[1].getnewaddress():9.99})
assert_raises_rpc_error(-22, "TX decode failed", self.nodes[1].walletprocesspsbt, rawtx)
# Convert a non-psbt to psbt and make sure we can decode it
rawtx = self.nodes[0].createrawtransaction([], {self.nodes[1].getnewaddress():10})
rawtx = self.nodes[0].fundrawtransaction(rawtx)
new_psbt = self.nodes[0].converttopsbt(rawtx['hex'])
self.nodes[0].decodepsbt(new_psbt)
# Make sure that a non-psbt with signatures cannot be converted
# Error could be either "TX decode failed" (segwit inputs causes parsing to fail) or "Inputs must not have scriptSigs and scriptWitnesses"
# We must set iswitness=True because the serialized transaction has inputs and is therefore a witness transaction
signedtx = self.nodes[0].signrawtransactionwithwallet(rawtx['hex'])
assert_raises_rpc_error(-22, "", self.nodes[0].converttopsbt, hexstring=signedtx['hex'], iswitness=True)
assert_raises_rpc_error(-22, "", self.nodes[0].converttopsbt, hexstring=signedtx['hex'], permitsigdata=False, iswitness=True)
# Unless we allow it to convert and strip signatures
self.nodes[0].converttopsbt(signedtx['hex'], True)
# Explicitly allow converting non-empty txs
new_psbt = self.nodes[0].converttopsbt(rawtx['hex'])
self.nodes[0].decodepsbt(new_psbt)
# Create outputs to nodes 1 and 2
node1_addr = self.nodes[1].getnewaddress()
node2_addr = self.nodes[2].getnewaddress()
txid1 = self.nodes[0].sendtoaddress(node1_addr, 13)
txid2 = self.nodes[0].sendtoaddress(node2_addr, 13)
blockhash = self.nodes[0].generate(6)[0]
self.sync_all()
vout1 = find_output(self.nodes[1], txid1, 13, blockhash=blockhash)
vout2 = find_output(self.nodes[2], txid2, 13, blockhash=blockhash)
# Create a psbt spending outputs from nodes 1 and 2
psbt_orig = self.nodes[0].createpsbt([{"txid":txid1, "vout":vout1}, {"txid":txid2, "vout":vout2}], {self.nodes[0].getnewaddress():25.999})
# Update psbts, should only have data for one input and not the other
psbt1 = self.nodes[1].walletprocesspsbt(psbt_orig, False, "ALL")['psbt']
psbt1_decoded = self.nodes[0].decodepsbt(psbt1)
assert psbt1_decoded['inputs'][0] and not psbt1_decoded['inputs'][1]
# Check that BIP32 path was added
assert "bip32_derivs" in psbt1_decoded['inputs'][0]
psbt2 = self.nodes[2].walletprocesspsbt(psbt_orig, False, "ALL", False)['psbt']
psbt2_decoded = self.nodes[0].decodepsbt(psbt2)
assert not psbt2_decoded['inputs'][0] and psbt2_decoded['inputs'][1]
# Check that BIP32 paths were not added
assert "bip32_derivs" not in psbt2_decoded['inputs'][1]
# Sign PSBTs (workaround issue #18039)
psbt1 = self.nodes[1].walletprocesspsbt(psbt_orig)['psbt']
psbt2 = self.nodes[2].walletprocesspsbt(psbt_orig)['psbt']
# Combine, finalize, and send the psbts
combined = self.nodes[0].combinepsbt([psbt1, psbt2])
finalized = self.nodes[0].finalizepsbt(combined)['hex']
self.nodes[0].sendrawtransaction(finalized)
self.nodes[0].generate(6)
self.sync_all()
# Test additional args in walletcreatepsbt
# Make sure both pre-included and funded inputs
# have the correct sequence numbers based on
# replaceable arg
block_height = self.nodes[0].getblockcount()
unspent = self.nodes[0].listunspent()[0]
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}], block_height+2, {"replaceable": False}, False)
decoded_psbt = self.nodes[0].decodepsbt(psbtx_info["psbt"])
for tx_in, psbt_in in zip(decoded_psbt["tx"]["vin"], decoded_psbt["inputs"]):
assert_greater_than(tx_in["sequence"], MAX_BIP125_RBF_SEQUENCE)
assert "bip32_derivs" not in psbt_in
assert_equal(decoded_psbt["tx"]["locktime"], block_height+2)
# Same construction with only locktime set and RBF explicitly enabled
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}], block_height, {"replaceable": True}, True)
decoded_psbt = self.nodes[0].decodepsbt(psbtx_info["psbt"])
for tx_in, psbt_in in zip(decoded_psbt["tx"]["vin"], decoded_psbt["inputs"]):
assert_equal(tx_in["sequence"], MAX_BIP125_RBF_SEQUENCE)
assert "bip32_derivs" in psbt_in
assert_equal(decoded_psbt["tx"]["locktime"], block_height)
# Same construction without optional arguments
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}])
decoded_psbt = self.nodes[0].decodepsbt(psbtx_info["psbt"])
for tx_in, psbt_in in zip(decoded_psbt["tx"]["vin"], decoded_psbt["inputs"]):
assert_equal(tx_in["sequence"], MAX_BIP125_RBF_SEQUENCE)
assert "bip32_derivs" in psbt_in
assert_equal(decoded_psbt["tx"]["locktime"], 0)
# Same construction without optional arguments, for a node with -walletrbf=0
unspent1 = self.nodes[1].listunspent()[0]
psbtx_info = self.nodes[1].walletcreatefundedpsbt([{"txid":unspent1["txid"], "vout":unspent1["vout"]}], [{self.nodes[2].getnewaddress():unspent1["amount"]+1}], block_height)
decoded_psbt = self.nodes[1].decodepsbt(psbtx_info["psbt"])
for tx_in, psbt_in in zip(decoded_psbt["tx"]["vin"], decoded_psbt["inputs"]):
assert_greater_than(tx_in["sequence"], MAX_BIP125_RBF_SEQUENCE)
assert "bip32_derivs" in psbt_in
# Make sure change address wallet does not have P2SH innerscript access to results in success
# when attempting BnB coin selection
self.nodes[0].walletcreatefundedpsbt([], [{self.nodes[2].getnewaddress():unspent["amount"]+1}], block_height+2, {"changeAddress":self.nodes[1].getnewaddress()}, False)
# Regression test for 14473 (mishandling of already-signed witness transaction):
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}])
complete_psbt = self.nodes[0].walletprocesspsbt(psbtx_info["psbt"])
double_processed_psbt = self.nodes[0].walletprocesspsbt(complete_psbt["psbt"])
assert_equal(complete_psbt, double_processed_psbt)
# We don't care about the decode result, but decoding must succeed.
self.nodes[0].decodepsbt(double_processed_psbt["psbt"])
# BIP 174 Test Vectors
# Check that unknown values are just passed through
unknown_psbt = "cHNidP8BAD8CAAAAAf//////////////////////////////////////////AAAAAAD/////AQAAAAAAAAAAA2oBAAAAAAAACg8BAgMEBQYHCAkPAQIDBAUGBwgJCgsMDQ4PAAA="
unknown_out = self.nodes[0].walletprocesspsbt(unknown_psbt)['psbt']
assert_equal(unknown_psbt, unknown_out)
# Open the data file
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/rpc_psbt.json'), encoding='utf-8') as f:
d = json.load(f)
invalids = d['invalid']
valids = d['valid']
creators = d['creator']
signers = d['signer']
combiners = d['combiner']
finalizers = d['finalizer']
extractors = d['extractor']
# Invalid PSBTs
for invalid in invalids:
assert_raises_rpc_error(-22, "TX decode failed", self.nodes[0].decodepsbt, invalid)
# Valid PSBTs
for valid in valids:
self.nodes[0].decodepsbt(valid)
# Creator Tests
for creator in creators:
created_tx = self.nodes[0].createpsbt(creator['inputs'], creator['outputs'])
assert_equal(created_tx, creator['result'])
# Signer tests
for i, signer in enumerate(signers):
self.nodes[2].createwallet("wallet{}".format(i))
wrpc = self.nodes[2].get_wallet_rpc("wallet{}".format(i))
for key in signer['privkeys']:
wrpc.importprivkey(key)
signed_tx = wrpc.walletprocesspsbt(signer['psbt'])['psbt']
assert_equal(signed_tx, signer['result'])
# Combiner test
for combiner in combiners:
combined = self.nodes[2].combinepsbt(combiner['combine'])
assert_equal(combined, combiner['result'])
# Empty combiner test
assert_raises_rpc_error(-8, "Parameter 'txs' cannot be empty", self.nodes[0].combinepsbt, [])
# Finalizer test
for finalizer in finalizers:
finalized = self.nodes[2].finalizepsbt(finalizer['finalize'], False)['psbt']
assert_equal(finalized, finalizer['result'])
# Extractor test
for extractor in extractors:
extracted = self.nodes[2].finalizepsbt(extractor['extract'], True)['hex']
assert_equal(extracted, extractor['result'])
# Unload extra wallets
for i, signer in enumerate(signers):
self.nodes[2].unloadwallet("wallet{}".format(i))
# TODO: Re-enable this for segwit v1
# self.test_utxo_conversion()
# Test that psbts with p2pkh outputs are created properly
p2pkh = self.nodes[0].getnewaddress(address_type='legacy')
psbt = self.nodes[1].walletcreatefundedpsbt([], [{p2pkh : 1}], 0, {"includeWatching" : True}, True)
self.nodes[0].decodepsbt(psbt['psbt'])
# Test decoding error: invalid base64
assert_raises_rpc_error(-22, "TX decode failed invalid base64", self.nodes[0].decodepsbt, ";definitely not base64;")
# Send to all types of addresses
addr1 = self.nodes[1].getnewaddress("", "bech32")
txid1 = self.nodes[0].sendtoaddress(addr1, 11)
vout1 = find_output(self.nodes[0], txid1, 11)
addr2 = self.nodes[1].getnewaddress("", "legacy")
txid2 = self.nodes[0].sendtoaddress(addr2, 11)
vout2 = find_output(self.nodes[0], txid2, 11)
addr3 = self.nodes[1].getnewaddress("", "p2sh-segwit")
txid3 = self.nodes[0].sendtoaddress(addr3, 11)
vout3 = find_output(self.nodes[0], txid3, 11)
self.sync_all()
def test_psbt_input_keys(psbt_input, keys):
"""Check that the psbt input has only the expected keys."""
assert_equal(set(keys), set(psbt_input.keys()))
# Create a PSBT. None of the inputs are filled initially
psbt = self.nodes[1].createpsbt([{"txid":txid1, "vout":vout1},{"txid":txid2, "vout":vout2},{"txid":txid3, "vout":vout3}], {self.nodes[0].getnewaddress():32.999})
decoded = self.nodes[1].decodepsbt(psbt)
test_psbt_input_keys(decoded['inputs'][0], [])
test_psbt_input_keys(decoded['inputs'][1], [])
test_psbt_input_keys(decoded['inputs'][2], [])
# Update a PSBT with UTXOs from the node
# Bech32 inputs should be filled with witness UTXO. Other inputs should not be filled because they are non-witness
updated = self.nodes[1].utxoupdatepsbt(psbt)
decoded = self.nodes[1].decodepsbt(updated)
test_psbt_input_keys(decoded['inputs'][0], ['witness_utxo'])
test_psbt_input_keys(decoded['inputs'][1], [])
test_psbt_input_keys(decoded['inputs'][2], [])
# Try again, now while providing descriptors, making P2SH-segwit work, and causing bip32_derivs and redeem_script to be filled in
descs = [self.nodes[1].getaddressinfo(addr)['desc'] for addr in [addr1,addr2,addr3]]
updated = self.nodes[1].utxoupdatepsbt(psbt=psbt, descriptors=descs)
decoded = self.nodes[1].decodepsbt(updated)
test_psbt_input_keys(decoded['inputs'][0], ['witness_utxo', 'bip32_derivs'])
test_psbt_input_keys(decoded['inputs'][1], [])
test_psbt_input_keys(decoded['inputs'][2], ['witness_utxo', 'bip32_derivs', 'redeem_script'])
# Two PSBTs with a common input should not be joinable
psbt1 = self.nodes[1].createpsbt([{"txid":txid1, "vout":vout1}], {self.nodes[0].getnewaddress():Decimal('10.999')})
assert_raises_rpc_error(-8, "exists in multiple PSBTs", self.nodes[1].joinpsbts, [psbt1, updated])
# Join two distinct PSBTs
addr4 = self.nodes[1].getnewaddress("", "p2sh-segwit")
txid4 = self.nodes[0].sendtoaddress(addr4, 5)
vout4 = find_output(self.nodes[0], txid4, 5)
self.nodes[0].generate(6)
self.sync_all()
psbt2 = self.nodes[1].createpsbt([{"txid":txid4, "vout":vout4}], {self.nodes[0].getnewaddress():Decimal('4.999')})
psbt2 = self.nodes[1].walletprocesspsbt(psbt2)['psbt']
psbt2_decoded = self.nodes[0].decodepsbt(psbt2)
assert "final_scriptwitness" in psbt2_decoded['inputs'][0] and "final_scriptSig" in psbt2_decoded['inputs'][0]
joined = self.nodes[0].joinpsbts([psbt, psbt2])
joined_decoded = self.nodes[0].decodepsbt(joined)
assert len(joined_decoded['inputs']) == 4 and len(joined_decoded['outputs']) == 2 and "final_scriptwitness" not in joined_decoded['inputs'][3] and "final_scriptSig" not in joined_decoded['inputs'][3]
# Check that joining shuffles the inputs and outputs
# 10 attempts should be enough to get a shuffled join
shuffled = False
for i in range(0, 10):
shuffled_joined = self.nodes[0].joinpsbts([psbt, psbt2])
shuffled |= joined != shuffled_joined
if shuffled:
break
assert shuffled
# Newly created PSBT needs UTXOs and updating
addr = self.nodes[1].getnewaddress("", "p2sh-segwit")
txid = self.nodes[0].sendtoaddress(addr, 7)
addrinfo = self.nodes[1].getaddressinfo(addr)
blockhash = self.nodes[0].generate(6)[0]
self.sync_all()
vout = find_output(self.nodes[0], txid, 7, blockhash=blockhash)
psbt = self.nodes[1].createpsbt([{"txid":txid, "vout":vout}], {self.nodes[0].getnewaddress("", "p2sh-segwit"):Decimal('6.999')})
analyzed = self.nodes[0].analyzepsbt(psbt)
assert not analyzed['inputs'][0]['has_utxo'] and not analyzed['inputs'][0]['is_final'] and analyzed['inputs'][0]['next'] == 'updater' and analyzed['next'] == 'updater'
# After update with wallet, only needs signing
updated = self.nodes[1].walletprocesspsbt(psbt, False, 'ALL', True)['psbt']
analyzed = self.nodes[0].analyzepsbt(updated)
assert analyzed['inputs'][0]['has_utxo'] and not analyzed['inputs'][0]['is_final'] and analyzed['inputs'][0]['next'] == 'signer' and analyzed['next'] == 'signer' and analyzed['inputs'][0]['missing']['signatures'][0] == addrinfo['embedded']['witness_program']
# Check fee and size things
assert analyzed['fee'] == Decimal('0.001') and analyzed['estimated_vsize'] == 134 and analyzed['estimated_feerate'] == Decimal('0.00746268')
# After signing and finalizing, needs extracting
signed = self.nodes[1].walletprocesspsbt(updated)['psbt']
analyzed = self.nodes[0].analyzepsbt(signed)
assert analyzed['inputs'][0]['has_utxo'] and analyzed['inputs'][0]['is_final'] and analyzed['next'] == 'extractor'
self.log.info("PSBT spending unspendable outputs should have error message and Creator as next")
analysis = self.nodes[0].analyzepsbt('cHNidP8BAJoCAAAAAljoeiG1ba8MI76OcHBFbDNvfLqlyHV5JPVFiHuyq911AAAAAAD/////g40EJ9DsZQpoqka7CwmK6kQiwHGyyng1Kgd5WdB86h0BAAAAAP////8CcKrwCAAAAAAWAEHYXCtx0AYLCcmIauuBXlCZHdoSTQDh9QUAAAAAFv8/wADXYP/7//////8JxOh0LR2HAI8AAAAAAAEBIADC6wsAAAAAF2oUt/X69ELjeX2nTof+fZ10l+OyAokDAQcJAwEHEAABAACAAAEBIADC6wsAAAAAF2oUt/X69ELjeX2nTof+fZ10l+OyAokDAQcJAwEHENkMak8AAAAA')
assert_equal(analysis['next'], 'creator')
assert_equal(analysis['error'], 'PSBT is not valid. Input 0 spends unspendable output')
self.log.info("PSBT with invalid values should have error message and Creator as next")
analysis = self.nodes[0].analyzepsbt('cHNidP8BAHECAAAAAfA00BFgAm6tp86RowwH6BMImQNL5zXUcTT97XoLGz0BAAAAAAD/////AgD5ApUAAAAAFgAUKNw0x8HRctAgmvoevm4u1SbN7XL87QKVAAAAABYAFPck4gF7iL4NL4wtfRAKgQbghiTUAAAAAAABAR8AgIFq49AHABYAFJUDtxf2PHo641HEOBOAIvFMNTr2AAAA')
assert_equal(analysis['next'], 'creator')
assert_equal(analysis['error'], 'PSBT is not valid. Input 0 has invalid value')
self.log.info("PSBT with signed, but not finalized, inputs should have Finalizer as next")
analysis = self.nodes[0].analyzepsbt('cHNidP8BAHECAAAAAZYezcxdnbXoQCmrD79t/LzDgtUo9ERqixk8wgioAobrAAAAAAD9////AlDDAAAAAAAAFgAUy/UxxZuzZswcmFnN/E9DGSiHLUsuGPUFAAAAABYAFLsH5o0R38wXx+X2cCosTMCZnQ4baAAAAAABAR8A4fUFAAAAABYAFOBI2h5thf3+Lflb2LGCsVSZwsltIgIC/i4dtVARCRWtROG0HHoGcaVklzJUcwo5homgGkSNAnJHMEQCIGx7zKcMIGr7cEES9BR4Kdt/pzPTK3fKWcGyCJXb7MVnAiALOBgqlMH4GbC1HDh/HmylmO54fyEy4lKde7/BT/PWxwEBAwQBAAAAIgYC/i4dtVARCRWtROG0HHoGcaVklzJUcwo5homgGkSNAnIYDwVpQ1QAAIABAACAAAAAgAAAAAAAAAAAAAAiAgL+CIiB59NSCssOJRGiMYQK1chahgAaaJpIXE41Cyir+xgPBWlDVAAAgAEAAIAAAACAAQAAAAAAAAAA')
assert_equal(analysis['next'], 'finalizer')
analysis = self.nodes[0].analyzepsbt('cHNidP8BAHECAAAAAfA00BFgAm6tp86RowwH6BMImQNL5zXUcTT97XoLGz0BAAAAAAD/////AgCAgWrj0AcAFgAUKNw0x8HRctAgmvoevm4u1SbN7XL87QKVAAAAABYAFPck4gF7iL4NL4wtfRAKgQbghiTUAAAAAAABAR8A8gUqAQAAABYAFJUDtxf2PHo641HEOBOAIvFMNTr2AAAA')
assert_equal(analysis['next'], 'creator')
assert_equal(analysis['error'], 'PSBT is not valid. Output amount invalid')
analysis = self.nodes[0].analyzepsbt('cHNidP8BAJoCAAAAAkvEW8NnDtdNtDpsmze+Ht2LH35IJcKv00jKAlUs21RrAwAAAAD/////S8Rbw2cO1020OmybN74e3Ysffkglwq/TSMoCVSzbVGsBAAAAAP7///8CwLYClQAAAAAWABSNJKzjaUb3uOxixsvh1GGE3fW7zQD5ApUAAAAAFgAUKNw0x8HRctAgmvoevm4u1SbN7XIAAAAAAAEAnQIAAAACczMa321tVHuN4GKWKRncycI22aX3uXgwSFUKM2orjRsBAAAAAP7///9zMxrfbW1Ue43gYpYpGdzJwjbZpfe5eDBIVQozaiuNGwAAAAAA/v///wIA+QKVAAAAABl2qRT9zXUVA8Ls5iVqynLHe5/vSe1XyYisQM0ClQAAAAAWABRmWQUcjSjghQ8/uH4Bn/zkakwLtAAAAAAAAQEfQM0ClQAAAAAWABRmWQUcjSjghQ8/uH4Bn/zkakwLtAAAAA==')
assert_equal(analysis['next'], 'creator')
assert_equal(analysis['error'], 'PSBT is not valid. Input 0 specifies invalid prevout')
assert_raises_rpc_error(-25, 'Missing inputs', self.nodes[0].walletprocesspsbt, 'cHNidP8BAJoCAAAAAkvEW8NnDtdNtDpsmze+Ht2LH35IJcKv00jKAlUs21RrAwAAAAD/////S8Rbw2cO1020OmybN74e3Ysffkglwq/TSMoCVSzbVGsBAAAAAP7///8CwLYClQAAAAAWABSNJKzjaUb3uOxixsvh1GGE3fW7zQD5ApUAAAAAFgAUKNw0x8HRctAgmvoevm4u1SbN7XIAAAAAAAEAnQIAAAACczMa321tVHuN4GKWKRncycI22aX3uXgwSFUKM2orjRsBAAAAAP7///9zMxrfbW1Ue43gYpYpGdzJwjbZpfe5eDBIVQozaiuNGwAAAAAA/v///wIA+QKVAAAAABl2qRT9zXUVA8Ls5iVqynLHe5/vSe1XyYisQM0ClQAAAAAWABRmWQUcjSjghQ8/uH4Bn/zkakwLtAAAAAAAAQEfQM0ClQAAAAAWABRmWQUcjSjghQ8/uH4Bn/zkakwLtAAAAA==')
if __name__ == '__main__':
PSBTTest().main()
| 58.969697 | 575 | 0.680517 |
b874c715857f8ddc79a8fa68e842882e04784650 | 7,999 | py | Python | backwardcompatibilityml/widgets/model_comparison/model_comparison.py | microsoft/BackwardCompatibilityML | 5910e485453f07fd5c85114d15c423c5db521122 | [
"MIT"
] | 54 | 2020-09-11T18:36:59.000Z | 2022-03-29T00:47:55.000Z | backwardcompatibilityml/widgets/model_comparison/model_comparison.py | microsoft/BackwardCompatibilityML | 5910e485453f07fd5c85114d15c423c5db521122 | [
"MIT"
] | 115 | 2020-10-08T16:55:34.000Z | 2022-03-12T00:50:21.000Z | backwardcompatibilityml/widgets/model_comparison/model_comparison.py | microsoft/BackwardCompatibilityML | 5910e485453f07fd5c85114d15c423c5db521122 | [
"MIT"
] | 11 | 2020-10-04T09:40:11.000Z | 2021-12-21T21:03:33.000Z | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import json
import pkg_resources
from jinja2 import Template
from IPython.display import (
display,
HTML
)
import torch.optim as optim
from flask import Response
from backwardcompatibilityml import loss
from backwardcompatibilityml.comparison_management import ComparisonManager
from backwardcompatibilityml.metrics import model_accuracy
from rai_core_flask.flask_helper import FlaskHelper
from rai_core_flask.environments import (
AzureNBEnvironment,
DatabricksEnvironment,
LocalIPythonEnvironment)
from backwardcompatibilityml.helpers import http
from backwardcompatibilityml.helpers import comparison
def build_environment_params(flask_service_env):
"""
A small helper function to return a dictionary of
the environment type and the base url of the
Flask service for the environment type.
Args:
flask_service_env: An instance of an environment from
rai_core_flask.environments.
Returns:
A dictionary of the environment type specified as a string,
and the base url to be used when accessing the Flask
service for this environment type.
"""
if isinstance(flask_service_env, LocalIPythonEnvironment):
return {
"environment_type": "local",
"base_url": ""
}
elif isinstance(flask_service_env, AzureNBEnvironment):
return {
"environment_type": "azureml",
"base_url": flask_service_env.base_url
}
elif isinstance(flask_service_env, DatabricksEnvironment):
return {
"environment_type": "databricks",
"base_url": flask_service_env.base_url
}
else:
return {
"environment_type": "unknown",
"base_url": ""
}
def render_widget_html(api_service_environment, data):
"""
Renders the HTML for the compatibility analysis widget.
Args:
api_service_environment: A dictionary of the environment
type, the base URL, and the port for the Flask service.
Returns:
The widget HTML rendered as a string.
"""
resource_package = __name__
javascript_path = '/'.join(('resources', 'widget-build.js'))
css_path = '/'.join(('resources', 'widget.css'))
html_template_path = '/'.join(('resources', 'widget.html'))
widget_javascript = pkg_resources.resource_string(
resource_package, javascript_path).decode("utf-8")
widget_css = pkg_resources.resource_string(
resource_package, css_path).decode("utf-8")
app_html_template_string = pkg_resources.resource_string(
resource_package, html_template_path).decode("utf-8")
app_html_template = Template(app_html_template_string)
return app_html_template.render(
widget_css=widget_css,
widget_javascript=widget_javascript,
api_service_environment=json.dumps(api_service_environment),
data=json.dumps(data))
def default_get_instance_metadata(instance_id):
return str(instance_id)
def init_app_routes(app, comparison_manager):
"""
Defines the API for the Flask app.
Args:
app: The Flask app to use for the API.
comparison_manager: The ComparisonManager that will be controlled by the API.
"""
@app.route("/api/v1/instance_data/<int:instance_id>")
@http.no_cache
def get_instance_data(instance_id):
return comparison_manager.get_instance_image(instance_id)
class ModelComparison(object):
"""
Model Comparison widget
The ModelComparison class is an interactive widget intended for use
within a Jupyter Notebook. It provides an interactive UI for the user
that allows the user to:
1. Compare two models h1 and h2 on a dataset with regard to compatibility.
2. The comparison is run by comparing the set of classification errors that h1 and h2
make on the dataset.
3. The Venn Diagram plot within the widget provides a breakdown of the overlap between
the sets of classification errors made by h1 and h2.
4. The bar chart indicates the number of errors made by h2 that are not made by h1
on a per class basis.
5. The error instances table, provides an exploratory view to allow the user to
explore the instances which h1 and h2 have misclassified. This table is linked
to the Venn Diagram and Bar Charts, so that the user may filter the error
instances displayed in the table by clicking on regions of those components.
Args:
h1: The reference model being used.
h2: The model that we want to compare against model h1.
dataset: The list of dataset samples as (batch_ids, input, target). This data needs to be batched.
performance_metric: A function to evaluate model performance. The function is expected to have the following signature:
metric(model, dataset, device)
model: The model being evaluated
dataset: The dataset as a list of (input, target) pairs
device: The device Pytorch is using for training - "cpu" or "cuda"
If unspecified, then accuracy is used.
port: An integer value to indicate the port to which the Flask service
should bind.
get_instance_image_by_id: A function that returns an image representation of the data corresponding to the instance id, in PNG format. It should be a function of the form:
get_instance_image_by_id(instance_id)
instance_id: An integer instance id
And should return a PNG image.
get_instance_metadata: A function that returns a text string representation of some metadata corresponding to the instance id. It should be a function of the form:
get_instance_metadata(instance_id)
instance_id: An integer instance id
And should return a string.
device: A string with values either "cpu" or "cuda" to indicate the
device that Pytorch is performing training on. By default this
value is "cpu". But in case your models reside on the GPU, make sure
to set this to "cuda". This makes sure that the input and target
tensors are transferred to the GPU during training.
"""
def __init__(self, h1, h2, dataset,
performance_metric=model_accuracy,
port=None,
get_instance_image_by_id=None,
get_instance_metadata=None,
device="cpu"):
if get_instance_metadata is None:
get_instance_metadata = default_get_instance_metadata
self.comparison_manager = ComparisonManager(
dataset,
get_instance_image_by_id=get_instance_image_by_id)
self.flask_service = FlaskHelper(ip="0.0.0.0", port=port)
app_has_routes = False
for route in FlaskHelper.app.url_map.iter_rules():
if route.endpoint == 'get_instance_data':
app_has_routes = True
break
if app_has_routes:
FlaskHelper.app.logger.info("Routes already defined. Skipping route initialization.")
else:
FlaskHelper.app.logger.info("Initializing routes")
init_app_routes(FlaskHelper.app, self.comparison_manager)
api_service_environment = build_environment_params(self.flask_service.env)
api_service_environment["port"] = self.flask_service.port
comparison_data = comparison.compare_models(
h1, h2, dataset,
performance_metric=performance_metric,
get_instance_metadata=get_instance_metadata,
device=device)
html_string = render_widget_html(api_service_environment, comparison_data)
self.html_widget = HTML(html_string)
display(self.html_widget)
| 40.39899 | 179 | 0.682835 |
29f1ad99ae00509442ea3babf5d07a9d4e1cf5a3 | 305 | py | Python | 2017/11/midterms-senate-seats-20171107/graphic_config.py | nprapps/graphics-archive | 97b0ef326b46a959df930f5522d325e537f7a655 | [
"FSFAP"
] | 14 | 2015-05-08T13:41:51.000Z | 2021-02-24T12:34:55.000Z | 2017/11/midterms-senate-seats-20171107/graphic_config.py | nprapps/graphics-archive | 97b0ef326b46a959df930f5522d325e537f7a655 | [
"FSFAP"
] | null | null | null | 2017/11/midterms-senate-seats-20171107/graphic_config.py | nprapps/graphics-archive | 97b0ef326b46a959df930f5522d325e537f7a655 | [
"FSFAP"
] | 7 | 2015-04-04T04:45:54.000Z | 2021-02-18T11:12:48.000Z | #!/usr/bin/env python
import base_filters
COPY_GOOGLE_DOC_KEY = '10Bcz3dUqr893Q19IF3sFrOKh1jjcJYy7AOzbtf-XRCQ'
USE_ASSETS = False
# Use these variables to override the default cache timeouts for this graphic
# DEFAULT_MAX_AGE = 20
# ASSETS_MAX_AGE = 300
JINJA_FILTER_FUNCTIONS = base_filters.FILTERS
| 21.785714 | 77 | 0.816393 |
2c56f19b2e9af0619aedfc2f338375537b227bb3 | 9,981 | py | Python | coder/blueprints/billing/gateways/stripecom.py | mikkokotila/coder-1 | c0462fb63bd23d4367a31f86f9c7f29b1ece93bd | [
"MIT"
] | 1 | 2019-03-11T12:44:33.000Z | 2019-03-11T12:44:33.000Z | coder/blueprints/billing/gateways/stripecom.py | mikkokotila/coder-1 | c0462fb63bd23d4367a31f86f9c7f29b1ece93bd | [
"MIT"
] | 1 | 2019-01-02T09:52:17.000Z | 2019-01-02T09:52:17.000Z | coder/blueprints/billing/gateways/stripecom.py | mikkokotila/coder-1 | c0462fb63bd23d4367a31f86f9c7f29b1ece93bd | [
"MIT"
] | 1 | 2019-01-04T12:44:50.000Z | 2019-01-04T12:44:50.000Z | import stripe
class Event(object):
@classmethod
def retrieve(cls, event_id):
"""
Retrieve an event, this is used to validate the event in attempt to
protect us from potentially malicious events not sent from Stripe.
API Documentation:
https://stripe.com/docs/api#retrieve_event
:param event_id: Stripe event id
:type event_id: int
:return: Stripe event
"""
return stripe.Event.retrieve(event_id)
class Customer(object):
@classmethod
def create(cls, token=None, email=None, coupon=None, plan=None):
"""
Create a new customer.
API Documentation:
https://stripe.com/docs/api#create_customer
:param token: Token returned by JavaScript
:type token: str
:param email: E-mail address of the customer
:type email: str
:param coupon: Coupon code
:type coupon: str
:param plan: Plan identifier
:type plan: str
:return: Stripe customer
"""
params = {
'source': token,
'email': email
}
if plan:
params['plan'] = plan
if coupon:
params['coupon'] = coupon
return stripe.Customer.create(**params)
class Charge(object):
@classmethod
def create(cls, customer_id=None, currency=None, amount=None):
"""
Create a new charge.
:param customer_id: Stripe customer id
:type customer_id: int
:param amount: Stripe currency
:type amount: str
:param amount: Amount in cents
:type amount: int
:return: Stripe charge
"""
foo = stripe.Charge.create(
amount=amount,
currency=currency,
customer=customer_id,
statement_descriptor='coder COINS')
print(foo)
return foo
class Coupon(object):
@classmethod
def create(cls, code=None, duration=None, amount_off=None,
percent_off=None, currency=None, duration_in_months=None,
max_redemptions=None, redeem_by=None):
"""
Create a new coupon.
API Documentation:
https://stripe.com/docs/api#create_coupon
:param code: Coupon code
:param duration: How long the coupon will be in effect
:type duration: str
:param amount_off: Discount in a fixed amount
:type amount_off: int
:param percent_off: Discount based on percent off
:type percent_off: int
:param currency: 3 digit currency abbreviation
:type currency: str
:param duration_in_months: Number of months in effect
:type duration_in_months: int
:param max_redemptions: Max number of times it can be redeemed
:type max_redemptions: int
:param redeem_by: Redeemable by this date
:type redeem_by: date
:return: Stripe coupon
"""
return stripe.Coupon.create(id=code,
duration=duration,
amount_off=amount_off,
percent_off=percent_off,
currency=currency,
duration_in_months=duration_in_months,
max_redemptions=max_redemptions,
redeem_by=redeem_by)
@classmethod
def delete(cls, id=None):
"""
Delete an existing coupon.
API Documentation:
https://stripe.com/docs/api#delete_coupon
:param id: Coupon code
:return: Stripe coupon
"""
coupon = stripe.Coupon.retrieve(id)
return coupon.delete()
class Card(object):
@classmethod
def update(cls, customer_id, stripe_token=None):
"""
Update an existing card through a customer.
API Documentation:
https://stripe.com/docs/api/python#update_card
:param customer_id: Stripe customer id
:type customer_id: int
:param stripe_token: Stripe token
:type stripe_token: str
:return: Stripe customer
"""
customer = stripe.Customer.retrieve(customer_id)
customer.source = stripe_token
return customer.save()
class Invoice(object):
@classmethod
def upcoming(cls, customer_id):
"""
Retrieve an upcoming invoice item for a user.
API Documentation:
https://stripe.com/docs/api#retrieve_customer_invoice
:param customer_id: Stripe customer id
:type customer_id: int
:return: Stripe invoice
"""
return stripe.Invoice.upcoming(customer=customer_id)
class Subscription(object):
@classmethod
def update(cls, customer_id=None, coupon=None, plan=None):
"""
Update an existing subscription.
API Documentation:
https://stripe.com/docs/api/python#update_subscription
:param customer_id: Customer id
:type customer_id: str
:param coupon: Coupon code
:type coupon: str
:param plan: Plan identifier
:type plan: str
:return: Stripe subscription
"""
customer = stripe.Customer.retrieve(customer_id)
subscription_id = customer.subscriptions.data[0].id
subscription = customer.subscriptions.retrieve(subscription_id)
subscription.plan = plan
if coupon:
subscription.coupon = coupon
return subscription.save()
@classmethod
def cancel(cls, customer_id=None):
"""
Cancel an existing subscription.
API Documentation:
https://stripe.com/docs/api#cancel_subscription
:param customer_id: Stripe customer id
:type customer_id: int
:return: Stripe subscription object
"""
customer = stripe.Customer.retrieve(customer_id)
subscription_id = customer.subscriptions.data[0].id
return customer.subscriptions.retrieve(subscription_id).delete()
class Plan(object):
@classmethod
def retrieve(cls, plan):
"""
Retrieve an existing plan.
API Documentation:
https://stripe.com/docs/api#retrieve_plan
:param plan: Plan identifier
:type plan: str
:return: Stripe plan
"""
try:
return stripe.Plan.retrieve(plan)
except stripe.error.StripeError as e:
print(e)
@classmethod
def list(cls):
"""
List all plans.
API Documentation:
https://stripe.com/docs/api#list_plans
:return: Stripe plans
"""
try:
return stripe.Plan.all()
except stripe.error.StripeError as e:
print(e)
@classmethod
def create(cls, id=None, name=None, amount=None, currency=None,
interval=None, interval_count=None, trial_period_days=None,
metadata=None, statement_descriptor=None):
"""
Create a new plan.
API Documentation:
https://stripe.com/docs/api#create_plan
:param id: Plan identifier
:type id: str
:param name: Plan name
:type name: str
:param amount: Amount in cents to charge or 0 for a free plan
:type amount: int
:param currency: 3 digit currency abbreviation
:type currency: str
:param interval: Billing frequency
:type interval: str
:param interval_count: Number of intervals between each bill
:type interval_count: int
:param trial_period_days: Number of days to run a free trial
:type trial_period_days: int
:param metadata: Additional data to save with the plan
:type metadata: dct
:param statement_descriptor: Arbitrary string to appear on CC statement
:type statement_descriptor: str
:return: Stripe plan
"""
try:
return stripe.Plan.create(id=id,
name=name,
amount=amount,
currency=currency,
interval=interval,
interval_count=interval_count,
trial_period_days=trial_period_days,
metadata=metadata,
statement_descriptor=statement_descriptor
)
except stripe.error.StripeError as e:
print(e)
@classmethod
def update(cls, id=None, name=None, metadata=None,
statement_descriptor=None):
"""
Update an existing plan.
API Documentation:
https://stripe.com/docs/api#update_plan
:param id: Plan identifier
:type id: str
:param name: Plan name
:type name: str
:param metadata: Additional data to save with the plan
:type metadata: dct
:param statement_descriptor: Arbitrary string to appear on CC statement
:type statement_descriptor: str
:return: Stripe plan
"""
try:
plan = stripe.Plan.retrieve(id)
plan.name = name
plan.metadata = metadata
plan.statement_descriptor = statement_descriptor
return plan.save()
except stripe.error.StripeError as e:
print(e)
@classmethod
def delete(cls, plan):
"""
Delete an existing plan.
API Documentation:
https://stripe.com/docs/api#delete_plan
:param plan: Plan identifier
:type plan: str
:return: Stripe plan object
"""
try:
plan = stripe.Plan.retrieve(plan)
return plan.delete()
except stripe.error.StripeError as e:
print(e)
| 29.617211 | 79 | 0.574992 |
873f5dfcaf6da97e7b73067d8813c31fa94f21fa | 12,072 | py | Python | CMW7 Generic/5130_irf-config.py | manpowertw/leafspine-ops | 59309bed802e6d11c7c801f893adfd9b188222b6 | [
"Apache-2.0"
] | 32 | 2016-05-24T23:32:02.000Z | 2021-11-17T07:53:50.000Z | CMW7 Generic/5130_irf-config.py | manpowertw/leafspine-ops | 59309bed802e6d11c7c801f893adfd9b188222b6 | [
"Apache-2.0"
] | 5 | 2016-09-25T15:55:02.000Z | 2018-09-06T10:54:45.000Z | CMW7 Generic/5130_irf-config.py | manpowertw/leafspine-ops | 59309bed802e6d11c7c801f893adfd9b188222b6 | [
"Apache-2.0"
] | 34 | 2016-03-02T17:37:07.000Z | 2021-11-17T07:54:04.000Z |
__author__ = 'Remi Batist / AXEZ ICT Solutions'
__version__ = '2.3'
__comments__= 'remi.batist@axez.nl'
### Deploying (IRF-)(iMC-)config and software on HP5130 24/48 Ports PoE Switches #########
### Support for models JG936A & JG937A
### version 1.0: first release (support for 6 members)
### version 1.1: adding support for 9 members
### version 1.2: compacting script
### version 1.3: supporting autodeploy IMC
### version 2.0: Changed to deploy with only one 'main' menu
### Version 2.1: Bugfixes
### Version 2.2: added "How to use the script"
### Version 2.3: Changed SNMP Community to support iMC version 7.2
### imc_snmpread = 'iMCV5read' -> 'iMCread'
### imc_snmpwrite = 'iMCV5write' -> 'iMCwrite'
###
### How to use de script;
### 1) On the HP IMC server(or other tftp-srver), put this script in the "%IMC Install Folder%\server\tmp" folder.
### 2) Set the DHCP-Server in the "deploy" network with this script as bootfile. Example on a Comware devices below.
### dhcp enable
### dhcp server forbid 10.0.1.1 10.0.1.200
### dhcp server ip-pool v1
### gateway 10.0.1.1
### bootfile-name 5130_irf-config.py
### tftp-server ip 10.0.1.100
### network 10.0.1.0 24
### 3) Boot a switch without a config-file and connect it to the "deploy" network.
### I build this script to support additional members when auto-deploying HP5130-PoE-switches with HP iMC.
### Why ?
### Normally when deploying the first member of an IRF-stack with HP iMC, the switch is always added as a managed device in HP iMC.
### Then if you want to auto-deploy another "member" of the same stack this procedure is failing, because it's already added in iMC...
### In this script I give you the choice for updating switch-software, poe-software and the changing IRF-member-ID.
### It also support the different member-deploy-scenarios by chosing between the IRF-port-config or iMC-auto-deploy.
### EXAMPLE:
### Current Switch Model 48 Ports
### Current Software version H3C Comware Software, Version 7.1.059, Alpha 7159
### Current PoE version Version 143
### Current Member ID 1
### New Member ID 5
### 1.Update Switch Firmware [ X ]
### 2.Update PoE Firmware [ X ]
### 3.Change IRF MemberID Only [ X ]
### 4.Change IRF MemberID and set IRF-Port-config [ ]
### 5.Trigger iMC for deployment [ X ]
### 6.Run selection
### 7.Exit/Quit and reboot
### For faster deploy the IRF-Port-config is configured by a custom value, see settings below
### 48 Ports IRF-Config
### IRF Port Interface
### 1 Ten-GigabitEthernetX/0/49 (irf_48_port_1)
### 2 Ten-GigabitEthernetX/0/51 (irf_48_port_2)
### 24 Ports IRF-Config
### IRF Port Interface
### 1 Ten-GigabitEthernetX/0/25 (irf_24_port_1)
### 2 Ten-GigabitEthernetX/0/27 (irf_24_port_2)
### You can change this or other custom settings below when needed
#### Custom settings
tftpsrv = "10.0.1.100"
imc_bootfile = "autocfg_startup.cfg"
imc_snmpread = 'iMCread'
imc_snmpwrite = 'iMCwrite'
bootfile = "5130ei-cmw710-boot-r3109p05.bin"
sysfile = "5130ei-cmw710-system-r3109p05.bin"
poefile = "S5130EI-POE-145.bin"
irf_48_port_1 = "/0/49"
irf_48_port_2 = "/0/51"
irf_24_port_1 = "/0/25"
irf_24_port_2 = "/0/27"
poe_pse_numbers = {"1":"4","2":"7","3":"10","4":"13","5":"16","6":"19","7":"22","8":"25","9":"26"}
irf_prio_numbers = {"1":"32","2":"31","3":"30","4":"29","5":"28","6":"27","7":"26","8":"25","9":"24"}
#### Importing python modules
import comware
import sys
import time
import termios
#### RAW user-input module
fd = sys.stdin.fileno();
new = termios.tcgetattr(fd)
new[3] = new[3] | termios.ICANON | termios.ECHO
new[6] [termios.VMIN] = 1
new[6] [termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, new)
termios.tcsendbreak(fd,0)
#### Notification for Starting
print (('\n' * 5) + "Starting script for deploying IRF-config and software on 5130 switches\n"
"\nPlease wait while getting the current settings...."
)
#### Getting Current settings and versions
def SwitchInput():
sys.stdout.write("\r%d%%" % 0)
sys.stdout.flush()
#### Get Current IRF Member
get_memberid = comware.CLI('display irf link', False).get_output()
for line in get_memberid:
if 'Member' in line:
s1 = line.rindex('Member') + 7
e1 = len(line)
memberid = line[s1:e1]
sys.stdout.write("\r%d%%" % 25)
sys.stdout.flush()
#### Get SwitchModel
get_model = comware.CLI('display int ten brief', False).get_output()
for line in get_model:
if '/0/28' in line:
model = "24 Ports"
if '/0/52' in line:
model = "48 Ports"
sys.stdout.write("\r%d%%" % 50)
sys.stdout.flush()
#### Get Mac-address
get_mac_address = comware.CLI('dis device manuinfo | in MAC_ADDRESS', False).get_output()
for line in get_mac_address:
if 'MAC_ADDRESS' in line:
s2 = line.rindex('MAC_ADDRESS') + 23
e2 = len(line)
mac_address = line[s2:e2]
#### Get Switch Software Version
get_sw_version = comware.CLI('display version | in Software', False).get_output()
sw_version = get_sw_version[1]
sys.stdout.write("\r%d%%" % 75)
sys.stdout.flush()
#### Get PoE Software Version
comware.CLI('system ; poe enable pse ' + str(poe_pse_numbers[memberid]), False).get_output()
get_poe_version = comware.CLI('display poe pse | in Software', False).get_output()
for line in get_poe_version:
if 'Software' in line:
s3 = line.rindex('Software') + 31
e3 = len(line)
poe_version = line[s3:e3]
sys.stdout.write("\r%d%%\n" % 100)
sys.stdout.flush()
return memberid, model, mac_address, sw_version, poe_version
#### Startmenu for deploying the switch
def StartMenu(memberid, model, mac_address, sw_version, poe_version):
checkbox1 = ''
checkbox2 = ''
checkbox3 = ''
checkbox4 = ''
checkbox5 = ''
set_memberid = ''
Menu = True
while Menu:
print "\nCurrent Switch Information:"
print " Current Switch Model " + str(model)
print " Current MAC-Address " + str(mac_address)
print " Current Software Version " + str(sw_version)
print " Current PoE Version " + str(poe_version)
print " Current Member ID " + str(memberid)
print " Newly chosen Member ID " + str(set_memberid)
print "\nFiles Ready for installation:"
print " Switch Software File " + str(sysfile)
print " Switch PoE Software File " + str(poefile)
print "\n\n%-50s %-1s %-1s %-1s" % ("1.Update Switch Firmware", "[", checkbox1, "]")
print "%-50s %-1s %-1s %-1s" % ("2.Update PoE Firmware", "[", checkbox2, "]")
print "%-50s %-1s %-1s %-1s" % ("3.Change IRF MemberID Only", "[", checkbox3, "]")
print "%-50s %-1s %-1s %-1s" % ("4.Change IRF MemberID and set IRF-Port-config", "[", checkbox4, "]")
print "%-50s %-1s %-1s %-1s" % ("5.Trigger iMC for deployment", "[", checkbox5, "]")
print "%-50s " % ("6.Run selection")
print "%-50s " % ("7.Restart Automatic Configuration")
print "%-50s " % ("8.Exit/Quit and reboot")
ans=raw_input("\nWhat would you like to do? ")
if ans=="1":
checkbox1 = "X"
elif ans=="2":
checkbox2 = "X"
elif ans=="3":
set_memberid = raw_input("Enter new Member-ID: ")
checkbox3 = "X"
elif ans=="4":
set_memberid = raw_input("Enter new Member-ID: ")
checkbox3 = "X"
checkbox4 = "X"
checkbox5 = ""
elif ans=="5":
checkbox4 = ""
checkbox5 = "X"
elif ans=="6":
Menu = False
elif ans=="7":
print "\nQuiting script...\n"
sys.exit()
elif ans=="8":
print "\nQuiting script and rebooting...\n"
comware.CLI("reboot force")
sys.exit()
else:
print("\n Not Valid Choice Try again")
return checkbox1, checkbox2, checkbox3, checkbox4, checkbox5, set_memberid
#### Switch software update
def SoftwareUpdate(checkbox1):
if checkbox1 == "X":
print "\nUpdating Switch Firmware....\n"
try:
comware.CLI("tftp " + tftpsrv + " get " + bootfile)
print "\nSwitch Firmware download successful\n"
except SystemError as s:
print "\nSwitch Firmware download successful\n"
try:
comware.CLI("tftp " + tftpsrv + " get " + sysfile)
print "\nSwitch Firmware download successful\n"
except SystemError as s:
print "\nSwitch Firmware download successful\n"
try:
comware.CLI("boot-loader file boot flash:/" + bootfile + " system flash:/" + sysfile + " all main")
print "\nConfiguring boot-loader successful\n"
except SystemError as s:
print "\nChange bootloader successful\n"
else:
print "\nSkipping Switch Firmware update"
#### Switch poe update
def PoEUpdate(checkbox2, memberid):
if checkbox2 == 'X':
try:
comware.CLI("tftp " + tftpsrv + " get " + poefile)
print "\nPoE Firmware download successful\n"
except SystemError as s:
print "\nPoE Firmware download successful\n"
try:
print "\nUpdating PoE Firmware..."
comware.CLI("system ; poe update full " + poefile + " pse " + str(poe_pse_numbers[memberid]))
print "\nPoE-Update successful\n"
except SystemError as s:
print "\nSkipping PoE-Update, member not available\n"
else:
print "\nSkipping PoE firmware update"
#### Change IRF MemberID
def ChangeIRFMemberID(memberid, checkbox3, set_memberid):
if checkbox3 == 'X':
print "\nChanging IRF MemberID..."
comware.CLI("system ; irf member " + memberid + " renumber " + set_memberid)
else:
print "\nskipping IRF MemberID Change"
#### Set IRFPorts in startup config
def SetIRFPorts(memberid, model, checkbox3, checkbox4, set_memberid):
if checkbox4 == 'X':
if model == "48 Ports":
print ('\n' * 5) + 'Deploying IRF-Port-config for 48 ports switch...\n'
if model == "24 Ports":
print ('\n' * 5) + 'Deploying IRF-Port-config for 24 ports switch...\n'
set_prio = irf_prio_numbers[set_memberid]
startup_file = open('flash:/startup.cfg', 'w')
startup_file.write("\nirf member "+ set_memberid +" priority "+ set_prio + "\n")
if model == "48 Ports":
startup_file.write("\nirf-port "+ set_memberid +"/1")
startup_file.write("\nport group interface Ten-GigabitEthernet"+ set_memberid + irf_48_port_1 + '\n')
startup_file.write("\nirf-port "+ set_memberid +"/2")
startup_file.write("\nport group interface Ten-GigabitEthernet"+ set_memberid + irf_48_port_2 + '\n')
if model == "24 Ports":
startup_file.write("\nirf-port "+ set_memberid +"/1")
startup_file.write("\nport group interface Ten-GigabitEthernet"+ set_memberid + irf_24_port_1 + '\n')
startup_file.write("\nirf-port "+ set_memberid +"/2")
startup_file.write("\nport group interface Ten-GigabitEthernet"+ set_memberid + irf_24_port_2 + '\n')
startup_file.close()
comware.CLI("startup saved-configuration startup.cfg")
comware.CLI("reboot force")
else:
print "\nSkipping IRF-Port-config"
#### Trigger iMC for auto-deployment
def TriggeriMC(checkbox5):
if checkbox5 == 'X':
print "\nTriggering iMC for deploy, please wait..."
comware.CLI('system ; snmp-agent ; snmp-agent community read ' + imc_snmpread + ' ; snmp-agent community write ' + imc_snmpwrite + ' ; snmp-agent sys-info version all', False)
comware.CLI('tftp ' + tftpsrv + ' get ' + imc_bootfile + ' tmp.cfg')
print "\nSuccess, waiting for config..."
time.sleep(300)
else:
print "\nSkipping iMC deploy"
#### Define main function
def main():
(memberid, model, mac_address, sw_version, poe_version) = SwitchInput()
(checkbox1, checkbox2, checkbox3, checkbox4, checkbox5, set_memberid) = StartMenu(memberid, model, mac_address, sw_version, poe_version)
SoftwareUpdate(checkbox1)
PoEUpdate(checkbox2, memberid)
ChangeIRFMemberID(memberid, checkbox3, set_memberid)
SetIRFPorts(memberid, model, checkbox3, checkbox4, set_memberid)
TriggeriMC(checkbox5)
if __name__ == "__main__":
main()
| 38.941935 | 177 | 0.64952 |
bdd37c99df0a835565ebae80b9bd1c5d4d52c702 | 114,968 | py | Python | python/pyspark/ml/classification.py | adamtobey/spark | 20cd47e82d7d84516455df960ededbd647694aa5 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-07-01T04:44:36.000Z | 2020-07-01T04:44:36.000Z | python/pyspark/ml/classification.py | adamtobey/spark | 20cd47e82d7d84516455df960ededbd647694aa5 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2017-03-10T03:47:48.000Z | 2020-06-29T00:02:52.000Z | python/pyspark/ml/classification.py | adamtobey/spark | 20cd47e82d7d84516455df960ededbd647694aa5 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import operator
import sys
from abc import ABCMeta, abstractmethod, abstractproperty
from multiprocessing.pool import ThreadPool
from pyspark import since, keyword_only
from pyspark.ml import Estimator, Predictor, PredictionModel, Model
from pyspark.ml.param.shared import *
from pyspark.ml.tree import _DecisionTreeModel, _DecisionTreeParams, \
_TreeEnsembleModel, _RandomForestParams, _GBTParams, \
_HasVarianceImpurity, _TreeClassifierParams, _TreeEnsembleParams
from pyspark.ml.regression import _FactorizationMachinesParams, DecisionTreeRegressionModel
from pyspark.ml.util import *
from pyspark.ml.base import _PredictorParams
from pyspark.ml.wrapper import JavaEstimator, JavaModel, JavaParams, \
JavaPredictor, JavaPredictionModel, JavaWrapper
from pyspark.ml.common import inherit_doc, _java2py, _py2java
from pyspark.ml.linalg import Vectors
from pyspark.sql import DataFrame
from pyspark.sql.functions import udf, when
from pyspark.sql.types import ArrayType, DoubleType
from pyspark.storagelevel import StorageLevel
__all__ = ['LinearSVC', 'LinearSVCModel',
'LinearSVCSummary', 'LinearSVCTrainingSummary',
'LogisticRegression', 'LogisticRegressionModel',
'LogisticRegressionSummary', 'LogisticRegressionTrainingSummary',
'BinaryLogisticRegressionSummary', 'BinaryLogisticRegressionTrainingSummary',
'DecisionTreeClassifier', 'DecisionTreeClassificationModel',
'GBTClassifier', 'GBTClassificationModel',
'RandomForestClassifier', 'RandomForestClassificationModel',
'NaiveBayes', 'NaiveBayesModel',
'MultilayerPerceptronClassifier', 'MultilayerPerceptronClassificationModel',
'OneVsRest', 'OneVsRestModel',
'FMClassifier', 'FMClassificationModel']
class _ClassifierParams(HasRawPredictionCol, _PredictorParams):
"""
Classifier Params for classification tasks.
.. versionadded:: 3.0.0
"""
pass
@inherit_doc
class Classifier(Predictor, _ClassifierParams):
"""
Classifier for classification tasks.
Classes are indexed {0, 1, ..., numClasses - 1}.
"""
__metaclass__ = ABCMeta
@since("3.0.0")
def setRawPredictionCol(self, value):
"""
Sets the value of :py:attr:`rawPredictionCol`.
"""
return self._set(rawPredictionCol=value)
@inherit_doc
class ClassificationModel(PredictionModel, _ClassifierParams):
"""
Model produced by a ``Classifier``.
Classes are indexed {0, 1, ..., numClasses - 1}.
"""
__metaclass__ = ABCMeta
@since("3.0.0")
def setRawPredictionCol(self, value):
"""
Sets the value of :py:attr:`rawPredictionCol`.
"""
return self._set(rawPredictionCol=value)
@abstractproperty
@since("2.1.0")
def numClasses(self):
"""
Number of classes (values which the label can take).
"""
raise NotImplementedError()
@abstractmethod
@since("3.0.0")
def predictRaw(self, value):
"""
Raw prediction for each possible label.
"""
raise NotImplementedError()
class _ProbabilisticClassifierParams(HasProbabilityCol, HasThresholds, _ClassifierParams):
"""
Params for :py:class:`ProbabilisticClassifier` and
:py:class:`ProbabilisticClassificationModel`.
.. versionadded:: 3.0.0
"""
pass
@inherit_doc
class ProbabilisticClassifier(Classifier, _ProbabilisticClassifierParams):
"""
Probabilistic Classifier for classification tasks.
"""
__metaclass__ = ABCMeta
@since("3.0.0")
def setProbabilityCol(self, value):
"""
Sets the value of :py:attr:`probabilityCol`.
"""
return self._set(probabilityCol=value)
@since("3.0.0")
def setThresholds(self, value):
"""
Sets the value of :py:attr:`thresholds`.
"""
return self._set(thresholds=value)
@inherit_doc
class ProbabilisticClassificationModel(ClassificationModel,
_ProbabilisticClassifierParams):
"""
Model produced by a ``ProbabilisticClassifier``.
"""
__metaclass__ = ABCMeta
@since("3.0.0")
def setProbabilityCol(self, value):
"""
Sets the value of :py:attr:`probabilityCol`.
"""
return self._set(probabilityCol=value)
@since("3.0.0")
def setThresholds(self, value):
"""
Sets the value of :py:attr:`thresholds`.
"""
return self._set(thresholds=value)
@abstractmethod
@since("3.0.0")
def predictProbability(self, value):
"""
Predict the probability of each class given the features.
"""
raise NotImplementedError()
@inherit_doc
class _JavaClassifier(Classifier, JavaPredictor):
"""
Java Classifier for classification tasks.
Classes are indexed {0, 1, ..., numClasses - 1}.
"""
__metaclass__ = ABCMeta
@since("3.0.0")
def setRawPredictionCol(self, value):
"""
Sets the value of :py:attr:`rawPredictionCol`.
"""
return self._set(rawPredictionCol=value)
@inherit_doc
class _JavaClassificationModel(ClassificationModel, JavaPredictionModel):
"""
Java Model produced by a ``Classifier``.
Classes are indexed {0, 1, ..., numClasses - 1}.
To be mixed in with :class:`pyspark.ml.JavaModel`
"""
@property
@since("2.1.0")
def numClasses(self):
"""
Number of classes (values which the label can take).
"""
return self._call_java("numClasses")
@since("3.0.0")
def predictRaw(self, value):
"""
Raw prediction for each possible label.
"""
return self._call_java("predictRaw", value)
@inherit_doc
class _JavaProbabilisticClassifier(ProbabilisticClassifier, _JavaClassifier):
"""
Java Probabilistic Classifier for classification tasks.
"""
__metaclass__ = ABCMeta
@inherit_doc
class _JavaProbabilisticClassificationModel(ProbabilisticClassificationModel,
_JavaClassificationModel):
"""
Java Model produced by a ``ProbabilisticClassifier``.
"""
@since("3.0.0")
def predictProbability(self, value):
"""
Predict the probability of each class given the features.
"""
return self._call_java("predictProbability", value)
@inherit_doc
class _ClassificationSummary(JavaWrapper):
"""
Abstraction for multiclass classification results for a given model.
.. versionadded:: 3.1.0
"""
@property
@since("3.1.0")
def predictions(self):
"""
Dataframe outputted by the model's `transform` method.
"""
return self._call_java("predictions")
@property
@since("3.1.0")
def predictionCol(self):
"""
Field in "predictions" which gives the prediction of each class.
"""
return self._call_java("predictionCol")
@property
@since("3.1.0")
def labelCol(self):
"""
Field in "predictions" which gives the true label of each
instance.
"""
return self._call_java("labelCol")
@property
@since("3.1.0")
def weightCol(self):
"""
Field in "predictions" which gives the weight of each instance
as a vector.
"""
return self._call_java("weightCol")
@property
@since("3.1.0")
def labels(self):
"""
Returns the sequence of labels in ascending order. This order matches the order used
in metrics which are specified as arrays over labels, e.g., truePositiveRateByLabel.
Note: In most cases, it will be values {0.0, 1.0, ..., numClasses-1}, However, if the
training set is missing a label, then all of the arrays over labels
(e.g., from truePositiveRateByLabel) will be of length numClasses-1 instead of the
expected numClasses.
"""
return self._call_java("labels")
@property
@since("3.1.0")
def truePositiveRateByLabel(self):
"""
Returns true positive rate for each label (category).
"""
return self._call_java("truePositiveRateByLabel")
@property
@since("3.1.0")
def falsePositiveRateByLabel(self):
"""
Returns false positive rate for each label (category).
"""
return self._call_java("falsePositiveRateByLabel")
@property
@since("3.1.0")
def precisionByLabel(self):
"""
Returns precision for each label (category).
"""
return self._call_java("precisionByLabel")
@property
@since("3.1.0")
def recallByLabel(self):
"""
Returns recall for each label (category).
"""
return self._call_java("recallByLabel")
@since("3.1.0")
def fMeasureByLabel(self, beta=1.0):
"""
Returns f-measure for each label (category).
"""
return self._call_java("fMeasureByLabel", beta)
@property
@since("3.1.0")
def accuracy(self):
"""
Returns accuracy.
(equals to the total number of correctly classified instances
out of the total number of instances.)
"""
return self._call_java("accuracy")
@property
@since("3.1.0")
def weightedTruePositiveRate(self):
"""
Returns weighted true positive rate.
(equals to precision, recall and f-measure)
"""
return self._call_java("weightedTruePositiveRate")
@property
@since("3.1.0")
def weightedFalsePositiveRate(self):
"""
Returns weighted false positive rate.
"""
return self._call_java("weightedFalsePositiveRate")
@property
@since("3.1.0")
def weightedRecall(self):
"""
Returns weighted averaged recall.
(equals to precision, recall and f-measure)
"""
return self._call_java("weightedRecall")
@property
@since("3.1.0")
def weightedPrecision(self):
"""
Returns weighted averaged precision.
"""
return self._call_java("weightedPrecision")
@since("3.1.0")
def weightedFMeasure(self, beta=1.0):
"""
Returns weighted averaged f-measure.
"""
return self._call_java("weightedFMeasure", beta)
@inherit_doc
class _TrainingSummary(JavaWrapper):
"""
Abstraction for Training results.
.. versionadded:: 3.1.0
"""
@property
@since("3.1.0")
def objectiveHistory(self):
"""
Objective function (scaled loss + regularization) at each
iteration. It contains one more element, the initial state,
than number of iterations.
"""
return self._call_java("objectiveHistory")
@property
@since("3.1.0")
def totalIterations(self):
"""
Number of training iterations until termination.
"""
return self._call_java("totalIterations")
@inherit_doc
class _BinaryClassificationSummary(_ClassificationSummary):
"""
Binary classification results for a given model.
.. versionadded:: 3.1.0
"""
@property
@since("3.1.0")
def scoreCol(self):
"""
Field in "predictions" which gives the probability or raw prediction
of each class as a vector.
"""
return self._call_java("scoreCol")
@property
@since("3.1.0")
def roc(self):
"""
Returns the receiver operating characteristic (ROC) curve,
which is a Dataframe having two fields (FPR, TPR) with
(0.0, 0.0) prepended and (1.0, 1.0) appended to it.
.. seealso:: `Wikipedia reference
<http://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_
"""
return self._call_java("roc")
@property
@since("3.1.0")
def areaUnderROC(self):
"""
Computes the area under the receiver operating characteristic
(ROC) curve.
"""
return self._call_java("areaUnderROC")
@property
@since("3.1.0")
def pr(self):
"""
Returns the precision-recall curve, which is a Dataframe
containing two fields recall, precision with (0.0, 1.0) prepended
to it.
"""
return self._call_java("pr")
@property
@since("3.1.0")
def fMeasureByThreshold(self):
"""
Returns a dataframe with two fields (threshold, F-Measure) curve
with beta = 1.0.
"""
return self._call_java("fMeasureByThreshold")
@property
@since("3.1.0")
def precisionByThreshold(self):
"""
Returns a dataframe with two fields (threshold, precision) curve.
Every possible probability obtained in transforming the dataset
are used as thresholds used in calculating the precision.
"""
return self._call_java("precisionByThreshold")
@property
@since("3.1.0")
def recallByThreshold(self):
"""
Returns a dataframe with two fields (threshold, recall) curve.
Every possible probability obtained in transforming the dataset
are used as thresholds used in calculating the recall.
"""
return self._call_java("recallByThreshold")
class _LinearSVCParams(_ClassifierParams, HasRegParam, HasMaxIter, HasFitIntercept, HasTol,
HasStandardization, HasWeightCol, HasAggregationDepth, HasThreshold,
HasBlockSize):
"""
Params for :py:class:`LinearSVC` and :py:class:`LinearSVCModel`.
.. versionadded:: 3.0.0
"""
threshold = Param(Params._dummy(), "threshold",
"The threshold in binary classification applied to the linear model"
" prediction. This threshold can be any real number, where Inf will make"
" all predictions 0.0 and -Inf will make all predictions 1.0.",
typeConverter=TypeConverters.toFloat)
@inherit_doc
class LinearSVC(_JavaClassifier, _LinearSVCParams, JavaMLWritable, JavaMLReadable):
"""
`Linear SVM Classifier <https://en.wikipedia.org/wiki/Support_vector_machine#Linear_SVM>`_
This binary classifier optimizes the Hinge Loss using the OWLQN optimizer.
Only supports L2 regularization currently.
>>> from pyspark.sql import Row
>>> from pyspark.ml.linalg import Vectors
>>> df = sc.parallelize([
... Row(label=1.0, features=Vectors.dense(1.0, 1.0, 1.0)),
... Row(label=0.0, features=Vectors.dense(1.0, 2.0, 3.0))]).toDF()
>>> svm = LinearSVC()
>>> svm.getMaxIter()
100
>>> svm.setMaxIter(5)
LinearSVC...
>>> svm.getMaxIter()
5
>>> svm.getRegParam()
0.0
>>> svm.setRegParam(0.01)
LinearSVC...
>>> svm.getRegParam()
0.01
>>> model = svm.fit(df)
>>> model.setPredictionCol("newPrediction")
LinearSVCModel...
>>> model.getPredictionCol()
'newPrediction'
>>> model.setThreshold(0.5)
LinearSVCModel...
>>> model.getThreshold()
0.5
>>> model.getBlockSize()
1
>>> model.coefficients
DenseVector([0.0, -0.2792, -0.1833])
>>> model.intercept
1.0206118982229047
>>> model.numClasses
2
>>> model.numFeatures
3
>>> test0 = sc.parallelize([Row(features=Vectors.dense(-1.0, -1.0, -1.0))]).toDF()
>>> model.predict(test0.head().features)
1.0
>>> model.predictRaw(test0.head().features)
DenseVector([-1.4831, 1.4831])
>>> result = model.transform(test0).head()
>>> result.newPrediction
1.0
>>> result.rawPrediction
DenseVector([-1.4831, 1.4831])
>>> svm_path = temp_path + "/svm"
>>> svm.save(svm_path)
>>> svm2 = LinearSVC.load(svm_path)
>>> svm2.getMaxIter()
5
>>> model_path = temp_path + "/svm_model"
>>> model.save(model_path)
>>> model2 = LinearSVCModel.load(model_path)
>>> model.coefficients[0] == model2.coefficients[0]
True
>>> model.intercept == model2.intercept
True
.. versionadded:: 2.2.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, regParam=0.0, tol=1e-6, rawPredictionCol="rawPrediction",
fitIntercept=True, standardization=True, threshold=0.0, weightCol=None,
aggregationDepth=2, blockSize=1):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, regParam=0.0, tol=1e-6, rawPredictionCol="rawPrediction", \
fitIntercept=True, standardization=True, threshold=0.0, weightCol=None, \
aggregationDepth=2, blockSize=1):
"""
super(LinearSVC, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.LinearSVC", self.uid)
self._setDefault(maxIter=100, regParam=0.0, tol=1e-6, fitIntercept=True,
standardization=True, threshold=0.0, aggregationDepth=2,
blockSize=1)
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("2.2.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, regParam=0.0, tol=1e-6, rawPredictionCol="rawPrediction",
fitIntercept=True, standardization=True, threshold=0.0, weightCol=None,
aggregationDepth=2, blockSize=1):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, regParam=0.0, tol=1e-6, rawPredictionCol="rawPrediction", \
fitIntercept=True, standardization=True, threshold=0.0, weightCol=None, \
aggregationDepth=2, blockSize=1):
Sets params for Linear SVM Classifier.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return LinearSVCModel(java_model)
@since("2.2.0")
def setMaxIter(self, value):
"""
Sets the value of :py:attr:`maxIter`.
"""
return self._set(maxIter=value)
@since("2.2.0")
def setRegParam(self, value):
"""
Sets the value of :py:attr:`regParam`.
"""
return self._set(regParam=value)
@since("2.2.0")
def setTol(self, value):
"""
Sets the value of :py:attr:`tol`.
"""
return self._set(tol=value)
@since("2.2.0")
def setFitIntercept(self, value):
"""
Sets the value of :py:attr:`fitIntercept`.
"""
return self._set(fitIntercept=value)
@since("2.2.0")
def setStandardization(self, value):
"""
Sets the value of :py:attr:`standardization`.
"""
return self._set(standardization=value)
@since("2.2.0")
def setThreshold(self, value):
"""
Sets the value of :py:attr:`threshold`.
"""
return self._set(threshold=value)
@since("2.2.0")
def setWeightCol(self, value):
"""
Sets the value of :py:attr:`weightCol`.
"""
return self._set(weightCol=value)
@since("2.2.0")
def setAggregationDepth(self, value):
"""
Sets the value of :py:attr:`aggregationDepth`.
"""
return self._set(aggregationDepth=value)
@since("3.1.0")
def setBlockSize(self, value):
"""
Sets the value of :py:attr:`blockSize`.
"""
return self._set(blockSize=value)
class LinearSVCModel(_JavaClassificationModel, _LinearSVCParams, JavaMLWritable, JavaMLReadable,
HasTrainingSummary):
"""
Model fitted by LinearSVC.
.. versionadded:: 2.2.0
"""
@since("3.0.0")
def setThreshold(self, value):
"""
Sets the value of :py:attr:`threshold`.
"""
return self._set(threshold=value)
@property
@since("2.2.0")
def coefficients(self):
"""
Model coefficients of Linear SVM Classifier.
"""
return self._call_java("coefficients")
@property
@since("2.2.0")
def intercept(self):
"""
Model intercept of Linear SVM Classifier.
"""
return self._call_java("intercept")
@since("3.1.0")
def summary(self):
"""
Gets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model
trained on the training set. An exception is thrown if `trainingSummary is None`.
"""
if self.hasSummary:
return LinearSVCTrainingSummary(super(LinearSVCModel, self).summary)
else:
raise RuntimeError("No training summary available for this %s" %
self.__class__.__name__)
@since("3.1.0")
def evaluate(self, dataset):
"""
Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
if not isinstance(dataset, DataFrame):
raise ValueError("dataset must be a DataFrame but got %s." % type(dataset))
java_lsvc_summary = self._call_java("evaluate", dataset)
return LinearSVCSummary(java_lsvc_summary)
class LinearSVCSummary(_BinaryClassificationSummary):
"""
Abstraction for LinearSVC Results for a given model.
.. versionadded:: 3.1.0
"""
pass
@inherit_doc
class LinearSVCTrainingSummary(LinearSVCSummary, _TrainingSummary):
"""
Abstraction for LinearSVC Training results.
.. versionadded:: 3.1.0
"""
pass
class _LogisticRegressionParams(_ProbabilisticClassifierParams, HasRegParam,
HasElasticNetParam, HasMaxIter, HasFitIntercept, HasTol,
HasStandardization, HasWeightCol, HasAggregationDepth,
HasThreshold, HasBlockSize):
"""
Params for :py:class:`LogisticRegression` and :py:class:`LogisticRegressionModel`.
.. versionadded:: 3.0.0
"""
threshold = Param(Params._dummy(), "threshold",
"Threshold in binary classification prediction, in range [0, 1]." +
" If threshold and thresholds are both set, they must match." +
"e.g. if threshold is p, then thresholds must be equal to [1-p, p].",
typeConverter=TypeConverters.toFloat)
family = Param(Params._dummy(), "family",
"The name of family which is a description of the label distribution to " +
"be used in the model. Supported options: auto, binomial, multinomial",
typeConverter=TypeConverters.toString)
lowerBoundsOnCoefficients = Param(Params._dummy(), "lowerBoundsOnCoefficients",
"The lower bounds on coefficients if fitting under bound "
"constrained optimization. The bound matrix must be "
"compatible with the shape "
"(1, number of features) for binomial regression, or "
"(number of classes, number of features) "
"for multinomial regression.",
typeConverter=TypeConverters.toMatrix)
upperBoundsOnCoefficients = Param(Params._dummy(), "upperBoundsOnCoefficients",
"The upper bounds on coefficients if fitting under bound "
"constrained optimization. The bound matrix must be "
"compatible with the shape "
"(1, number of features) for binomial regression, or "
"(number of classes, number of features) "
"for multinomial regression.",
typeConverter=TypeConverters.toMatrix)
lowerBoundsOnIntercepts = Param(Params._dummy(), "lowerBoundsOnIntercepts",
"The lower bounds on intercepts if fitting under bound "
"constrained optimization. The bounds vector size must be"
"equal with 1 for binomial regression, or the number of"
"lasses for multinomial regression.",
typeConverter=TypeConverters.toVector)
upperBoundsOnIntercepts = Param(Params._dummy(), "upperBoundsOnIntercepts",
"The upper bounds on intercepts if fitting under bound "
"constrained optimization. The bound vector size must be "
"equal with 1 for binomial regression, or the number of "
"classes for multinomial regression.",
typeConverter=TypeConverters.toVector)
@since("1.4.0")
def setThreshold(self, value):
"""
Sets the value of :py:attr:`threshold`.
Clears value of :py:attr:`thresholds` if it has been set.
"""
self._set(threshold=value)
self.clear(self.thresholds)
return self
@since("1.4.0")
def getThreshold(self):
"""
Get threshold for binary classification.
If :py:attr:`thresholds` is set with length 2 (i.e., binary classification),
this returns the equivalent threshold:
:math:`\\frac{1}{1 + \\frac{thresholds(0)}{thresholds(1)}}`.
Otherwise, returns :py:attr:`threshold` if set or its default value if unset.
"""
self._checkThresholdConsistency()
if self.isSet(self.thresholds):
ts = self.getOrDefault(self.thresholds)
if len(ts) != 2:
raise ValueError("Logistic Regression getThreshold only applies to" +
" binary classification, but thresholds has length != 2." +
" thresholds: " + ",".join(ts))
return 1.0/(1.0 + ts[0]/ts[1])
else:
return self.getOrDefault(self.threshold)
@since("1.5.0")
def setThresholds(self, value):
"""
Sets the value of :py:attr:`thresholds`.
Clears value of :py:attr:`threshold` if it has been set.
"""
self._set(thresholds=value)
self.clear(self.threshold)
return self
@since("1.5.0")
def getThresholds(self):
"""
If :py:attr:`thresholds` is set, return its value.
Otherwise, if :py:attr:`threshold` is set, return the equivalent thresholds for binary
classification: (1-threshold, threshold).
If neither are set, throw an error.
"""
self._checkThresholdConsistency()
if not self.isSet(self.thresholds) and self.isSet(self.threshold):
t = self.getOrDefault(self.threshold)
return [1.0-t, t]
else:
return self.getOrDefault(self.thresholds)
def _checkThresholdConsistency(self):
if self.isSet(self.threshold) and self.isSet(self.thresholds):
ts = self.getOrDefault(self.thresholds)
if len(ts) != 2:
raise ValueError("Logistic Regression getThreshold only applies to" +
" binary classification, but thresholds has length != 2." +
" thresholds: {0}".format(str(ts)))
t = 1.0/(1.0 + ts[0]/ts[1])
t2 = self.getOrDefault(self.threshold)
if abs(t2 - t) >= 1E-5:
raise ValueError("Logistic Regression getThreshold found inconsistent values for" +
" threshold (%g) and thresholds (equivalent to %g)" % (t2, t))
@since("2.1.0")
def getFamily(self):
"""
Gets the value of :py:attr:`family` or its default value.
"""
return self.getOrDefault(self.family)
@since("2.3.0")
def getLowerBoundsOnCoefficients(self):
"""
Gets the value of :py:attr:`lowerBoundsOnCoefficients`
"""
return self.getOrDefault(self.lowerBoundsOnCoefficients)
@since("2.3.0")
def getUpperBoundsOnCoefficients(self):
"""
Gets the value of :py:attr:`upperBoundsOnCoefficients`
"""
return self.getOrDefault(self.upperBoundsOnCoefficients)
@since("2.3.0")
def getLowerBoundsOnIntercepts(self):
"""
Gets the value of :py:attr:`lowerBoundsOnIntercepts`
"""
return self.getOrDefault(self.lowerBoundsOnIntercepts)
@since("2.3.0")
def getUpperBoundsOnIntercepts(self):
"""
Gets the value of :py:attr:`upperBoundsOnIntercepts`
"""
return self.getOrDefault(self.upperBoundsOnIntercepts)
@inherit_doc
class LogisticRegression(_JavaProbabilisticClassifier, _LogisticRegressionParams, JavaMLWritable,
JavaMLReadable):
"""
Logistic regression.
This class supports multinomial logistic (softmax) and binomial logistic regression.
>>> from pyspark.sql import Row
>>> from pyspark.ml.linalg import Vectors
>>> bdf = sc.parallelize([
... Row(label=1.0, weight=1.0, features=Vectors.dense(0.0, 5.0)),
... Row(label=0.0, weight=2.0, features=Vectors.dense(1.0, 2.0)),
... Row(label=1.0, weight=3.0, features=Vectors.dense(2.0, 1.0)),
... Row(label=0.0, weight=4.0, features=Vectors.dense(3.0, 3.0))]).toDF()
>>> blor = LogisticRegression(weightCol="weight")
>>> blor.getRegParam()
0.0
>>> blor.setRegParam(0.01)
LogisticRegression...
>>> blor.getRegParam()
0.01
>>> blor.setMaxIter(10)
LogisticRegression...
>>> blor.getMaxIter()
10
>>> blor.clear(blor.maxIter)
>>> blorModel = blor.fit(bdf)
>>> blorModel.setFeaturesCol("features")
LogisticRegressionModel...
>>> blorModel.setProbabilityCol("newProbability")
LogisticRegressionModel...
>>> blorModel.getProbabilityCol()
'newProbability'
>>> blorModel.getBlockSize()
1
>>> blorModel.setThreshold(0.1)
LogisticRegressionModel...
>>> blorModel.getThreshold()
0.1
>>> blorModel.coefficients
DenseVector([-1.080..., -0.646...])
>>> blorModel.intercept
3.112...
>>> blorModel.evaluate(bdf).accuracy == blorModel.summary.accuracy
True
>>> data_path = "data/mllib/sample_multiclass_classification_data.txt"
>>> mdf = spark.read.format("libsvm").load(data_path)
>>> mlor = LogisticRegression(regParam=0.1, elasticNetParam=1.0, family="multinomial")
>>> mlorModel = mlor.fit(mdf)
>>> mlorModel.coefficientMatrix
SparseMatrix(3, 4, [0, 1, 2, 3], [3, 2, 1], [1.87..., -2.75..., -0.50...], 1)
>>> mlorModel.interceptVector
DenseVector([0.04..., -0.42..., 0.37...])
>>> test0 = sc.parallelize([Row(features=Vectors.dense(-1.0, 1.0))]).toDF()
>>> blorModel.predict(test0.head().features)
1.0
>>> blorModel.predictRaw(test0.head().features)
DenseVector([-3.54..., 3.54...])
>>> blorModel.predictProbability(test0.head().features)
DenseVector([0.028, 0.972])
>>> result = blorModel.transform(test0).head()
>>> result.prediction
1.0
>>> result.newProbability
DenseVector([0.02..., 0.97...])
>>> result.rawPrediction
DenseVector([-3.54..., 3.54...])
>>> test1 = sc.parallelize([Row(features=Vectors.sparse(2, [0], [1.0]))]).toDF()
>>> blorModel.transform(test1).head().prediction
1.0
>>> blor.setParams("vector")
Traceback (most recent call last):
...
TypeError: Method setParams forces keyword arguments.
>>> lr_path = temp_path + "/lr"
>>> blor.save(lr_path)
>>> lr2 = LogisticRegression.load(lr_path)
>>> lr2.getRegParam()
0.01
>>> model_path = temp_path + "/lr_model"
>>> blorModel.save(model_path)
>>> model2 = LogisticRegressionModel.load(model_path)
>>> blorModel.coefficients[0] == model2.coefficients[0]
True
>>> blorModel.intercept == model2.intercept
True
>>> model2
LogisticRegressionModel: uid=..., numClasses=2, numFeatures=2
.. versionadded:: 1.3.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True,
threshold=0.5, thresholds=None, probabilityCol="probability",
rawPredictionCol="rawPrediction", standardization=True, weightCol=None,
aggregationDepth=2, family="auto",
lowerBoundsOnCoefficients=None, upperBoundsOnCoefficients=None,
lowerBoundsOnIntercepts=None, upperBoundsOnIntercepts=None,
blockSize=1):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, \
threshold=0.5, thresholds=None, probabilityCol="probability", \
rawPredictionCol="rawPrediction", standardization=True, weightCol=None, \
aggregationDepth=2, family="auto", \
lowerBoundsOnCoefficients=None, upperBoundsOnCoefficients=None, \
lowerBoundsOnIntercepts=None, upperBoundsOnIntercepts=None, \
blockSize=1):
If the threshold and thresholds Params are both set, they must be equivalent.
"""
super(LogisticRegression, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.LogisticRegression", self.uid)
self._setDefault(maxIter=100, regParam=0.0, tol=1E-6, threshold=0.5, family="auto",
blockSize=1)
kwargs = self._input_kwargs
self.setParams(**kwargs)
self._checkThresholdConsistency()
@keyword_only
@since("1.3.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True,
threshold=0.5, thresholds=None, probabilityCol="probability",
rawPredictionCol="rawPrediction", standardization=True, weightCol=None,
aggregationDepth=2, family="auto",
lowerBoundsOnCoefficients=None, upperBoundsOnCoefficients=None,
lowerBoundsOnIntercepts=None, upperBoundsOnIntercepts=None,
blockSize=1):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, \
threshold=0.5, thresholds=None, probabilityCol="probability", \
rawPredictionCol="rawPrediction", standardization=True, weightCol=None, \
aggregationDepth=2, family="auto", \
lowerBoundsOnCoefficients=None, upperBoundsOnCoefficients=None, \
lowerBoundsOnIntercepts=None, upperBoundsOnIntercepts=None, \
blockSize=1):
Sets params for logistic regression.
If the threshold and thresholds Params are both set, they must be equivalent.
"""
kwargs = self._input_kwargs
self._set(**kwargs)
self._checkThresholdConsistency()
return self
def _create_model(self, java_model):
return LogisticRegressionModel(java_model)
@since("2.1.0")
def setFamily(self, value):
"""
Sets the value of :py:attr:`family`.
"""
return self._set(family=value)
@since("2.3.0")
def setLowerBoundsOnCoefficients(self, value):
"""
Sets the value of :py:attr:`lowerBoundsOnCoefficients`
"""
return self._set(lowerBoundsOnCoefficients=value)
@since("2.3.0")
def setUpperBoundsOnCoefficients(self, value):
"""
Sets the value of :py:attr:`upperBoundsOnCoefficients`
"""
return self._set(upperBoundsOnCoefficients=value)
@since("2.3.0")
def setLowerBoundsOnIntercepts(self, value):
"""
Sets the value of :py:attr:`lowerBoundsOnIntercepts`
"""
return self._set(lowerBoundsOnIntercepts=value)
@since("2.3.0")
def setUpperBoundsOnIntercepts(self, value):
"""
Sets the value of :py:attr:`upperBoundsOnIntercepts`
"""
return self._set(upperBoundsOnIntercepts=value)
def setMaxIter(self, value):
"""
Sets the value of :py:attr:`maxIter`.
"""
return self._set(maxIter=value)
def setRegParam(self, value):
"""
Sets the value of :py:attr:`regParam`.
"""
return self._set(regParam=value)
def setTol(self, value):
"""
Sets the value of :py:attr:`tol`.
"""
return self._set(tol=value)
def setElasticNetParam(self, value):
"""
Sets the value of :py:attr:`elasticNetParam`.
"""
return self._set(elasticNetParam=value)
def setFitIntercept(self, value):
"""
Sets the value of :py:attr:`fitIntercept`.
"""
return self._set(fitIntercept=value)
def setStandardization(self, value):
"""
Sets the value of :py:attr:`standardization`.
"""
return self._set(standardization=value)
def setWeightCol(self, value):
"""
Sets the value of :py:attr:`weightCol`.
"""
return self._set(weightCol=value)
def setAggregationDepth(self, value):
"""
Sets the value of :py:attr:`aggregationDepth`.
"""
return self._set(aggregationDepth=value)
@since("3.1.0")
def setBlockSize(self, value):
"""
Sets the value of :py:attr:`blockSize`.
"""
return self._set(blockSize=value)
class LogisticRegressionModel(_JavaProbabilisticClassificationModel, _LogisticRegressionParams,
JavaMLWritable, JavaMLReadable, HasTrainingSummary):
"""
Model fitted by LogisticRegression.
.. versionadded:: 1.3.0
"""
@property
@since("2.0.0")
def coefficients(self):
"""
Model coefficients of binomial logistic regression.
An exception is thrown in the case of multinomial logistic regression.
"""
return self._call_java("coefficients")
@property
@since("1.4.0")
def intercept(self):
"""
Model intercept of binomial logistic regression.
An exception is thrown in the case of multinomial logistic regression.
"""
return self._call_java("intercept")
@property
@since("2.1.0")
def coefficientMatrix(self):
"""
Model coefficients.
"""
return self._call_java("coefficientMatrix")
@property
@since("2.1.0")
def interceptVector(self):
"""
Model intercept.
"""
return self._call_java("interceptVector")
@property
@since("2.0.0")
def summary(self):
"""
Gets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model
trained on the training set. An exception is thrown if `trainingSummary is None`.
"""
if self.hasSummary:
if self.numClasses <= 2:
return BinaryLogisticRegressionTrainingSummary(super(LogisticRegressionModel,
self).summary)
else:
return LogisticRegressionTrainingSummary(super(LogisticRegressionModel,
self).summary)
else:
raise RuntimeError("No training summary available for this %s" %
self.__class__.__name__)
@since("2.0.0")
def evaluate(self, dataset):
"""
Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
if not isinstance(dataset, DataFrame):
raise ValueError("dataset must be a DataFrame but got %s." % type(dataset))
java_blr_summary = self._call_java("evaluate", dataset)
if self.numClasses <= 2:
return BinaryLogisticRegressionSummary(java_blr_summary)
else:
return LogisticRegressionSummary(java_blr_summary)
class LogisticRegressionSummary(_ClassificationSummary):
"""
Abstraction for Logistic Regression Results for a given model.
.. versionadded:: 2.0.0
"""
@property
@since("2.0.0")
def probabilityCol(self):
"""
Field in "predictions" which gives the probability
of each class as a vector.
"""
return self._call_java("probabilityCol")
@property
@since("2.0.0")
def featuresCol(self):
"""
Field in "predictions" which gives the features of each instance
as a vector.
"""
return self._call_java("featuresCol")
@inherit_doc
class LogisticRegressionTrainingSummary(LogisticRegressionSummary, _TrainingSummary):
"""
Abstraction for multinomial Logistic Regression Training results.
.. versionadded:: 2.0.0
"""
pass
@inherit_doc
class BinaryLogisticRegressionSummary(_BinaryClassificationSummary,
LogisticRegressionSummary):
"""
Binary Logistic regression results for a given model.
.. versionadded:: 2.0.0
"""
pass
@inherit_doc
class BinaryLogisticRegressionTrainingSummary(BinaryLogisticRegressionSummary,
LogisticRegressionTrainingSummary):
"""
Binary Logistic regression training results for a given model.
.. versionadded:: 2.0.0
"""
pass
@inherit_doc
class _DecisionTreeClassifierParams(_DecisionTreeParams, _TreeClassifierParams):
"""
Params for :py:class:`DecisionTreeClassifier` and :py:class:`DecisionTreeClassificationModel`.
"""
pass
@inherit_doc
class DecisionTreeClassifier(_JavaProbabilisticClassifier, _DecisionTreeClassifierParams,
JavaMLWritable, JavaMLReadable):
"""
`Decision tree <http://en.wikipedia.org/wiki/Decision_tree_learning>`_
learning algorithm for classification.
It supports both binary and multiclass labels, as well as both continuous and categorical
features.
>>> from pyspark.ml.linalg import Vectors
>>> from pyspark.ml.feature import StringIndexer
>>> df = spark.createDataFrame([
... (1.0, Vectors.dense(1.0)),
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
>>> si_model = stringIndexer.fit(df)
>>> td = si_model.transform(df)
>>> dt = DecisionTreeClassifier(maxDepth=2, labelCol="indexed", leafCol="leafId")
>>> model = dt.fit(td)
>>> model.getLabelCol()
'indexed'
>>> model.setFeaturesCol("features")
DecisionTreeClassificationModel...
>>> model.numNodes
3
>>> model.depth
1
>>> model.featureImportances
SparseVector(1, {0: 1.0})
>>> model.numFeatures
1
>>> model.numClasses
2
>>> print(model.toDebugString)
DecisionTreeClassificationModel...depth=1, numNodes=3...
>>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
>>> model.predict(test0.head().features)
0.0
>>> model.predictRaw(test0.head().features)
DenseVector([1.0, 0.0])
>>> model.predictProbability(test0.head().features)
DenseVector([1.0, 0.0])
>>> result = model.transform(test0).head()
>>> result.prediction
0.0
>>> result.probability
DenseVector([1.0, 0.0])
>>> result.rawPrediction
DenseVector([1.0, 0.0])
>>> result.leafId
0.0
>>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
>>> model.transform(test1).head().prediction
1.0
>>> dtc_path = temp_path + "/dtc"
>>> dt.save(dtc_path)
>>> dt2 = DecisionTreeClassifier.load(dtc_path)
>>> dt2.getMaxDepth()
2
>>> model_path = temp_path + "/dtc_model"
>>> model.save(model_path)
>>> model2 = DecisionTreeClassificationModel.load(model_path)
>>> model.featureImportances == model2.featureImportances
True
>>> df3 = spark.createDataFrame([
... (1.0, 0.2, Vectors.dense(1.0)),
... (1.0, 0.8, Vectors.dense(1.0)),
... (0.0, 1.0, Vectors.sparse(1, [], []))], ["label", "weight", "features"])
>>> si3 = StringIndexer(inputCol="label", outputCol="indexed")
>>> si_model3 = si3.fit(df3)
>>> td3 = si_model3.transform(df3)
>>> dt3 = DecisionTreeClassifier(maxDepth=2, weightCol="weight", labelCol="indexed")
>>> model3 = dt3.fit(td3)
>>> print(model3.toDebugString)
DecisionTreeClassificationModel...depth=1, numNodes=3...
.. versionadded:: 1.4.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini",
seed=None, weightCol=None, leafCol="", minWeightFractionPerNode=0.0):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini", \
seed=None, weightCol=None, leafCol="", minWeightFractionPerNode=0.0)
"""
super(DecisionTreeClassifier, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.DecisionTreeClassifier", self.uid)
self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
impurity="gini", leafCol="", minWeightFractionPerNode=0.0)
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.4.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
impurity="gini", seed=None, weightCol=None, leafCol="",
minWeightFractionPerNode=0.0):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini", \
seed=None, weightCol=None, leafCol="", minWeightFractionPerNode=0.0)
Sets params for the DecisionTreeClassifier.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return DecisionTreeClassificationModel(java_model)
def setMaxDepth(self, value):
"""
Sets the value of :py:attr:`maxDepth`.
"""
return self._set(maxDepth=value)
def setMaxBins(self, value):
"""
Sets the value of :py:attr:`maxBins`.
"""
return self._set(maxBins=value)
def setMinInstancesPerNode(self, value):
"""
Sets the value of :py:attr:`minInstancesPerNode`.
"""
return self._set(minInstancesPerNode=value)
@since("3.0.0")
def setMinWeightFractionPerNode(self, value):
"""
Sets the value of :py:attr:`minWeightFractionPerNode`.
"""
return self._set(minWeightFractionPerNode=value)
def setMinInfoGain(self, value):
"""
Sets the value of :py:attr:`minInfoGain`.
"""
return self._set(minInfoGain=value)
def setMaxMemoryInMB(self, value):
"""
Sets the value of :py:attr:`maxMemoryInMB`.
"""
return self._set(maxMemoryInMB=value)
def setCacheNodeIds(self, value):
"""
Sets the value of :py:attr:`cacheNodeIds`.
"""
return self._set(cacheNodeIds=value)
@since("1.4.0")
def setImpurity(self, value):
"""
Sets the value of :py:attr:`impurity`.
"""
return self._set(impurity=value)
@since("1.4.0")
def setCheckpointInterval(self, value):
"""
Sets the value of :py:attr:`checkpointInterval`.
"""
return self._set(checkpointInterval=value)
def setSeed(self, value):
"""
Sets the value of :py:attr:`seed`.
"""
return self._set(seed=value)
@since("3.0.0")
def setWeightCol(self, value):
"""
Sets the value of :py:attr:`weightCol`.
"""
return self._set(weightCol=value)
@inherit_doc
class DecisionTreeClassificationModel(_DecisionTreeModel, _JavaProbabilisticClassificationModel,
_DecisionTreeClassifierParams, JavaMLWritable,
JavaMLReadable):
"""
Model fitted by DecisionTreeClassifier.
.. versionadded:: 1.4.0
"""
@property
@since("2.0.0")
def featureImportances(self):
"""
Estimate of the importance of each feature.
This generalizes the idea of "Gini" importance to other losses,
following the explanation of Gini importance from "Random Forests" documentation
by Leo Breiman and Adele Cutler, and following the implementation from scikit-learn.
This feature importance is calculated as follows:
- importance(feature j) = sum (over nodes which split on feature j) of the gain,
where gain is scaled by the number of instances passing through node
- Normalize importances for tree to sum to 1.
.. note:: Feature importance for single decision trees can have high variance due to
correlated predictor variables. Consider using a :py:class:`RandomForestClassifier`
to determine feature importance instead.
"""
return self._call_java("featureImportances")
@inherit_doc
class _RandomForestClassifierParams(_RandomForestParams, _TreeClassifierParams):
"""
Params for :py:class:`RandomForestClassifier` and :py:class:`RandomForestClassificationModel`.
"""
pass
@inherit_doc
class RandomForestClassifier(_JavaProbabilisticClassifier, _RandomForestClassifierParams,
JavaMLWritable, JavaMLReadable):
"""
`Random Forest <http://en.wikipedia.org/wiki/Random_forest>`_
learning algorithm for classification.
It supports both binary and multiclass labels, as well as both continuous and categorical
features.
>>> import numpy
>>> from numpy import allclose
>>> from pyspark.ml.linalg import Vectors
>>> from pyspark.ml.feature import StringIndexer
>>> df = spark.createDataFrame([
... (1.0, Vectors.dense(1.0)),
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
>>> si_model = stringIndexer.fit(df)
>>> td = si_model.transform(df)
>>> rf = RandomForestClassifier(numTrees=3, maxDepth=2, labelCol="indexed", seed=42,
... leafCol="leafId")
>>> rf.getMinWeightFractionPerNode()
0.0
>>> model = rf.fit(td)
>>> model.getLabelCol()
'indexed'
>>> model.setFeaturesCol("features")
RandomForestClassificationModel...
>>> model.setRawPredictionCol("newRawPrediction")
RandomForestClassificationModel...
>>> model.getBootstrap()
True
>>> model.getRawPredictionCol()
'newRawPrediction'
>>> model.featureImportances
SparseVector(1, {0: 1.0})
>>> allclose(model.treeWeights, [1.0, 1.0, 1.0])
True
>>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
>>> model.predict(test0.head().features)
0.0
>>> model.predictRaw(test0.head().features)
DenseVector([2.0, 0.0])
>>> model.predictProbability(test0.head().features)
DenseVector([1.0, 0.0])
>>> result = model.transform(test0).head()
>>> result.prediction
0.0
>>> numpy.argmax(result.probability)
0
>>> numpy.argmax(result.newRawPrediction)
0
>>> result.leafId
DenseVector([0.0, 0.0, 0.0])
>>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
>>> model.transform(test1).head().prediction
1.0
>>> model.trees
[DecisionTreeClassificationModel...depth=..., DecisionTreeClassificationModel...]
>>> rfc_path = temp_path + "/rfc"
>>> rf.save(rfc_path)
>>> rf2 = RandomForestClassifier.load(rfc_path)
>>> rf2.getNumTrees()
3
>>> model_path = temp_path + "/rfc_model"
>>> model.save(model_path)
>>> model2 = RandomForestClassificationModel.load(model_path)
>>> model.featureImportances == model2.featureImportances
True
.. versionadded:: 1.4.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini",
numTrees=20, featureSubsetStrategy="auto", seed=None, subsamplingRate=1.0,
leafCol="", minWeightFractionPerNode=0.0, weightCol=None, bootstrap=True):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini", \
numTrees=20, featureSubsetStrategy="auto", seed=None, subsamplingRate=1.0, \
leafCol="", minWeightFractionPerNode=0.0, weightCol=None, bootstrap=True)
"""
super(RandomForestClassifier, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.RandomForestClassifier", self.uid)
self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
impurity="gini", numTrees=20, featureSubsetStrategy="auto",
subsamplingRate=1.0, leafCol="", minWeightFractionPerNode=0.0,
bootstrap=True)
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.4.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, seed=None,
impurity="gini", numTrees=20, featureSubsetStrategy="auto", subsamplingRate=1.0,
leafCol="", minWeightFractionPerNode=0.0, weightCol=None, bootstrap=True):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, seed=None, \
impurity="gini", numTrees=20, featureSubsetStrategy="auto", subsamplingRate=1.0, \
leafCol="", minWeightFractionPerNode=0.0, weightCol=None, bootstrap=True)
Sets params for linear classification.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return RandomForestClassificationModel(java_model)
def setMaxDepth(self, value):
"""
Sets the value of :py:attr:`maxDepth`.
"""
return self._set(maxDepth=value)
def setMaxBins(self, value):
"""
Sets the value of :py:attr:`maxBins`.
"""
return self._set(maxBins=value)
def setMinInstancesPerNode(self, value):
"""
Sets the value of :py:attr:`minInstancesPerNode`.
"""
return self._set(minInstancesPerNode=value)
def setMinInfoGain(self, value):
"""
Sets the value of :py:attr:`minInfoGain`.
"""
return self._set(minInfoGain=value)
def setMaxMemoryInMB(self, value):
"""
Sets the value of :py:attr:`maxMemoryInMB`.
"""
return self._set(maxMemoryInMB=value)
def setCacheNodeIds(self, value):
"""
Sets the value of :py:attr:`cacheNodeIds`.
"""
return self._set(cacheNodeIds=value)
@since("1.4.0")
def setImpurity(self, value):
"""
Sets the value of :py:attr:`impurity`.
"""
return self._set(impurity=value)
@since("1.4.0")
def setNumTrees(self, value):
"""
Sets the value of :py:attr:`numTrees`.
"""
return self._set(numTrees=value)
@since("3.0.0")
def setBootstrap(self, value):
"""
Sets the value of :py:attr:`bootstrap`.
"""
return self._set(bootstrap=value)
@since("1.4.0")
def setSubsamplingRate(self, value):
"""
Sets the value of :py:attr:`subsamplingRate`.
"""
return self._set(subsamplingRate=value)
@since("2.4.0")
def setFeatureSubsetStrategy(self, value):
"""
Sets the value of :py:attr:`featureSubsetStrategy`.
"""
return self._set(featureSubsetStrategy=value)
def setSeed(self, value):
"""
Sets the value of :py:attr:`seed`.
"""
return self._set(seed=value)
def setCheckpointInterval(self, value):
"""
Sets the value of :py:attr:`checkpointInterval`.
"""
return self._set(checkpointInterval=value)
@since("3.0.0")
def setWeightCol(self, value):
"""
Sets the value of :py:attr:`weightCol`.
"""
return self._set(weightCol=value)
@since("3.0.0")
def setMinWeightFractionPerNode(self, value):
"""
Sets the value of :py:attr:`minWeightFractionPerNode`.
"""
return self._set(minWeightFractionPerNode=value)
class RandomForestClassificationModel(_TreeEnsembleModel, _JavaProbabilisticClassificationModel,
_RandomForestClassifierParams, JavaMLWritable,
JavaMLReadable):
"""
Model fitted by RandomForestClassifier.
.. versionadded:: 1.4.0
"""
@property
@since("2.0.0")
def featureImportances(self):
"""
Estimate of the importance of each feature.
Each feature's importance is the average of its importance across all trees in the ensemble
The importance vector is normalized to sum to 1. This method is suggested by Hastie et al.
(Hastie, Tibshirani, Friedman. "The Elements of Statistical Learning, 2nd Edition." 2001.)
and follows the implementation from scikit-learn.
.. seealso:: :py:attr:`DecisionTreeClassificationModel.featureImportances`
"""
return self._call_java("featureImportances")
@property
@since("2.0.0")
def trees(self):
"""Trees in this ensemble. Warning: These have null parent Estimators."""
return [DecisionTreeClassificationModel(m) for m in list(self._call_java("trees"))]
class _GBTClassifierParams(_GBTParams, _HasVarianceImpurity):
"""
Params for :py:class:`GBTClassifier` and :py:class:`GBTClassifierModel`.
.. versionadded:: 3.0.0
"""
supportedLossTypes = ["logistic"]
lossType = Param(Params._dummy(), "lossType",
"Loss function which GBT tries to minimize (case-insensitive). " +
"Supported options: " + ", ".join(supportedLossTypes),
typeConverter=TypeConverters.toString)
@since("1.4.0")
def getLossType(self):
"""
Gets the value of lossType or its default value.
"""
return self.getOrDefault(self.lossType)
@inherit_doc
class GBTClassifier(_JavaProbabilisticClassifier, _GBTClassifierParams,
JavaMLWritable, JavaMLReadable):
"""
`Gradient-Boosted Trees (GBTs) <http://en.wikipedia.org/wiki/Gradient_boosting>`_
learning algorithm for classification.
It supports binary labels, as well as both continuous and categorical features.
The implementation is based upon: J.H. Friedman. "Stochastic Gradient Boosting." 1999.
Notes on Gradient Boosting vs. TreeBoost:
- This implementation is for Stochastic Gradient Boosting, not for TreeBoost.
- Both algorithms learn tree ensembles by minimizing loss functions.
- TreeBoost (Friedman, 1999) additionally modifies the outputs at tree leaf nodes
based on the loss function, whereas the original gradient boosting method does not.
- We expect to implement TreeBoost in the future:
`SPARK-4240 <https://issues.apache.org/jira/browse/SPARK-4240>`_
.. note:: Multiclass labels are not currently supported.
>>> from numpy import allclose
>>> from pyspark.ml.linalg import Vectors
>>> from pyspark.ml.feature import StringIndexer
>>> df = spark.createDataFrame([
... (1.0, Vectors.dense(1.0)),
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
>>> si_model = stringIndexer.fit(df)
>>> td = si_model.transform(df)
>>> gbt = GBTClassifier(maxIter=5, maxDepth=2, labelCol="indexed", seed=42,
... leafCol="leafId")
>>> gbt.setMaxIter(5)
GBTClassifier...
>>> gbt.setMinWeightFractionPerNode(0.049)
GBTClassifier...
>>> gbt.getMaxIter()
5
>>> gbt.getFeatureSubsetStrategy()
'all'
>>> model = gbt.fit(td)
>>> model.getLabelCol()
'indexed'
>>> model.setFeaturesCol("features")
GBTClassificationModel...
>>> model.setThresholds([0.3, 0.7])
GBTClassificationModel...
>>> model.getThresholds()
[0.3, 0.7]
>>> model.featureImportances
SparseVector(1, {0: 1.0})
>>> allclose(model.treeWeights, [1.0, 0.1, 0.1, 0.1, 0.1])
True
>>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
>>> model.predict(test0.head().features)
0.0
>>> model.predictRaw(test0.head().features)
DenseVector([1.1697, -1.1697])
>>> model.predictProbability(test0.head().features)
DenseVector([0.9121, 0.0879])
>>> result = model.transform(test0).head()
>>> result.prediction
0.0
>>> result.leafId
DenseVector([0.0, 0.0, 0.0, 0.0, 0.0])
>>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
>>> model.transform(test1).head().prediction
1.0
>>> model.totalNumNodes
15
>>> print(model.toDebugString)
GBTClassificationModel...numTrees=5...
>>> gbtc_path = temp_path + "gbtc"
>>> gbt.save(gbtc_path)
>>> gbt2 = GBTClassifier.load(gbtc_path)
>>> gbt2.getMaxDepth()
2
>>> model_path = temp_path + "gbtc_model"
>>> model.save(model_path)
>>> model2 = GBTClassificationModel.load(model_path)
>>> model.featureImportances == model2.featureImportances
True
>>> model.treeWeights == model2.treeWeights
True
>>> model.trees
[DecisionTreeRegressionModel...depth=..., DecisionTreeRegressionModel...]
>>> validation = spark.createDataFrame([(0.0, Vectors.dense(-1.0),)],
... ["indexed", "features"])
>>> model.evaluateEachIteration(validation)
[0.25..., 0.23..., 0.21..., 0.19..., 0.18...]
>>> model.numClasses
2
>>> gbt = gbt.setValidationIndicatorCol("validationIndicator")
>>> gbt.getValidationIndicatorCol()
'validationIndicator'
>>> gbt.getValidationTol()
0.01
.. versionadded:: 1.4.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, lossType="logistic",
maxIter=20, stepSize=0.1, seed=None, subsamplingRate=1.0, impurity="variance",
featureSubsetStrategy="all", validationTol=0.01, validationIndicatorCol=None,
leafCol="", minWeightFractionPerNode=0.0, weightCol=None):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, \
lossType="logistic", maxIter=20, stepSize=0.1, seed=None, subsamplingRate=1.0, \
impurity="variance", featureSubsetStrategy="all", validationTol=0.01, \
validationIndicatorCol=None, leafCol="", minWeightFractionPerNode=0.0, \
weightCol=None)
"""
super(GBTClassifier, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.GBTClassifier", self.uid)
self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
lossType="logistic", maxIter=20, stepSize=0.1, subsamplingRate=1.0,
impurity="variance", featureSubsetStrategy="all", validationTol=0.01,
leafCol="", minWeightFractionPerNode=0.0)
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.4.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
lossType="logistic", maxIter=20, stepSize=0.1, seed=None, subsamplingRate=1.0,
impurity="variance", featureSubsetStrategy="all", validationTol=0.01,
validationIndicatorCol=None, leafCol="", minWeightFractionPerNode=0.0,
weightCol=None):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, \
lossType="logistic", maxIter=20, stepSize=0.1, seed=None, subsamplingRate=1.0, \
impurity="variance", featureSubsetStrategy="all", validationTol=0.01, \
validationIndicatorCol=None, leafCol="", minWeightFractionPerNode=0.0, \
weightCol=None)
Sets params for Gradient Boosted Tree Classification.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return GBTClassificationModel(java_model)
def setMaxDepth(self, value):
"""
Sets the value of :py:attr:`maxDepth`.
"""
return self._set(maxDepth=value)
def setMaxBins(self, value):
"""
Sets the value of :py:attr:`maxBins`.
"""
return self._set(maxBins=value)
def setMinInstancesPerNode(self, value):
"""
Sets the value of :py:attr:`minInstancesPerNode`.
"""
return self._set(minInstancesPerNode=value)
def setMinInfoGain(self, value):
"""
Sets the value of :py:attr:`minInfoGain`.
"""
return self._set(minInfoGain=value)
def setMaxMemoryInMB(self, value):
"""
Sets the value of :py:attr:`maxMemoryInMB`.
"""
return self._set(maxMemoryInMB=value)
def setCacheNodeIds(self, value):
"""
Sets the value of :py:attr:`cacheNodeIds`.
"""
return self._set(cacheNodeIds=value)
@since("1.4.0")
def setImpurity(self, value):
"""
Sets the value of :py:attr:`impurity`.
"""
return self._set(impurity=value)
@since("1.4.0")
def setLossType(self, value):
"""
Sets the value of :py:attr:`lossType`.
"""
return self._set(lossType=value)
@since("1.4.0")
def setSubsamplingRate(self, value):
"""
Sets the value of :py:attr:`subsamplingRate`.
"""
return self._set(subsamplingRate=value)
@since("2.4.0")
def setFeatureSubsetStrategy(self, value):
"""
Sets the value of :py:attr:`featureSubsetStrategy`.
"""
return self._set(featureSubsetStrategy=value)
@since("3.0.0")
def setValidationIndicatorCol(self, value):
"""
Sets the value of :py:attr:`validationIndicatorCol`.
"""
return self._set(validationIndicatorCol=value)
@since("1.4.0")
def setMaxIter(self, value):
"""
Sets the value of :py:attr:`maxIter`.
"""
return self._set(maxIter=value)
@since("1.4.0")
def setCheckpointInterval(self, value):
"""
Sets the value of :py:attr:`checkpointInterval`.
"""
return self._set(checkpointInterval=value)
@since("1.4.0")
def setSeed(self, value):
"""
Sets the value of :py:attr:`seed`.
"""
return self._set(seed=value)
@since("1.4.0")
def setStepSize(self, value):
"""
Sets the value of :py:attr:`stepSize`.
"""
return self._set(stepSize=value)
@since("3.0.0")
def setWeightCol(self, value):
"""
Sets the value of :py:attr:`weightCol`.
"""
return self._set(weightCol=value)
@since("3.0.0")
def setMinWeightFractionPerNode(self, value):
"""
Sets the value of :py:attr:`minWeightFractionPerNode`.
"""
return self._set(minWeightFractionPerNode=value)
class GBTClassificationModel(_TreeEnsembleModel, _JavaProbabilisticClassificationModel,
_GBTClassifierParams, JavaMLWritable, JavaMLReadable):
"""
Model fitted by GBTClassifier.
.. versionadded:: 1.4.0
"""
@property
@since("2.0.0")
def featureImportances(self):
"""
Estimate of the importance of each feature.
Each feature's importance is the average of its importance across all trees in the ensemble
The importance vector is normalized to sum to 1. This method is suggested by Hastie et al.
(Hastie, Tibshirani, Friedman. "The Elements of Statistical Learning, 2nd Edition." 2001.)
and follows the implementation from scikit-learn.
.. seealso:: :py:attr:`DecisionTreeClassificationModel.featureImportances`
"""
return self._call_java("featureImportances")
@property
@since("2.0.0")
def trees(self):
"""Trees in this ensemble. Warning: These have null parent Estimators."""
return [DecisionTreeRegressionModel(m) for m in list(self._call_java("trees"))]
@since("2.4.0")
def evaluateEachIteration(self, dataset):
"""
Method to compute error or loss for every iteration of gradient boosting.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
return self._call_java("evaluateEachIteration", dataset)
class _NaiveBayesParams(_PredictorParams, HasWeightCol):
"""
Params for :py:class:`NaiveBayes` and :py:class:`NaiveBayesModel`.
.. versionadded:: 3.0.0
"""
smoothing = Param(Params._dummy(), "smoothing", "The smoothing parameter, should be >= 0, " +
"default is 1.0", typeConverter=TypeConverters.toFloat)
modelType = Param(Params._dummy(), "modelType", "The model type which is a string " +
"(case-sensitive). Supported options: multinomial (default), bernoulli " +
"and gaussian.",
typeConverter=TypeConverters.toString)
@since("1.5.0")
def getSmoothing(self):
"""
Gets the value of smoothing or its default value.
"""
return self.getOrDefault(self.smoothing)
@since("1.5.0")
def getModelType(self):
"""
Gets the value of modelType or its default value.
"""
return self.getOrDefault(self.modelType)
@inherit_doc
class NaiveBayes(_JavaProbabilisticClassifier, _NaiveBayesParams, HasThresholds, HasWeightCol,
JavaMLWritable, JavaMLReadable):
"""
Naive Bayes Classifiers.
It supports both Multinomial and Bernoulli NB. `Multinomial NB
<http://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html>`_
can handle finitely supported discrete data. For example, by converting documents into
TF-IDF vectors, it can be used for document classification. By making every vector a
binary (0/1) data, it can also be used as `Bernoulli NB
<http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html>`_.
The input feature values for Multinomial NB and Bernoulli NB must be nonnegative.
Since 3.0.0, it supports Complement NB which is an adaptation of the Multinomial NB.
Specifically, Complement NB uses statistics from the complement of each class to compute
the model's coefficients. The inventors of Complement NB show empirically that the parameter
estimates for CNB are more stable than those for Multinomial NB. Like Multinomial NB, the
input feature values for Complement NB must be nonnegative.
Since 3.0.0, it also supports Gaussian NB
<https://en.wikipedia.org/wiki/Naive_Bayes_classifier#Gaussian_naive_Bayes>`_.
which can handle continuous data.
>>> from pyspark.sql import Row
>>> from pyspark.ml.linalg import Vectors
>>> df = spark.createDataFrame([
... Row(label=0.0, weight=0.1, features=Vectors.dense([0.0, 0.0])),
... Row(label=0.0, weight=0.5, features=Vectors.dense([0.0, 1.0])),
... Row(label=1.0, weight=1.0, features=Vectors.dense([1.0, 0.0]))])
>>> nb = NaiveBayes(smoothing=1.0, modelType="multinomial", weightCol="weight")
>>> model = nb.fit(df)
>>> model.setFeaturesCol("features")
NaiveBayesModel...
>>> model.getSmoothing()
1.0
>>> model.pi
DenseVector([-0.81..., -0.58...])
>>> model.theta
DenseMatrix(2, 2, [-0.91..., -0.51..., -0.40..., -1.09...], 1)
>>> model.sigma
DenseMatrix(0, 0, [...], ...)
>>> test0 = sc.parallelize([Row(features=Vectors.dense([1.0, 0.0]))]).toDF()
>>> model.predict(test0.head().features)
1.0
>>> model.predictRaw(test0.head().features)
DenseVector([-1.72..., -0.99...])
>>> model.predictProbability(test0.head().features)
DenseVector([0.32..., 0.67...])
>>> result = model.transform(test0).head()
>>> result.prediction
1.0
>>> result.probability
DenseVector([0.32..., 0.67...])
>>> result.rawPrediction
DenseVector([-1.72..., -0.99...])
>>> test1 = sc.parallelize([Row(features=Vectors.sparse(2, [0], [1.0]))]).toDF()
>>> model.transform(test1).head().prediction
1.0
>>> nb_path = temp_path + "/nb"
>>> nb.save(nb_path)
>>> nb2 = NaiveBayes.load(nb_path)
>>> nb2.getSmoothing()
1.0
>>> model_path = temp_path + "/nb_model"
>>> model.save(model_path)
>>> model2 = NaiveBayesModel.load(model_path)
>>> model.pi == model2.pi
True
>>> model.theta == model2.theta
True
>>> nb = nb.setThresholds([0.01, 10.00])
>>> model3 = nb.fit(df)
>>> result = model3.transform(test0).head()
>>> result.prediction
0.0
>>> nb3 = NaiveBayes().setModelType("gaussian")
>>> model4 = nb3.fit(df)
>>> model4.getModelType()
'gaussian'
>>> model4.sigma
DenseMatrix(2, 2, [0.0, 0.25, 0.0, 0.0], 1)
>>> nb5 = NaiveBayes(smoothing=1.0, modelType="complement", weightCol="weight")
>>> model5 = nb5.fit(df)
>>> model5.getModelType()
'complement'
>>> model5.theta
DenseMatrix(2, 2, [...], 1)
>>> model5.sigma
DenseMatrix(0, 0, [...], ...)
.. versionadded:: 1.5.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0,
modelType="multinomial", thresholds=None, weightCol=None):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0, \
modelType="multinomial", thresholds=None, weightCol=None)
"""
super(NaiveBayes, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.NaiveBayes", self.uid)
self._setDefault(smoothing=1.0, modelType="multinomial")
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.5.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0,
modelType="multinomial", thresholds=None, weightCol=None):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0, \
modelType="multinomial", thresholds=None, weightCol=None)
Sets params for Naive Bayes.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return NaiveBayesModel(java_model)
@since("1.5.0")
def setSmoothing(self, value):
"""
Sets the value of :py:attr:`smoothing`.
"""
return self._set(smoothing=value)
@since("1.5.0")
def setModelType(self, value):
"""
Sets the value of :py:attr:`modelType`.
"""
return self._set(modelType=value)
def setWeightCol(self, value):
"""
Sets the value of :py:attr:`weightCol`.
"""
return self._set(weightCol=value)
class NaiveBayesModel(_JavaProbabilisticClassificationModel, _NaiveBayesParams, JavaMLWritable,
JavaMLReadable):
"""
Model fitted by NaiveBayes.
.. versionadded:: 1.5.0
"""
@property
@since("2.0.0")
def pi(self):
"""
log of class priors.
"""
return self._call_java("pi")
@property
@since("2.0.0")
def theta(self):
"""
log of class conditional probabilities.
"""
return self._call_java("theta")
@property
@since("3.0.0")
def sigma(self):
"""
variance of each feature.
"""
return self._call_java("sigma")
class _MultilayerPerceptronParams(_ProbabilisticClassifierParams, HasSeed, HasMaxIter,
HasTol, HasStepSize, HasSolver, HasBlockSize):
"""
Params for :py:class:`MultilayerPerceptronClassifier`.
.. versionadded:: 3.0.0
"""
layers = Param(Params._dummy(), "layers", "Sizes of layers from input layer to output layer " +
"E.g., Array(780, 100, 10) means 780 inputs, one hidden layer with 100 " +
"neurons and output layer of 10 neurons.",
typeConverter=TypeConverters.toListInt)
solver = Param(Params._dummy(), "solver", "The solver algorithm for optimization. Supported " +
"options: l-bfgs, gd.", typeConverter=TypeConverters.toString)
initialWeights = Param(Params._dummy(), "initialWeights", "The initial weights of the model.",
typeConverter=TypeConverters.toVector)
@since("1.6.0")
def getLayers(self):
"""
Gets the value of layers or its default value.
"""
return self.getOrDefault(self.layers)
@since("2.0.0")
def getInitialWeights(self):
"""
Gets the value of initialWeights or its default value.
"""
return self.getOrDefault(self.initialWeights)
@inherit_doc
class MultilayerPerceptronClassifier(_JavaProbabilisticClassifier, _MultilayerPerceptronParams,
JavaMLWritable, JavaMLReadable):
"""
Classifier trainer based on the Multilayer Perceptron.
Each layer has sigmoid activation function, output layer has softmax.
Number of inputs has to be equal to the size of feature vectors.
Number of outputs has to be equal to the total number of labels.
>>> from pyspark.ml.linalg import Vectors
>>> df = spark.createDataFrame([
... (0.0, Vectors.dense([0.0, 0.0])),
... (1.0, Vectors.dense([0.0, 1.0])),
... (1.0, Vectors.dense([1.0, 0.0])),
... (0.0, Vectors.dense([1.0, 1.0]))], ["label", "features"])
>>> mlp = MultilayerPerceptronClassifier(layers=[2, 2, 2], seed=123)
>>> mlp.setMaxIter(100)
MultilayerPerceptronClassifier...
>>> mlp.getMaxIter()
100
>>> mlp.getBlockSize()
128
>>> mlp.setBlockSize(1)
MultilayerPerceptronClassifier...
>>> mlp.getBlockSize()
1
>>> model = mlp.fit(df)
>>> model.setFeaturesCol("features")
MultilayerPerceptronClassificationModel...
>>> model.getMaxIter()
100
>>> model.getLayers()
[2, 2, 2]
>>> model.weights.size
12
>>> testDF = spark.createDataFrame([
... (Vectors.dense([1.0, 0.0]),),
... (Vectors.dense([0.0, 0.0]),)], ["features"])
>>> model.predict(testDF.head().features)
1.0
>>> model.predictRaw(testDF.head().features)
DenseVector([-16.208, 16.344])
>>> model.predictProbability(testDF.head().features)
DenseVector([0.0, 1.0])
>>> model.transform(testDF).select("features", "prediction").show()
+---------+----------+
| features|prediction|
+---------+----------+
|[1.0,0.0]| 1.0|
|[0.0,0.0]| 0.0|
+---------+----------+
...
>>> mlp_path = temp_path + "/mlp"
>>> mlp.save(mlp_path)
>>> mlp2 = MultilayerPerceptronClassifier.load(mlp_path)
>>> mlp2.getBlockSize()
1
>>> model_path = temp_path + "/mlp_model"
>>> model.save(model_path)
>>> model2 = MultilayerPerceptronClassificationModel.load(model_path)
>>> model.getLayers() == model2.getLayers()
True
>>> model.weights == model2.weights
True
>>> mlp2 = mlp2.setInitialWeights(list(range(0, 12)))
>>> model3 = mlp2.fit(df)
>>> model3.weights != model2.weights
True
>>> model3.getLayers() == model.getLayers()
True
.. versionadded:: 1.6.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, tol=1e-6, seed=None, layers=None, blockSize=128, stepSize=0.03,
solver="l-bfgs", initialWeights=None, probabilityCol="probability",
rawPredictionCol="rawPrediction"):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, tol=1e-6, seed=None, layers=None, blockSize=128, stepSize=0.03, \
solver="l-bfgs", initialWeights=None, probabilityCol="probability", \
rawPredictionCol="rawPrediction")
"""
super(MultilayerPerceptronClassifier, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.MultilayerPerceptronClassifier", self.uid)
self._setDefault(maxIter=100, tol=1E-6, blockSize=128, stepSize=0.03, solver="l-bfgs")
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.6.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, tol=1e-6, seed=None, layers=None, blockSize=128, stepSize=0.03,
solver="l-bfgs", initialWeights=None, probabilityCol="probability",
rawPredictionCol="rawPrediction"):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, tol=1e-6, seed=None, layers=None, blockSize=128, stepSize=0.03, \
solver="l-bfgs", initialWeights=None, probabilityCol="probability", \
rawPredictionCol="rawPrediction"):
Sets params for MultilayerPerceptronClassifier.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return MultilayerPerceptronClassificationModel(java_model)
@since("1.6.0")
def setLayers(self, value):
"""
Sets the value of :py:attr:`layers`.
"""
return self._set(layers=value)
@since("1.6.0")
def setBlockSize(self, value):
"""
Sets the value of :py:attr:`blockSize`.
"""
return self._set(blockSize=value)
@since("2.0.0")
def setInitialWeights(self, value):
"""
Sets the value of :py:attr:`initialWeights`.
"""
return self._set(initialWeights=value)
def setMaxIter(self, value):
"""
Sets the value of :py:attr:`maxIter`.
"""
return self._set(maxIter=value)
def setSeed(self, value):
"""
Sets the value of :py:attr:`seed`.
"""
return self._set(seed=value)
def setTol(self, value):
"""
Sets the value of :py:attr:`tol`.
"""
return self._set(tol=value)
@since("2.0.0")
def setStepSize(self, value):
"""
Sets the value of :py:attr:`stepSize`.
"""
return self._set(stepSize=value)
def setSolver(self, value):
"""
Sets the value of :py:attr:`solver`.
"""
return self._set(solver=value)
class MultilayerPerceptronClassificationModel(_JavaProbabilisticClassificationModel,
_MultilayerPerceptronParams, JavaMLWritable,
JavaMLReadable):
"""
Model fitted by MultilayerPerceptronClassifier.
.. versionadded:: 1.6.0
"""
@property
@since("2.0.0")
def weights(self):
"""
the weights of layers.
"""
return self._call_java("weights")
class _OneVsRestParams(_ClassifierParams, HasWeightCol):
"""
Params for :py:class:`OneVsRest` and :py:class:`OneVsRestModelModel`.
"""
classifier = Param(Params._dummy(), "classifier", "base binary classifier")
@since("2.0.0")
def getClassifier(self):
"""
Gets the value of classifier or its default value.
"""
return self.getOrDefault(self.classifier)
@inherit_doc
class OneVsRest(Estimator, _OneVsRestParams, HasParallelism, JavaMLReadable, JavaMLWritable):
"""
Reduction of Multiclass Classification to Binary Classification.
Performs reduction using one against all strategy.
For a multiclass classification with k classes, train k models (one per class).
Each example is scored against all k models and the model with highest score
is picked to label the example.
>>> from pyspark.sql import Row
>>> from pyspark.ml.linalg import Vectors
>>> data_path = "data/mllib/sample_multiclass_classification_data.txt"
>>> df = spark.read.format("libsvm").load(data_path)
>>> lr = LogisticRegression(regParam=0.01)
>>> ovr = OneVsRest(classifier=lr)
>>> ovr.getRawPredictionCol()
'rawPrediction'
>>> ovr.setPredictionCol("newPrediction")
OneVsRest...
>>> model = ovr.fit(df)
>>> model.models[0].coefficients
DenseVector([0.5..., -1.0..., 3.4..., 4.2...])
>>> model.models[1].coefficients
DenseVector([-2.1..., 3.1..., -2.6..., -2.3...])
>>> model.models[2].coefficients
DenseVector([0.3..., -3.4..., 1.0..., -1.1...])
>>> [x.intercept for x in model.models]
[-2.7..., -2.5..., -1.3...]
>>> test0 = sc.parallelize([Row(features=Vectors.dense(-1.0, 0.0, 1.0, 1.0))]).toDF()
>>> model.transform(test0).head().newPrediction
0.0
>>> test1 = sc.parallelize([Row(features=Vectors.sparse(4, [0], [1.0]))]).toDF()
>>> model.transform(test1).head().newPrediction
2.0
>>> test2 = sc.parallelize([Row(features=Vectors.dense(0.5, 0.4, 0.3, 0.2))]).toDF()
>>> model.transform(test2).head().newPrediction
0.0
>>> model_path = temp_path + "/ovr_model"
>>> model.save(model_path)
>>> model2 = OneVsRestModel.load(model_path)
>>> model2.transform(test0).head().newPrediction
0.0
>>> model.transform(test2).columns
['features', 'rawPrediction', 'newPrediction']
.. versionadded:: 2.0.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
rawPredictionCol="rawPrediction", classifier=None, weightCol=None, parallelism=1):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
rawPredictionCol="rawPrediction", classifier=None, weightCol=None, parallelism=1):
"""
super(OneVsRest, self).__init__()
self._setDefault(parallelism=1)
kwargs = self._input_kwargs
self._set(**kwargs)
@keyword_only
@since("2.0.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
rawPredictionCol="rawPrediction", classifier=None, weightCol=None, parallelism=1):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
rawPredictionCol="rawPrediction", classifier=None, weightCol=None, parallelism=1):
Sets params for OneVsRest.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
@since("2.0.0")
def setClassifier(self, value):
"""
Sets the value of :py:attr:`classifier`.
"""
return self._set(classifier=value)
def setLabelCol(self, value):
"""
Sets the value of :py:attr:`labelCol`.
"""
return self._set(labelCol=value)
def setFeaturesCol(self, value):
"""
Sets the value of :py:attr:`featuresCol`.
"""
return self._set(featuresCol=value)
def setPredictionCol(self, value):
"""
Sets the value of :py:attr:`predictionCol`.
"""
return self._set(predictionCol=value)
def setRawPredictionCol(self, value):
"""
Sets the value of :py:attr:`rawPredictionCol`.
"""
return self._set(rawPredictionCol=value)
def setWeightCol(self, value):
"""
Sets the value of :py:attr:`weightCol`.
"""
return self._set(weightCol=value)
def setParallelism(self, value):
"""
Sets the value of :py:attr:`parallelism`.
"""
return self._set(parallelism=value)
def _fit(self, dataset):
labelCol = self.getLabelCol()
featuresCol = self.getFeaturesCol()
predictionCol = self.getPredictionCol()
classifier = self.getClassifier()
numClasses = int(dataset.agg({labelCol: "max"}).head()["max("+labelCol+")"]) + 1
weightCol = None
if (self.isDefined(self.weightCol) and self.getWeightCol()):
if isinstance(classifier, HasWeightCol):
weightCol = self.getWeightCol()
else:
warnings.warn("weightCol is ignored, "
"as it is not supported by {} now.".format(classifier))
if weightCol:
multiclassLabeled = dataset.select(labelCol, featuresCol, weightCol)
else:
multiclassLabeled = dataset.select(labelCol, featuresCol)
# persist if underlying dataset is not persistent.
handlePersistence = dataset.storageLevel == StorageLevel(False, False, False, False)
if handlePersistence:
multiclassLabeled.persist(StorageLevel.MEMORY_AND_DISK)
def trainSingleClass(index):
binaryLabelCol = "mc2b$" + str(index)
trainingDataset = multiclassLabeled.withColumn(
binaryLabelCol,
when(multiclassLabeled[labelCol] == float(index), 1.0).otherwise(0.0))
paramMap = dict([(classifier.labelCol, binaryLabelCol),
(classifier.featuresCol, featuresCol),
(classifier.predictionCol, predictionCol)])
if weightCol:
paramMap[classifier.weightCol] = weightCol
return classifier.fit(trainingDataset, paramMap)
pool = ThreadPool(processes=min(self.getParallelism(), numClasses))
models = pool.map(trainSingleClass, range(numClasses))
if handlePersistence:
multiclassLabeled.unpersist()
return self._copyValues(OneVsRestModel(models=models))
@since("2.0.0")
def copy(self, extra=None):
"""
Creates a copy of this instance with a randomly generated uid
and some extra params. This creates a deep copy of the embedded paramMap,
and copies the embedded and extra parameters over.
:param extra: Extra parameters to copy to the new instance
:return: Copy of this instance
"""
if extra is None:
extra = dict()
newOvr = Params.copy(self, extra)
if self.isSet(self.classifier):
newOvr.setClassifier(self.getClassifier().copy(extra))
return newOvr
@classmethod
def _from_java(cls, java_stage):
"""
Given a Java OneVsRest, create and return a Python wrapper of it.
Used for ML persistence.
"""
featuresCol = java_stage.getFeaturesCol()
labelCol = java_stage.getLabelCol()
predictionCol = java_stage.getPredictionCol()
rawPredictionCol = java_stage.getRawPredictionCol()
classifier = JavaParams._from_java(java_stage.getClassifier())
parallelism = java_stage.getParallelism()
py_stage = cls(featuresCol=featuresCol, labelCol=labelCol, predictionCol=predictionCol,
rawPredictionCol=rawPredictionCol, classifier=classifier,
parallelism=parallelism)
if java_stage.isDefined(java_stage.getParam("weightCol")):
py_stage.setWeightCol(java_stage.getWeightCol())
py_stage._resetUid(java_stage.uid())
return py_stage
def _to_java(self):
"""
Transfer this instance to a Java OneVsRest. Used for ML persistence.
:return: Java object equivalent to this instance.
"""
_java_obj = JavaParams._new_java_obj("org.apache.spark.ml.classification.OneVsRest",
self.uid)
_java_obj.setClassifier(self.getClassifier()._to_java())
_java_obj.setParallelism(self.getParallelism())
_java_obj.setFeaturesCol(self.getFeaturesCol())
_java_obj.setLabelCol(self.getLabelCol())
_java_obj.setPredictionCol(self.getPredictionCol())
if (self.isDefined(self.weightCol) and self.getWeightCol()):
_java_obj.setWeightCol(self.getWeightCol())
_java_obj.setRawPredictionCol(self.getRawPredictionCol())
return _java_obj
def _make_java_param_pair(self, param, value):
"""
Makes a Java param pair.
"""
sc = SparkContext._active_spark_context
param = self._resolveParam(param)
_java_obj = JavaParams._new_java_obj("org.apache.spark.ml.classification.OneVsRest",
self.uid)
java_param = _java_obj.getParam(param.name)
if isinstance(value, JavaParams):
# used in the case of an estimator having another estimator as a parameter
# the reason why this is not in _py2java in common.py is that importing
# Estimator and Model in common.py results in a circular import with inherit_doc
java_value = value._to_java()
else:
java_value = _py2java(sc, value)
return java_param.w(java_value)
def _transfer_param_map_to_java(self, pyParamMap):
"""
Transforms a Python ParamMap into a Java ParamMap.
"""
paramMap = JavaWrapper._new_java_obj("org.apache.spark.ml.param.ParamMap")
for param in self.params:
if param in pyParamMap:
pair = self._make_java_param_pair(param, pyParamMap[param])
paramMap.put([pair])
return paramMap
def _transfer_param_map_from_java(self, javaParamMap):
"""
Transforms a Java ParamMap into a Python ParamMap.
"""
sc = SparkContext._active_spark_context
paramMap = dict()
for pair in javaParamMap.toList():
param = pair.param()
if self.hasParam(str(param.name())):
if param.name() == "classifier":
paramMap[self.getParam(param.name())] = JavaParams._from_java(pair.value())
else:
paramMap[self.getParam(param.name())] = _java2py(sc, pair.value())
return paramMap
class OneVsRestModel(Model, _OneVsRestParams, JavaMLReadable, JavaMLWritable):
"""
Model fitted by OneVsRest.
This stores the models resulting from training k binary classifiers: one for each class.
Each example is scored against all k models, and the model with the highest score
is picked to label the example.
.. versionadded:: 2.0.0
"""
def setFeaturesCol(self, value):
"""
Sets the value of :py:attr:`featuresCol`.
"""
return self._set(featuresCol=value)
def setPredictionCol(self, value):
"""
Sets the value of :py:attr:`predictionCol`.
"""
return self._set(predictionCol=value)
def setRawPredictionCol(self, value):
"""
Sets the value of :py:attr:`rawPredictionCol`.
"""
return self._set(rawPredictionCol=value)
def __init__(self, models):
super(OneVsRestModel, self).__init__()
self.models = models
java_models = [model._to_java() for model in self.models]
sc = SparkContext._active_spark_context
java_models_array = JavaWrapper._new_java_array(java_models,
sc._gateway.jvm.org.apache.spark.ml
.classification.ClassificationModel)
# TODO: need to set metadata
metadata = JavaParams._new_java_obj("org.apache.spark.sql.types.Metadata")
self._java_obj = \
JavaParams._new_java_obj("org.apache.spark.ml.classification.OneVsRestModel",
self.uid, metadata.empty(), java_models_array)
def _transform(self, dataset):
# determine the input columns: these need to be passed through
origCols = dataset.columns
# add an accumulator column to store predictions of all the models
accColName = "mbc$acc" + str(uuid.uuid4())
initUDF = udf(lambda _: [], ArrayType(DoubleType()))
newDataset = dataset.withColumn(accColName, initUDF(dataset[origCols[0]]))
# persist if underlying dataset is not persistent.
handlePersistence = dataset.storageLevel == StorageLevel(False, False, False, False)
if handlePersistence:
newDataset.persist(StorageLevel.MEMORY_AND_DISK)
# update the accumulator column with the result of prediction of models
aggregatedDataset = newDataset
for index, model in enumerate(self.models):
rawPredictionCol = self.getRawPredictionCol()
columns = origCols + [rawPredictionCol, accColName]
# add temporary column to store intermediate scores and update
tmpColName = "mbc$tmp" + str(uuid.uuid4())
updateUDF = udf(
lambda predictions, prediction: predictions + [prediction.tolist()[1]],
ArrayType(DoubleType()))
transformedDataset = model.transform(aggregatedDataset).select(*columns)
updatedDataset = transformedDataset.withColumn(
tmpColName,
updateUDF(transformedDataset[accColName], transformedDataset[rawPredictionCol]))
newColumns = origCols + [tmpColName]
# switch out the intermediate column with the accumulator column
aggregatedDataset = updatedDataset\
.select(*newColumns).withColumnRenamed(tmpColName, accColName)
if handlePersistence:
newDataset.unpersist()
if self.getRawPredictionCol():
def func(predictions):
predArray = []
for x in predictions:
predArray.append(x)
return Vectors.dense(predArray)
rawPredictionUDF = udf(func)
aggregatedDataset = aggregatedDataset.withColumn(
self.getRawPredictionCol(), rawPredictionUDF(aggregatedDataset[accColName]))
if self.getPredictionCol():
# output the index of the classifier with highest confidence as prediction
labelUDF = udf(lambda predictions: float(max(enumerate(predictions),
key=operator.itemgetter(1))[0]), DoubleType())
aggregatedDataset = aggregatedDataset.withColumn(
self.getPredictionCol(), labelUDF(aggregatedDataset[accColName]))
return aggregatedDataset.drop(accColName)
@since("2.0.0")
def copy(self, extra=None):
"""
Creates a copy of this instance with a randomly generated uid
and some extra params. This creates a deep copy of the embedded paramMap,
and copies the embedded and extra parameters over.
:param extra: Extra parameters to copy to the new instance
:return: Copy of this instance
"""
if extra is None:
extra = dict()
newModel = Params.copy(self, extra)
newModel.models = [model.copy(extra) for model in self.models]
return newModel
@classmethod
def _from_java(cls, java_stage):
"""
Given a Java OneVsRestModel, create and return a Python wrapper of it.
Used for ML persistence.
"""
featuresCol = java_stage.getFeaturesCol()
labelCol = java_stage.getLabelCol()
predictionCol = java_stage.getPredictionCol()
classifier = JavaParams._from_java(java_stage.getClassifier())
models = [JavaParams._from_java(model) for model in java_stage.models()]
py_stage = cls(models=models).setPredictionCol(predictionCol)\
.setFeaturesCol(featuresCol)
py_stage._set(labelCol=labelCol)
if java_stage.isDefined(java_stage.getParam("weightCol")):
py_stage._set(weightCol=java_stage.getWeightCol())
py_stage._set(classifier=classifier)
py_stage._resetUid(java_stage.uid())
return py_stage
def _to_java(self):
"""
Transfer this instance to a Java OneVsRestModel. Used for ML persistence.
:return: Java object equivalent to this instance.
"""
sc = SparkContext._active_spark_context
java_models = [model._to_java() for model in self.models]
java_models_array = JavaWrapper._new_java_array(
java_models, sc._gateway.jvm.org.apache.spark.ml.classification.ClassificationModel)
metadata = JavaParams._new_java_obj("org.apache.spark.sql.types.Metadata")
_java_obj = JavaParams._new_java_obj("org.apache.spark.ml.classification.OneVsRestModel",
self.uid, metadata.empty(), java_models_array)
_java_obj.set("classifier", self.getClassifier()._to_java())
_java_obj.set("featuresCol", self.getFeaturesCol())
_java_obj.set("labelCol", self.getLabelCol())
_java_obj.set("predictionCol", self.getPredictionCol())
if (self.isDefined(self.weightCol) and self.getWeightCol()):
_java_obj.set("weightCol", self.getWeightCol())
return _java_obj
@inherit_doc
class FMClassifier(_JavaProbabilisticClassifier, _FactorizationMachinesParams, JavaMLWritable,
JavaMLReadable):
"""
Factorization Machines learning algorithm for classification.
solver Supports:
* gd (normal mini-batch gradient descent)
* adamW (default)
>>> from pyspark.ml.linalg import Vectors
>>> from pyspark.ml.classification import FMClassifier
>>> df = spark.createDataFrame([
... (1.0, Vectors.dense(1.0)),
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
>>> fm = FMClassifier(factorSize=2)
>>> fm.setSeed(11)
FMClassifier...
>>> model = fm.fit(df)
>>> model.getMaxIter()
100
>>> test0 = spark.createDataFrame([
... (Vectors.dense(-1.0),),
... (Vectors.dense(0.5),),
... (Vectors.dense(1.0),),
... (Vectors.dense(2.0),)], ["features"])
>>> model.predictRaw(test0.head().features)
DenseVector([22.13..., -22.13...])
>>> model.predictProbability(test0.head().features)
DenseVector([1.0, 0.0])
>>> model.transform(test0).select("features", "probability").show(10, False)
+--------+------------------------------------------+
|features|probability |
+--------+------------------------------------------+
|[-1.0] |[0.9999999997574736,2.425264676902229E-10]|
|[0.5] |[0.47627851732981163,0.5237214826701884] |
|[1.0] |[5.491554426243495E-4,0.9994508445573757] |
|[2.0] |[2.005766663870645E-10,0.9999999997994233]|
+--------+------------------------------------------+
...
>>> model.intercept
-7.316665276826291
>>> model.linear
DenseVector([14.8232])
>>> model.factors
DenseMatrix(1, 2, [0.0163, -0.0051], 1)
.. versionadded:: 3.0.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction",
factorSize=8, fitIntercept=True, fitLinear=True, regParam=0.0,
miniBatchFraction=1.0, initStd=0.01, maxIter=100, stepSize=1.0,
tol=1e-6, solver="adamW", thresholds=None, seed=None):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", \
factorSize=8, fitIntercept=True, fitLinear=True, regParam=0.0, \
miniBatchFraction=1.0, initStd=0.01, maxIter=100, stepSize=1.0, \
tol=1e-6, solver="adamW", thresholds=None, seed=None)
"""
super(FMClassifier, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.FMClassifier", self.uid)
self._setDefault(factorSize=8, fitIntercept=True, fitLinear=True, regParam=0.0,
miniBatchFraction=1.0, initStd=0.01, maxIter=100, stepSize=1.0,
tol=1e-6, solver="adamW")
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("3.0.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction",
factorSize=8, fitIntercept=True, fitLinear=True, regParam=0.0,
miniBatchFraction=1.0, initStd=0.01, maxIter=100, stepSize=1.0,
tol=1e-6, solver="adamW", thresholds=None, seed=None):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", \
factorSize=8, fitIntercept=True, fitLinear=True, regParam=0.0, \
miniBatchFraction=1.0, initStd=0.01, maxIter=100, stepSize=1.0, \
tol=1e-6, solver="adamW", thresholds=None, seed=None)
Sets Params for FMClassifier.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return FMClassificationModel(java_model)
@since("3.0.0")
def setFactorSize(self, value):
"""
Sets the value of :py:attr:`factorSize`.
"""
return self._set(factorSize=value)
@since("3.0.0")
def setFitLinear(self, value):
"""
Sets the value of :py:attr:`fitLinear`.
"""
return self._set(fitLinear=value)
@since("3.0.0")
def setMiniBatchFraction(self, value):
"""
Sets the value of :py:attr:`miniBatchFraction`.
"""
return self._set(miniBatchFraction=value)
@since("3.0.0")
def setInitStd(self, value):
"""
Sets the value of :py:attr:`initStd`.
"""
return self._set(initStd=value)
@since("3.0.0")
def setMaxIter(self, value):
"""
Sets the value of :py:attr:`maxIter`.
"""
return self._set(maxIter=value)
@since("3.0.0")
def setStepSize(self, value):
"""
Sets the value of :py:attr:`stepSize`.
"""
return self._set(stepSize=value)
@since("3.0.0")
def setTol(self, value):
"""
Sets the value of :py:attr:`tol`.
"""
return self._set(tol=value)
@since("3.0.0")
def setSolver(self, value):
"""
Sets the value of :py:attr:`solver`.
"""
return self._set(solver=value)
@since("3.0.0")
def setSeed(self, value):
"""
Sets the value of :py:attr:`seed`.
"""
return self._set(seed=value)
@since("3.0.0")
def setFitIntercept(self, value):
"""
Sets the value of :py:attr:`fitIntercept`.
"""
return self._set(fitIntercept=value)
@since("3.0.0")
def setRegParam(self, value):
"""
Sets the value of :py:attr:`regParam`.
"""
return self._set(regParam=value)
class FMClassificationModel(_JavaProbabilisticClassificationModel, _FactorizationMachinesParams,
JavaMLWritable, JavaMLReadable):
"""
Model fitted by :class:`FMClassifier`.
.. versionadded:: 3.0.0
"""
@property
@since("3.0.0")
def intercept(self):
"""
Model intercept.
"""
return self._call_java("intercept")
@property
@since("3.0.0")
def linear(self):
"""
Model linear term.
"""
return self._call_java("linear")
@property
@since("3.0.0")
def factors(self):
"""
Model factor term.
"""
return self._call_java("factors")
if __name__ == "__main__":
import doctest
import pyspark.ml.classification
from pyspark.sql import SparkSession
globs = pyspark.ml.classification.__dict__.copy()
# The small batch size here ensures that we see multiple batches,
# even in these small test examples:
spark = SparkSession.builder\
.master("local[2]")\
.appName("ml.classification tests")\
.getOrCreate()
sc = spark.sparkContext
globs['sc'] = sc
globs['spark'] = spark
import tempfile
temp_path = tempfile.mkdtemp()
globs['temp_path'] = temp_path
try:
(failure_count, test_count) = doctest.testmod(globs=globs, optionflags=doctest.ELLIPSIS)
spark.stop()
finally:
from shutil import rmtree
try:
rmtree(temp_path)
except OSError:
pass
if failure_count:
sys.exit(-1)
| 35.793275 | 100 | 0.612249 |
370f72a6b657dc7012dddc8539a629bcd299794e | 2,922 | py | Python | Virtual2038.py | Furcht968/Virtual2038 | 9348cec6288e0095ff535b35422d2c493802c8c6 | [
"MIT"
] | null | null | null | Virtual2038.py | Furcht968/Virtual2038 | 9348cec6288e0095ff535b35422d2c493802c8c6 | [
"MIT"
] | null | null | null | Virtual2038.py | Furcht968/Virtual2038 | 9348cec6288e0095ff535b35422d2c493802c8c6 | [
"MIT"
] | null | null | null | # *****************************************
#
# Virtual2038 - Virtual 2038 Problem Python Software
#
#
# Copyright (c) 2020 Furcht968
# Released under the MIT license
# https://github.com/Furcht968/Virtual2038/blob/master/License/LICENSE.txt
# https://github.com/Furcht968/Virtual2038/blob/master/License/LICENSE_jp.txt
#
#
# *****************************************
import time
import json
from datetime import datetime
import sys
if __name__ == "Virtual2038":
class now():
def __init__(self, bit=32):
bitover = (2**int(bit-1))*2
time32u2 = format(int(time.time()), "b")[-bit:]
time32u10 = int(time32u2, 2)
time32d10 = datetime.fromtimestamp(time32u10)
self.RealTime = time32d10
self.binary = time32u2
self.decimal = time32u10
self.until = bitover-time32u10
if __name__ == "__main__":
if len(sys.argv) == 1:
bit = 31
else:
bit = int(sys.argv[1])-1
with open("config.json") as f:
config = json.loads(f.read())
backcolor = []
textcolor = []
backimage = config["background_image"]
for i in range(0, 6, 2):
backcolor += [int(config["backcolor"][i:i+2], 16)]
textcolor += [int(config["textcolor"][i:i+2], 16)]
bitover = (2**int(bit))*2
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640, 360))
if(bit != 31):
pygame.display.set_caption(f"Virtual2038 on {bit+1}bit")
else:
pygame.display.set_caption(f"Virtual2038")
font = pygame.font.SysFont(None, 32)
font2 = pygame.font.SysFont(None, 70)
pygame.display.set_icon(pygame.image.load('icons/icon.png'))
while(1):
screen.fill(backcolor)
if(backimage != None):
img = pygame.image.load(backimage)
img = pygame.transform.scale(img, (640, 360))
screen.blit(img, (0, 0))
time32u2 = format(int(time.time()), "b")[-bit:]
time32u10 = int(time32u2, 2)
time32d10 = datetime.fromtimestamp(time32u10)
bin = font.render(f"Binary: {time32u2}", True, textcolor)
dec = font.render(f"Decimal: {time32u10}", True, textcolor)
txt = font2.render("RealTime:", True, textcolor)
utc = font2.render(str(time32d10).replace("-", "/"), True, textcolor)
ovrt = f"Until Overflow: {bitover-time32u10}"
if(bitover-time32u10 <= 10):
ovr = font.render(ovrt, True, (255, 0, 0))
else:
ovr = font.render(ovrt, True, textcolor)
screen.blit(bin, (90, 60))
screen.blit(dec, (90, 80))
screen.blit(txt, (90, 140))
screen.blit(utc, (90, 190))
screen.blit(ovr, (90, 270))
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
| 32.466667 | 77 | 0.569815 |
7647170de4ab0620c4d214cce6a5af57a95dc128 | 5,605 | py | Python | backend/modules/aux_fn_ML.py | alexp25/d4w_app_lab | df40e32f524bba8a726ffe788cfb932b45c32f25 | [
"MIT"
] | null | null | null | backend/modules/aux_fn_ML.py | alexp25/d4w_app_lab | df40e32f524bba8a726ffe788cfb932b45c32f25 | [
"MIT"
] | null | null | null | backend/modules/aux_fn_ML.py | alexp25/d4w_app_lab | df40e32f524bba8a726ffe788cfb932b45c32f25 | [
"MIT"
] | null | null | null | from modules.aux_fn import *
import copy
import scipy
# from sklearn.metrics import classification_report
from sklearn.metrics.pairwise import pairwise_distances_argmin
from sklearn.metrics import silhouette_samples, silhouette_score
from sklearn.cluster import KMeans
def run_dual_clustering_on_node_range(data, r, nclusters, nclusters_final, final_centroids=None):
"""
Run dual clustering on specified node range.
The data from a node is an array of arrays
(for each day there is an array of 24 values).
The clusters are calculated separately for each node and added to the cluster array.
Then, there is another clustering on this cluster array which returns
the final clusters for all the network (consumer types in the network)
:param r:
:param nclusters:
:param nclusters_final:
:return:
"""
centroid_vect = []
raw_data_vect = []
if r is None:
r = list(range(0, len(data)))
print("node range: ", r)
# run clustering for each node and save clusters into array
for node_id in r:
res = run_clustering_on_node_id(data, node_id, nclusters)
centroid_vect.append(res)
centroid_vect = get_array_of_arrays(centroid_vect)
raw_data_vect = get_array_of_arrays(raw_data_vect)
n_clusters_total = len(centroid_vect)
centroids_np = np.array(centroid_vect)
# run clustering again for the previous clusters
res = get_centroids(centroids_np, nclusters_final, final_centroids)
centroids_np = np.array(res)
return centroids_np
def get_centroids(data, n_clusters=8, init=None):
if n_clusters is not None:
if init is not None:
kmeans = KMeans(n_clusters=n_clusters, init=init)
else:
kmeans = KMeans(n_clusters=n_clusters)
else:
n_clusters_range = range(2, 10)
max_silhouette_avg = [0] * len(n_clusters_range)
# data = np.array(data)
for (i, k) in enumerate(n_clusters_range):
kmeans = KMeans(n_clusters=k)
a = kmeans.fit_predict(data)
# print(data.shape)
# print(a)
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the formed
# clusters
silhouette_avg = silhouette_score(data, a)
# print("For n_clusters =", k,
# "The average silhouette_score is :", silhouette_avg)
max_silhouette_avg[i] = silhouette_avg
n_clusters = n_clusters_range[max_silhouette_avg.index(max(max_silhouette_avg))]
kmeans = KMeans(n_clusters=n_clusters)
a = kmeans.fit(data)
centroids = a.cluster_centers_
return centroids
def run_clustering_on_node_id(data, node_id, nclusters, partial_sample_until_id=None, add_deviation_value=None):
"""
Run clustering on specified node. The data from the node is an array of arrays
(for each day there is an array of 24 values)
The result is the consumer behaviour over the analyzed time frame
:param node_id:
:param nclusters:
:return:
"""
data = copy.deepcopy(data[node_id]["series"])
if partial_sample_until_id is not None:
data = data[0:partial_sample_until_id]
if add_deviation_value is not None:
data[partial_sample_until_id] += add_deviation_value
if nclusters is not None and nclusters > len(data):
print("node " + str(node_id) + "nclusters > len(data): " + str(nclusters) + "," + str(len(data)))
return [], None, data
res = get_centroids(data, nclusters)
centroids = res
nc = len(centroids)
centroids_np = np.array(centroids)
return centroids_np
def run_clustering_for_each_node_and_concat(data, r, nclusters):
"""
Run clustering on specified node range. The data from a node is an array of arrays
(for each day there is an array of 24 values). The clusters are calculated
separately for each node and added to the cluster array (various consumer
behaviours in the network)
:param start:
:param end:
:param nclusters:
:return:
"""
centroid_vect = []
raw_data_vect = []
if r is None:
r = list(range(0, len(data)))
# run clustering for each node and save clusters into array
for node_id in r:
res = run_clustering_on_node_id(node_id, nclusters)
centroid_vect.append(res)
centroid_vect = get_array_of_arrays(centroid_vect)
centroids_np = np.array(centroid_vect)
return centroids_np
def run_clustering_for_all_nodes_at_once(data, r, nclusters, n_data=None):
"""
Run clustering on specified node. The data from the node is an array of arrays
(for each day there is an array of 24 values)
The result is the consumer behaviour over the analyzed time frame
:param n_data: the number of samples to be used from the data
:param node_id:
:param nclusters:
:return:
"""
if r is None:
r = list(range(0, len(data)))
res_data = []
for id in r:
for (i, s) in enumerate(data[id]["series"]):
if n_data is not None:
if i < n_data:
res_data.append(s)
else:
res_data.append(s)
res_data = np.array(res_data)
res = get_centroids(res_data, nclusters)
centroids = res
centroids_np = np.array(centroids)
return centroids_np | 34.813665 | 113 | 0.65388 |
d1f1451e43947337be833bec0d732fb722ebb211 | 18,908 | py | Python | tests/regressiontests/aggregation_regress/models.py | mrts2/django | 973cf20260cb90b42b0c97d6fe80c988b539ed89 | [
"BSD-3-Clause"
] | 1 | 2016-05-09T13:27:14.000Z | 2016-05-09T13:27:14.000Z | tests/regressiontests/aggregation_regress/models.py | mrts2/django | 973cf20260cb90b42b0c97d6fe80c988b539ed89 | [
"BSD-3-Clause"
] | null | null | null | tests/regressiontests/aggregation_regress/models.py | mrts2/django | 973cf20260cb90b42b0c97d6fe80c988b539ed89 | [
"BSD-3-Clause"
] | null | null | null | # coding: utf-8
import pickle
from django.db import models
from django.conf import settings
try:
sorted
except NameError:
from django.utils.itercompat import sorted # For Python 2.3
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
friends = models.ManyToManyField('self', blank=True)
def __unicode__(self):
return self.name
class Publisher(models.Model):
name = models.CharField(max_length=300)
num_awards = models.IntegerField()
def __unicode__(self):
return self.name
class Book(models.Model):
isbn = models.CharField(max_length=9)
name = models.CharField(max_length=300)
pages = models.IntegerField()
rating = models.FloatField()
price = models.DecimalField(decimal_places=2, max_digits=6)
authors = models.ManyToManyField(Author)
contact = models.ForeignKey(Author, related_name='book_contact_set')
publisher = models.ForeignKey(Publisher)
pubdate = models.DateField()
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
original_opening = models.DateTimeField()
friday_night_closing = models.TimeField()
def __unicode__(self):
return self.name
class Entries(models.Model):
EntryID = models.AutoField(primary_key=True, db_column='Entry ID')
Entry = models.CharField(unique=True, max_length=50)
Exclude = models.BooleanField()
class Clues(models.Model):
ID = models.AutoField(primary_key=True)
EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column = 'Entry ID')
Clue = models.CharField(max_length=150)
class HardbackBook(Book):
weight = models.FloatField()
def __unicode__(self):
return "%s (hardback): %s" % (self.name, self.weight)
__test__ = {'API_TESTS': """
>>> from django.core import management
>>> from django.db.models import get_app, F
# Reset the database representation of this app.
# This will return the database to a clean initial state.
>>> management.call_command('flush', verbosity=0, interactive=False)
>>> from django.db.models import Avg, Sum, Count, Max, Min, StdDev, Variance
# Ordering requests are ignored
>>> Author.objects.all().order_by('name').aggregate(Avg('age'))
{'age__avg': 37.4...}
# Implicit ordering is also ignored
>>> Book.objects.all().aggregate(Sum('pages'))
{'pages__sum': 3703}
# Baseline results
>>> Book.objects.all().aggregate(Sum('pages'), Avg('pages'))
{'pages__sum': 3703, 'pages__avg': 617.1...}
# Empty values query doesn't affect grouping or results
>>> Book.objects.all().values().aggregate(Sum('pages'), Avg('pages'))
{'pages__sum': 3703, 'pages__avg': 617.1...}
# Aggregate overrides extra selected column
>>> Book.objects.all().extra(select={'price_per_page' : 'price / pages'}).aggregate(Sum('pages'))
{'pages__sum': 3703}
# Annotations get combined with extra select clauses
>>> sorted(Book.objects.all().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).get(pk=2).__dict__.items())
[('contact_id', 3), ('id', 2), ('isbn', u'067232959'), ('manufacture_cost', ...11.545...), ('mean_auth_age', 45.0), ('name', u'Sams Teach Yourself Django in 24 Hours'), ('pages', 528), ('price', Decimal("23.09")), ('pubdate', datetime.date(2008, 3, 3)), ('publisher_id', 2), ('rating', 3.0)]
# Order of the annotate/extra in the query doesn't matter
>>> sorted(Book.objects.all().extra(select={'manufacture_cost' : 'price * .5'}).annotate(mean_auth_age=Avg('authors__age')).get(pk=2).__dict__.items())
[('contact_id', 3), ('id', 2), ('isbn', u'067232959'), ('manufacture_cost', ...11.545...), ('mean_auth_age', 45.0), ('name', u'Sams Teach Yourself Django in 24 Hours'), ('pages', 528), ('price', Decimal("23.09")), ('pubdate', datetime.date(2008, 3, 3)), ('publisher_id', 2), ('rating', 3.0)]
# Values queries can be combined with annotate and extra
>>> sorted(Book.objects.all().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).values().get(pk=2).items())
[('contact_id', 3), ('id', 2), ('isbn', u'067232959'), ('manufacture_cost', ...11.545...), ('mean_auth_age', 45.0), ('name', u'Sams Teach Yourself Django in 24 Hours'), ('pages', 528), ('price', Decimal("23.09")), ('pubdate', datetime.date(2008, 3, 3)), ('publisher_id', 2), ('rating', 3.0)]
# The order of the (empty) values, annotate and extra clauses doesn't matter
>>> sorted(Book.objects.all().values().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).get(pk=2).items())
[('contact_id', 3), ('id', 2), ('isbn', u'067232959'), ('manufacture_cost', ...11.545...), ('mean_auth_age', 45.0), ('name', u'Sams Teach Yourself Django in 24 Hours'), ('pages', 528), ('price', Decimal("23.09")), ('pubdate', datetime.date(2008, 3, 3)), ('publisher_id', 2), ('rating', 3.0)]
# If the annotation precedes the values clause, it won't be included
# unless it is explicitly named
>>> sorted(Book.objects.all().annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).values('name').get(pk=1).items())
[('name', u'The Definitive Guide to Django: Web Development Done Right')]
>>> sorted(Book.objects.all().annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).values('name','mean_auth_age').get(pk=1).items())
[('mean_auth_age', 34.5), ('name', u'The Definitive Guide to Django: Web Development Done Right')]
# If an annotation isn't included in the values, it can still be used in a filter
>>> Book.objects.annotate(n_authors=Count('authors')).values('name').filter(n_authors__gt=2)
[{'name': u'Python Web Development with Django'}]
# The annotations are added to values output if values() precedes annotate()
>>> sorted(Book.objects.all().values('name').annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).get(pk=1).items())
[('mean_auth_age', 34.5), ('name', u'The Definitive Guide to Django: Web Development Done Right')]
# Check that all of the objects are getting counted (allow_nulls) and that values respects the amount of objects
>>> len(Author.objects.all().annotate(Avg('friends__age')).values())
9
# Check that consecutive calls to annotate accumulate in the query
>>> Book.objects.values('price').annotate(oldest=Max('authors__age')).order_by('oldest', 'price').annotate(Max('publisher__num_awards'))
[{'price': Decimal("30..."), 'oldest': 35, 'publisher__num_awards__max': 3}, {'price': Decimal("29.69"), 'oldest': 37, 'publisher__num_awards__max': 7}, {'price': Decimal("23.09"), 'oldest': 45, 'publisher__num_awards__max': 1}, {'price': Decimal("75..."), 'oldest': 57, 'publisher__num_awards__max': 9}, {'price': Decimal("82.8..."), 'oldest': 57, 'publisher__num_awards__max': 7}]
# Aggregates can be composed over annotations.
# The return type is derived from the composed aggregate
>>> Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('pages'), Max('price'), Sum('num_authors'), Avg('num_authors'))
{'num_authors__sum': 10, 'num_authors__avg': 1.66..., 'pages__max': 1132, 'price__max': Decimal("82.80")}
# Bad field requests in aggregates are caught and reported
>>> Book.objects.all().aggregate(num_authors=Count('foo'))
Traceback (most recent call last):
...
FieldError: Cannot resolve keyword 'foo' into field. Choices are: authors, contact, hardbackbook, id, isbn, name, pages, price, pubdate, publisher, rating, store
>>> Book.objects.all().annotate(num_authors=Count('foo'))
Traceback (most recent call last):
...
FieldError: Cannot resolve keyword 'foo' into field. Choices are: authors, contact, hardbackbook, id, isbn, name, pages, price, pubdate, publisher, rating, store
>>> Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('foo'))
Traceback (most recent call last):
...
FieldError: Cannot resolve keyword 'foo' into field. Choices are: authors, contact, hardbackbook, id, isbn, name, pages, price, pubdate, publisher, rating, store, num_authors
# Old-style count aggregations can be mixed with new-style
>>> Book.objects.annotate(num_authors=Count('authors')).count()
6
# Non-ordinal, non-computed Aggregates over annotations correctly inherit
# the annotation's internal type if the annotation is ordinal or computed
>>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Max('num_authors'))
{'num_authors__max': 3}
>>> Publisher.objects.annotate(avg_price=Avg('book__price')).aggregate(Max('avg_price'))
{'avg_price__max': 75.0...}
# Aliases are quoted to protected aliases that might be reserved names
>>> Book.objects.aggregate(number=Max('pages'), select=Max('pages'))
{'number': 1132, 'select': 1132}
# Regression for #10064: select_related() plays nice with aggregates
>>> Book.objects.select_related('publisher').annotate(num_authors=Count('authors')).values()[0]
{'rating': 4.0, 'isbn': u'013790395', 'name': u'Artificial Intelligence: A Modern Approach', 'pubdate': datetime.date(1995, 1, 15), 'price': Decimal("82.8..."), 'contact_id': 8, 'id': 5, 'num_authors': 2, 'publisher_id': 3, 'pages': 1132}
# Regression for #10010: exclude on an aggregate field is correctly negated
>>> len(Book.objects.annotate(num_authors=Count('authors')))
6
>>> len(Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=2))
1
>>> len(Book.objects.annotate(num_authors=Count('authors')).exclude(num_authors__gt=2))
5
>>> len(Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__lt=3).exclude(num_authors__lt=2))
2
>>> len(Book.objects.annotate(num_authors=Count('authors')).exclude(num_authors__lt=2).filter(num_authors__lt=3))
2
# Aggregates can be used with F() expressions
# ... where the F() is pushed into the HAVING clause
>>> Publisher.objects.annotate(num_books=Count('book')).filter(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards')
[{'num_books': 1, 'name': u'Morgan Kaufmann', 'num_awards': 9}, {'num_books': 2, 'name': u'Prentice Hall', 'num_awards': 7}]
>>> Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards')
[{'num_books': 2, 'name': u'Apress', 'num_awards': 3}, {'num_books': 0, 'name': u"Jonno's House of Books", 'num_awards': 0}, {'num_books': 1, 'name': u'Sams', 'num_awards': 1}]
# ... and where the F() references an aggregate
>>> Publisher.objects.annotate(num_books=Count('book')).filter(num_awards__gt=2*F('num_books')).order_by('name').values('name','num_books','num_awards')
[{'num_books': 1, 'name': u'Morgan Kaufmann', 'num_awards': 9}, {'num_books': 2, 'name': u'Prentice Hall', 'num_awards': 7}]
>>> Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards')
[{'num_books': 2, 'name': u'Apress', 'num_awards': 3}, {'num_books': 0, 'name': u"Jonno's House of Books", 'num_awards': 0}, {'num_books': 1, 'name': u'Sams', 'num_awards': 1}]
# Tests on fields with non-default table and column names.
>>> Clues.objects.values('EntryID__Entry').annotate(Appearances=Count('EntryID'), Distinct_Clues=Count('Clue', distinct=True))
[]
>>> Entries.objects.annotate(clue_count=Count('clues__ID'))
[]
# Regression for #10089: Check handling of empty result sets with aggregates
>>> Book.objects.filter(id__in=[]).count()
0
>>> Book.objects.filter(id__in=[]).aggregate(num_authors=Count('authors'), avg_authors=Avg('authors'), max_authors=Max('authors'), max_price=Max('price'), max_rating=Max('rating'))
{'max_authors': None, 'max_rating': None, 'num_authors': 0, 'avg_authors': None, 'max_price': None}
>>> Publisher.objects.filter(pk=5).annotate(num_authors=Count('book__authors'), avg_authors=Avg('book__authors'), max_authors=Max('book__authors'), max_price=Max('book__price'), max_rating=Max('book__rating')).values()
[{'max_authors': None, 'name': u"Jonno's House of Books", 'num_awards': 0, 'max_price': None, 'num_authors': 0, 'max_rating': None, 'id': 5, 'avg_authors': None}]
# Regression for #10113 - Fields mentioned in order_by() must be included in the GROUP BY.
# This only becomes a problem when the order_by introduces a new join.
>>> Book.objects.annotate(num_authors=Count('authors')).order_by('publisher__name', 'name')
[<Book: Practical Django Projects>, <Book: The Definitive Guide to Django: Web Development Done Right>, <Book: Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp>, <Book: Artificial Intelligence: A Modern Approach>, <Book: Python Web Development with Django>, <Book: Sams Teach Yourself Django in 24 Hours>]
# Regression for #10127 - Empty select_related() works with annotate
>>> books = Book.objects.all().filter(rating__lt=4.5).select_related().annotate(Avg('authors__age'))
>>> sorted([(b.name, b.authors__age__avg, b.publisher.name, b.contact.name) for b in books])
[(u'Artificial Intelligence: A Modern Approach', 51.5, u'Prentice Hall', u'Peter Norvig'), (u'Practical Django Projects', 29.0, u'Apress', u'James Bennett'), (u'Python Web Development with Django', 30.3..., u'Prentice Hall', u'Jeffrey Forcier'), (u'Sams Teach Yourself Django in 24 Hours', 45.0, u'Sams', u'Brad Dayley')]
# Regression for #10132 - If the values() clause only mentioned extra(select=) columns, those columns are used for grouping
>>> Book.objects.extra(select={'pub':'publisher_id'}).values('pub').annotate(Count('id')).order_by('pub')
[{'pub': 1, 'id__count': 2}, {'pub': 2, 'id__count': 1}, {'pub': 3, 'id__count': 2}, {'pub': 4, 'id__count': 1}]
>>> Book.objects.extra(select={'pub':'publisher_id','foo':'pages'}).values('pub').annotate(Count('id')).order_by('pub')
[{'pub': 1, 'id__count': 2}, {'pub': 2, 'id__count': 1}, {'pub': 3, 'id__count': 2}, {'pub': 4, 'id__count': 1}]
# Regression for #10182 - Queries with aggregate calls are correctly realiased when used in a subquery
>>> ids = Book.objects.filter(pages__gt=100).annotate(n_authors=Count('authors')).filter(n_authors__gt=2).order_by('n_authors')
>>> Book.objects.filter(id__in=ids)
[<Book: Python Web Development with Django>]
# Regression for #10197 -- Queries with aggregates can be pickled.
# First check that pickling is possible at all. No crash = success
>>> qs = Book.objects.annotate(num_authors=Count('authors'))
>>> out = pickle.dumps(qs)
# Then check that the round trip works.
>>> query = qs.query.as_sql()[0]
>>> select_fields = qs.query.select_fields
>>> query2 = pickle.loads(pickle.dumps(qs))
>>> query2.query.as_sql()[0] == query
True
>>> query2.query.select_fields = select_fields
# Regression for #10199 - Aggregate calls clone the original query so the original query can still be used
>>> books = Book.objects.all()
>>> _ = books.aggregate(Avg('authors__age'))
>>> books.all()
[<Book: Artificial Intelligence: A Modern Approach>, <Book: Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp>, <Book: Practical Django Projects>, <Book: Python Web Development with Django>, <Book: Sams Teach Yourself Django in 24 Hours>, <Book: The Definitive Guide to Django: Web Development Done Right>]
# Regression for #10248 - Annotations work with DateQuerySets
>>> Book.objects.annotate(num_authors=Count('authors')).filter(num_authors=2).dates('pubdate', 'day')
[datetime.datetime(1995, 1, 15, 0, 0), datetime.datetime(2007, 12, 6, 0, 0)]
# Regression for #10290 - extra selects with parameters can be used for
# grouping.
>>> qs = Book.objects.all().annotate(mean_auth_age=Avg('authors__age')).extra(select={'sheets' : '(pages + %s) / %s'}, select_params=[1, 2]).order_by('sheets').values('sheets')
>>> [int(x['sheets']) for x in qs]
[150, 175, 224, 264, 473, 566]
# Regression for 10425 - annotations don't get in the way of a count() clause
>>> Book.objects.values('publisher').annotate(Count('publisher')).count()
4
>>> Book.objects.annotate(Count('publisher')).values('publisher').count()
6
>>> publishers = Publisher.objects.filter(id__in=(1,2))
>>> publishers
[<Publisher: Apress>, <Publisher: Sams>]
>>> publishers = publishers.annotate(n_books=models.Count('book'))
>>> publishers[0].n_books
2
>>> publishers
[<Publisher: Apress>, <Publisher: Sams>]
>>> books = Book.objects.filter(publisher__in=publishers)
>>> books
[<Book: Practical Django Projects>, <Book: Sams Teach Yourself Django in 24 Hours>, <Book: The Definitive Guide to Django: Web Development Done Right>]
>>> publishers
[<Publisher: Apress>, <Publisher: Sams>]
# Regression for 10666 - inherited fields work with annotations and aggregations
>>> HardbackBook.objects.aggregate(n_pages=Sum('book_ptr__pages'))
{'n_pages': 2078}
>>> HardbackBook.objects.aggregate(n_pages=Sum('pages'))
{'n_pages': 2078}
>>> HardbackBook.objects.annotate(n_authors=Count('book_ptr__authors')).values('name','n_authors')
[{'n_authors': 2, 'name': u'Artificial Intelligence: A Modern Approach'}, {'n_authors': 1, 'name': u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'}]
>>> HardbackBook.objects.annotate(n_authors=Count('authors')).values('name','n_authors')
[{'n_authors': 2, 'name': u'Artificial Intelligence: A Modern Approach'}, {'n_authors': 1, 'name': u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'}]
# Regression for #10766 - Shouldn't be able to reference an aggregate fields in an an aggregate() call.
>>> Book.objects.all().annotate(mean_age=Avg('authors__age')).annotate(Avg('mean_age'))
Traceback (most recent call last):
...
FieldError: Cannot compute Avg('mean_age'): 'mean_age' is an aggregate
"""
}
if settings.DATABASE_ENGINE != 'sqlite3':
__test__['API_TESTS'] += """
# Stddev and Variance are not guaranteed to be available for SQLite.
>>> Book.objects.aggregate(StdDev('pages'))
{'pages__stddev': 311.46...}
>>> Book.objects.aggregate(StdDev('rating'))
{'rating__stddev': 0.60...}
>>> Book.objects.aggregate(StdDev('price'))
{'price__stddev': 24.16...}
>>> Book.objects.aggregate(StdDev('pages', sample=True))
{'pages__stddev': 341.19...}
>>> Book.objects.aggregate(StdDev('rating', sample=True))
{'rating__stddev': 0.66...}
>>> Book.objects.aggregate(StdDev('price', sample=True))
{'price__stddev': 26.46...}
>>> Book.objects.aggregate(Variance('pages'))
{'pages__variance': 97010.80...}
>>> Book.objects.aggregate(Variance('rating'))
{'rating__variance': 0.36...}
>>> Book.objects.aggregate(Variance('price'))
{'price__variance': 583.77...}
>>> Book.objects.aggregate(Variance('pages', sample=True))
{'pages__variance': 116412.96...}
>>> Book.objects.aggregate(Variance('rating', sample=True))
{'rating__variance': 0.44...}
>>> Book.objects.aggregate(Variance('price', sample=True))
{'price__variance': 700.53...}
"""
| 51.241192 | 382 | 0.708642 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.