hexsha
stringlengths
40
40
size
int64
4
1.02M
ext
stringclasses
8 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
209
max_stars_repo_name
stringlengths
5
121
max_stars_repo_head_hexsha
stringlengths
40
40
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
4
209
max_issues_repo_name
stringlengths
5
121
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
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
4
209
max_forks_repo_name
stringlengths
5
121
max_forks_repo_head_hexsha
stringlengths
40
40
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
4
1.02M
avg_line_length
float64
1.07
66.1k
max_line_length
int64
4
266k
alphanum_fraction
float64
0.01
1
75d4367999961c5433556d37188b1324f556216d
9,665
py
Python
contrib/bitrpc/bitrpc.py
stintcoin/Stintcoin
75b9fc740ed1929bde1f142502f9adbbb630d812
[ "MIT" ]
2
2018-12-04T17:42:46.000Z
2020-02-13T17:49:29.000Z
contrib/bitrpc/bitrpc.py
stintcoin/Stintcoin
75b9fc740ed1929bde1f142502f9adbbb630d812
[ "MIT" ]
null
null
null
contrib/bitrpc/bitrpc.py
stintcoin/Stintcoin
75b9fc740ed1929bde1f142502f9adbbb630d812
[ "MIT" ]
null
null
null
from jsonrpc import ServiceProxy import sys import string import getpass # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:27502") else: access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:27502") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "encryptwallet": try: pwd = getpass.getpass(prompt="Enter passphrase: ") pwd2 = getpass.getpass(prompt="Repeat passphrase: ") if pwd == pwd2: access.encryptwallet(pwd) print "\n---Wallet encrypted. Server stopping, restart to run with encrypted wallet---\n" else: print "\n---Passphrases do not match---\n" except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a Bitcoin address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n" elif cmd == "getaccountaddress": try: acct = raw_input("Enter an account name: ") print access.getaccountaddress(acct) except: print "\n---An error occurred---\n" elif cmd == "getaddressesbyaccount": try: acct = raw_input("Enter an account name: ") print access.getaddressesbyaccount(acct) except: print "\n---An error occurred---\n" elif cmd == "getbalance": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getbalance(acct, mc) except: print access.getbalance() except: print "\n---An error occurred---\n" elif cmd == "getblockbycount": try: height = raw_input("Height: ") print access.getblockbycount(height) except: print "\n---An error occurred---\n" elif cmd == "getblockcount": try: print access.getblockcount() except: print "\n---An error occurred---\n" elif cmd == "getblocknumber": try: print access.getblocknumber() except: print "\n---An error occurred---\n" elif cmd == "getconnectioncount": try: print access.getconnectioncount() except: print "\n---An error occurred---\n" elif cmd == "getdifficulty": try: print access.getdifficulty() except: print "\n---An error occurred---\n" elif cmd == "getgenerate": try: print access.getgenerate() except: print "\n---An error occurred---\n" elif cmd == "gethashespersec": try: print access.gethashespersec() except: print "\n---An error occurred---\n" elif cmd == "getinfo": try: print access.getinfo() except: print "\n---An error occurred---\n" elif cmd == "getnewaddress": try: acct = raw_input("Enter an account name: ") try: print access.getnewaddress(acct) except: print access.getnewaddress() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaccount": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaccount(acct, mc) except: print access.getreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaddress": try: addr = raw_input("Enter a Bitcoin address (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaddress(addr, mc) except: print access.getreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "gettransaction": try: txid = raw_input("Enter a transaction ID: ") print access.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: data = raw_input("Data (optional): ") try: print access.gettransaction(data) except: print access.gettransaction() except: print "\n---An error occurred---\n" elif cmd == "help": try: cmd = raw_input("Command (optional): ") try: print access.help(cmd) except: print access.help() except: print "\n---An error occurred---\n" elif cmd == "listaccounts": try: mc = raw_input("Minimum confirmations (optional): ") try: print access.listaccounts(mc) except: print access.listaccounts() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaccount": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaccount(mc, incemp) except: print access.listreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaddress": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaddress(mc, incemp) except: print access.listreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "listtransactions": try: acct = raw_input("Account (optional): ") count = raw_input("Number of transactions (optional): ") frm = raw_input("Skip (optional):") try: print access.listtransactions(acct, count, frm) except: print access.listtransactions() except: print "\n---An error occurred---\n" elif cmd == "move": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.move(frm, to, amt, mc, comment) except: print access.move(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendfrom": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendfrom(frm, to, amt, mc, comment, commentto) except: print access.sendfrom(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendmany": try: frm = raw_input("From: ") to = raw_input("To (in format address1:amount1,address2:amount2,...): ") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.sendmany(frm,to,mc,comment) except: print access.sendmany(frm,to) except: print "\n---An error occurred---\n" elif cmd == "sendtoaddress": try: to = raw_input("To (in format address1:amount1,address2:amount2,...): ") amt = raw_input("Amount:") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendtoaddress(to,amt,comment,commentto) except: print access.sendtoaddress(to,amt) except: print "\n---An error occurred---\n" elif cmd == "setaccount": try: addr = raw_input("Address: ") acct = raw_input("Account:") print access.setaccount(addr,acct) except: print "\n---An error occurred---\n" elif cmd == "setgenerate": try: gen= raw_input("Generate? (true/false): ") cpus = raw_input("Max processors/cores (-1 for unlimited, optional):") try: print access.setgenerate(gen, cpus) except: print access.setgenerate(gen) except: print "\n---An error occurred---\n" elif cmd == "settxfee": try: amt = raw_input("Amount:") print access.settxfee(amt) except: print "\n---An error occurred---\n" elif cmd == "stop": try: print access.stop() except: print "\n---An error occurred---\n" elif cmd == "validateaddress": try: addr = raw_input("Address: ") print access.validateaddress(addr) except: print "\n---An error occurred---\n" elif cmd == "walletpassphrase": try: pwd = getpass.getpass(prompt="Enter wallet passphrase: ") access.walletpassphrase(pwd, 60) print "\n---Wallet unlocked---\n" except: print "\n---An error occurred---\n" elif cmd == "walletpassphrasechange": try: pwd = getpass.getpass(prompt="Enter old wallet passphrase: ") pwd2 = getpass.getpass(prompt="Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2) print print "\n---Passphrase changed---\n" except: print print "\n---An error occurred---\n" print else: print "Command not found or not supported"
28.594675
101
0.573513
ded5f9a23f4c03aedce76e7701d5db3aeaaa8b95
2,607
py
Python
src/app/main/sms_tools.py
chenweixu/bunnyc_mgr
1243fa951c45c665442212247d682ce3d39aec08
[ "Apache-2.0" ]
null
null
null
src/app/main/sms_tools.py
chenweixu/bunnyc_mgr
1243fa951c45c665442212247d682ce3d39aec08
[ "Apache-2.0" ]
null
null
null
src/app/main/sms_tools.py
chenweixu/bunnyc_mgr
1243fa951c45c665442212247d682ce3d39aec08
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Email: chenwx716@163.com # DateTime: 2017-12-01 15:32:37 __author__ = "chenwx" import hashlib from suds.client import Client from app.main.conf import conf_data from app import work_log class Sms_tools(object): """docstring for Sms_tools""" def __init__(self): super(Sms_tools, self).__init__() def md5s(self, body): m = hashlib.md5() m.update(body.encode("utf8")) return m.hexdigest() def send_mess(self, mobile_list, content): rspXml_body = [] url = conf_data("sms_conf", "url") password = conf_data("sms_conf", "passwd") try: work_log.info(url) work_log.info(mobile_list) work_log.info(content) client = Client(url) except Exception as e: work_log.error("link sms webservice interface url error") work_log.error(str(e)) return 1 for mobile in mobile_list: reqXml = ( """<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SmsServiceReq><SmsList> <Mobile>""" + mobile + """</Mobile> <Contents><![CDATA[""" + content + """]]></Contents></SmsList> </SmsServiceReq>""" ) work_log.debug("-------------------------------------") work_log.debug(str(mobile)) work_log.debug("send sms xml") work_log.debug(str(reqXml)) work_log.debug("-------------------------------------") action = "00" target = "0101" brief = self.md5s(password + action + reqXml + target) try: rspXml = client.service.smsService(target, action, reqXml, brief) work_log.info("send_mess yes-----------------------------") work_log.info(str(mobile)) work_log.info(str(content)) work_log.info("send_mess rspXml---------------------------") work_log.info(str(rspXml)) work_log.info("send_mess yes-----------------------------") except Exception as e: work_log.error("send_mess error----------------------------") work_log.error(str(reqXml)) work_log.error("send_mess error----------------------------") work_log.error(str(e)) work_log.error("send_mess error----------------------------") return 2 rspXml_body.append(rspXml) return rspXml_body
34.302632
86
0.472957
64fd4c08cba646e567331e5ad0c53e36b8dc7d75
28,700
py
Python
diofant/tests/simplify/test_simplify.py
BuildJet/diofant
1895ccbf7da0c3a6a7fb45b7d8529f69a8dcf96b
[ "BSD-3-Clause" ]
null
null
null
diofant/tests/simplify/test_simplify.py
BuildJet/diofant
1895ccbf7da0c3a6a7fb45b7d8529f69a8dcf96b
[ "BSD-3-Clause" ]
null
null
null
diofant/tests/simplify/test_simplify.py
BuildJet/diofant
1895ccbf7da0c3a6a7fb45b7d8529f69a8dcf96b
[ "BSD-3-Clause" ]
null
null
null
import pytest from diofant import (Add, Basic, E, Eq, Float, Function, GoldenRatio, I, Integer, Integral, Lt, Matrix, MatrixSymbol, Mul, Number, Piecewise, Rational, Sum, Symbol, acos, asin, atan, besseli, besselj, besselsimp, binomial, cancel, cbrt, combsimp, cos, cosh, cosine_transform, count_ops, diff, erf, exp, exp_polar, expand, expand_multinomial, factor, factorial, gamma, hyper, hypersimp, integrate, ln, log, logcombine, nsimplify, oo, pi, posify, rad, root, separatevars, sign, signsimp, simplify, sin, sinh, solve, sqrt, sqrtdenest, sstr, symbols, tan, true, zoo) from diofant.abc import (R, a, b, c, d, e, f, g, h, i, k, m, n, r, s, t, w, x, y, z) from diofant.core.mul import _keep_coeff from diofant.simplify.simplify import clear_coefficients, nthroot __all__ = () def test_sympyissue_7263(): assert abs((simplify(30.8**2 - 82.5**2 * sin(rad(11.6))**2)).evalf(strict=False) - 673.447451402970) < 1e-12 def test_factorial_simplify(): # There are more tests in test_factorials.py. These are just to # ensure that simplify() calls factorial_simplify correctly assert simplify(factorial(x)/x) == factorial(x - 1) assert simplify(factorial(factorial(x))) == factorial(factorial(x)) def test_simplify_expr(): A = Symbol('A') f = Function('f') assert all(simplify(tmp) == tmp for tmp in [I, E, oo, x, -x, -oo, -E, -I]) e = 1/x + 1/y assert e != (x + y)/(x*y) assert simplify(e) == (x + y)/(x*y) e = A**2*s**4/(4*pi*k*m**3) assert simplify(e) == e e = (4 + 4*x - 2*(2 + 2*x))/(2 + 2*x) assert simplify(e) == 0 e = (-4*x*y**2 - 2*y**3 - 2*x**2*y)/(x + y)**2 assert simplify(e) == -2*y e = -x - y - (x + y)**(-1)*y**2 + (x + y)**(-1)*x**2 assert simplify(e) == -2*y e = (x + x*y)/x assert simplify(e) == 1 + y e = (f(x) + y*f(x))/f(x) assert simplify(e) == 1 + y e = (2 * (1/n - cos(n * pi)/n))/pi assert simplify(e) == (-cos(pi*n) + 1)/(pi*n)*2 e = integrate(1/(x**3 + 1), x).diff(x) assert simplify(e) == 1/(x**3 + 1) e = integrate(x/(x**2 + 3*x + 1), x).diff(x) assert simplify(e) == x/(x**2 + 3*x + 1) f = Symbol('f') A = Matrix([[2*k - m*w**2, -k], [-k, k - m*w**2]]).inv() assert simplify((A*Matrix([0, f]))[1]) == \ -f*(2*k - m*w**2)/(k**2 - (k - m*w**2)*(2*k - m*w**2)) f = -x + y/(z + t) + z*x/(z + t) + z*a/(z + t) + t*x/(z + t) assert simplify(f) == (y + a*z)/(z + t) A, B = symbols('A,B', commutative=False) assert simplify(A*B - B*A) == A*B - B*A assert simplify(A/(1 + y/x)) == x*A/(x + y) assert simplify(A*(1/x + 1/y)) == A/x + A/y # (x + y)*A/(x*y) assert simplify(log(2) + log(3)) == log(6) assert simplify(log(2*x) - log(2)) == log(x) assert simplify(hyper([], [], x)) == exp(x) def test_sympyissue_3557(): f_1 = x*a + y*b + z*c - 1 f_2 = x*d + y*e + z*f - 1 f_3 = x*g + y*h + z*i - 1 solutions = solve([f_1, f_2, f_3], x, y, z, simplify=False) assert simplify(solutions[0][y]) == \ (a*i + c*d + f*g - a*f - c*g - d*i) / \ (a*e*i + b*f*g + c*d*h - a*f*h - b*d*i - c*e*g) def test_simplify_other(): assert simplify(sin(x)**2 + cos(x)**2) == 1 assert simplify(gamma(x + 1)/gamma(x)) == x assert simplify(sin(x)**2 + cos(x)**2 + factorial(x)/gamma(x)) == 1 + x assert simplify( Eq(sin(x)**2 + cos(x)**2, factorial(x)/gamma(x))) == Eq(x, 1) nc = symbols('nc', commutative=False) assert simplify(x + x*nc) == x*(1 + nc) # issue sympy/sympy#6123 # f = exp(-I*(k*sqrt(t) + x/(2*sqrt(t)))**2) # ans = integrate(f, (k, -oo, oo), conds='none') ans = (I*(-pi*x*exp(-3*I*pi/4 + I*x**2/(4*t))*erf(x*exp(-3*I*pi/4) / (2*sqrt(t)))/(2*sqrt(t)) + pi*x*exp(-3*I*pi/4 + I*x**2/(4*t)) / (2*sqrt(t)))*exp(-I*x**2/(4*t))/(sqrt(pi)*x) - I*sqrt(pi) * (-erf(x*exp(I*pi/4)/(2*sqrt(t))) + 1)*exp(I*pi/4)/(2*sqrt(t))) assert simplify(ans) == -(-1)**Rational(3, 4)*sqrt(pi)/sqrt(t) # issue sympy/sympy#6370 assert simplify(2**(2 + x)/4) == 2**x def test_simplify_complex(): cosAsExp = cos(x)._eval_rewrite_as_exp(x) tanAsExp = tan(x)._eval_rewrite_as_exp(x) assert simplify(cosAsExp*tanAsExp).expand() == ( sin(x))._eval_rewrite_as_exp(x).expand() # issue sympy/sympy#4341 def test_simplify_ratio(): # roots of x**3-3*x+5 roots = [(Rational(1, 2) - sqrt(3)*I/2) * cbrt(sqrt(21)/2 + Rational(5, 2)) + 1/((Rational(1, 2) - sqrt(3)*I/2)*cbrt(sqrt(21)/2 + Rational(5, 2))), 1/((Rational(1, 2) + sqrt(3)*I/2) * cbrt(sqrt(21)/2 + Rational(5, 2))) + (Rational(1, 2) + sqrt(3)*I/2)*cbrt(sqrt(21)/2 + Rational(5, 2)), -cbrt(sqrt(21)/2 + Rational(5, 2)) - 1/cbrt(sqrt(21)/2 + Rational(5, 2))] for root in roots: assert count_ops(simplify(root, ratio=1)) <= count_ops(root) # If ratio=oo, simplify() is always applied: assert simplify(root, ratio=oo) is not root def test_simplify_measure(): def measure1(expr): return len(str(expr)) def measure2(expr): return -count_ops(expr) # Return the most complicated result expr = (x + 1)/(x + sin(x)**2 + cos(x)**2) assert measure1(simplify(expr, measure=measure1)) <= measure1(expr) assert measure2(simplify(expr, measure=measure2)) <= measure2(expr) expr2 = Eq(sin(x)**2 + cos(x)**2, 1) assert measure1(simplify(expr2, measure=measure1)) <= measure1(expr2) assert measure2(simplify(expr2, measure=measure2)) <= measure2(expr2) def test_simplify_sympyissue_4407(): assert simplify(exp(-Rational(1, 2)) + exp(-Rational(3, 2))) == \ (1 + E)*exp(-Rational(3, 2)) def test_sympyissue_5652(): assert simplify(E + exp(-E)) == exp(-E) + E n = symbols('n', commutative=False) assert simplify(n + n**(-n)) == n + n**(-n) def test_simplify_fail1(): e = (x + y)**2/(-4*x*y**2 - 2*y**3 - 2*x**2*y) assert simplify(e) == 1 / (-2*y) def test_nthroot(): assert nthroot(90 + 34*sqrt(7), 3) == sqrt(7) + 3 q = 1 + sqrt(2) - 2*sqrt(3) + sqrt(6) + sqrt(7) assert nthroot(expand_multinomial(q**3), 3) == q assert nthroot(41 + 29*sqrt(2), 5) == 1 + sqrt(2) assert nthroot(-41 - 29*sqrt(2), 5) == -1 - sqrt(2) expr = 1320*sqrt(10) + 4216 + 2576*sqrt(6) + 1640*sqrt(15) assert nthroot(expr, 5) == 1 + sqrt(6) + sqrt(15) q = 1 + sqrt(2) + sqrt(3) + sqrt(5) assert expand_multinomial(nthroot(expand_multinomial(q**5), 5)) == q q = 1 + sqrt(2) + 7*sqrt(6) + 2*sqrt(10) assert nthroot(expand_multinomial(q**5), 5, 8) == q q = 1 + sqrt(2) - 2*sqrt(3) + 1171*sqrt(6) assert nthroot(expand_multinomial(q**3), 3) == q assert nthroot(expand_multinomial(q**6), 6) == q @pytest.mark.slow def test_nthroot1(): q = 1 + sqrt(2) + sqrt(3) + Rational(1, 10)**20 p = expand_multinomial(q**5) assert nthroot(p, 5) == q q = 1 + sqrt(2) + sqrt(3) + Rational(1, 10)**30 p = expand_multinomial(q**5) assert nthroot(p, 5) == q def test_separatevars(): n = Symbol('n') assert separatevars(2*n*x*z + 2*x*y*z) == 2*x*z*(n + y) assert separatevars(x*z + x*y*z) == x*z*(1 + y) assert separatevars(pi*x*z + pi*x*y*z) == pi*x*z*(1 + y) assert separatevars(x*y**2*sin(x) + x*sin(x)*sin(y)) == \ x*(sin(y) + y**2)*sin(x) assert separatevars(x*exp(x + y) + x*exp(x)) == x*(1 + exp(y))*exp(x) assert separatevars((x*(y + 1))**z).is_Pow # != x**z*(1 + y)**z assert separatevars(1 + x + y + x*y) == (x + 1)*(y + 1) assert separatevars(y/pi*exp(-(z - x)/cos(n))) == \ y*exp(x/cos(n))*exp(-z/cos(n))/pi assert separatevars((x + y)*(x - y) + y**2 + 2*x + 1) == (x + 1)**2 # issue sympy/sympy#4858 p = Symbol('p', positive=True) assert separatevars(sqrt(p**2 + x*p**2)) == p*sqrt(1 + x) assert separatevars(sqrt(y*(p**2 + x*p**2))) == p*sqrt(y*(1 + x)) assert separatevars(sqrt(y*(p**2 + x*p**2)), force=True) == \ p*sqrt(y)*sqrt(1 + x) # issue sympy/sympy#4865 assert separatevars(sqrt(x*y)).is_Pow assert separatevars(sqrt(x*y), force=True) == sqrt(x)*sqrt(y) # issue sympy/sympy#4957 # any type sequence for symbols is fine assert separatevars(((2*x + 2)*y), dict=True, symbols=()) == \ {'coeff': 1, x: 2*x + 2, y: y} # separable assert separatevars(((2*x + 2)*y), dict=True, symbols=[x]) == \ {'coeff': y, x: 2*x + 2} assert separatevars(((2*x + 2)*y), dict=True, symbols=[]) == \ {'coeff': 1, x: 2*x + 2, y: y} assert separatevars(((2*x + 2)*y), dict=True) == \ {'coeff': 1, x: 2*x + 2, y: y} assert separatevars(((2*x + 2)*y), dict=True, symbols=None) == \ {'coeff': y*(2*x + 2)} # not separable assert separatevars(3, dict=True) is None assert separatevars(2*x + y, dict=True, symbols=()) is None assert separatevars(2*x + y, dict=True) is None assert separatevars(2*x + y, dict=True, symbols=None) == {'coeff': 2*x + y} # issue sympy/sympy#4808 n, m = symbols('n,m', commutative=False) assert separatevars(m + n*m) == (1 + n)*m assert separatevars(x + x*n) == x*(1 + n) # issue sympy/sympy#4910 f = Function('f') assert separatevars(f(x) + x*f(x)) == f(x) + x*f(x) # a noncommutable object present eq = x*(1 + hyper((), (), y*z)) assert separatevars(eq) == eq def test_separatevars_advanced_factor(): x, y = symbols('x,y') assert (separatevars(1 + log(x)*log(y) + log(x) + log(y)) == (log(x) + 1)*(log(y) + 1)) assert (separatevars(1 + x - log(z) - x*log(z) - exp(y)*log(z) - x*exp(y)*log(z) + x*exp(y) + exp(y)) == -((exp(y) + 1) * (x + 1)*(log(z) - 1))) x, y = symbols('x,y', positive=True) assert (separatevars(1 + log(x**log(y)) + log(x*y)) == (log(x) + 1)*(log(y) + 1)) def test_hypersimp(): n, k = symbols('n,k', integer=True) assert hypersimp(factorial(k), k) == k + 1 assert hypersimp(factorial(k**2), k) is None assert hypersimp(1/factorial(k), k) == 1/(k + 1) assert hypersimp(2**k/factorial(k)**2, k) == 2/(k + 1)**2 assert hypersimp(binomial(n, k), k) == (n - k)/(k + 1) assert hypersimp(binomial(n + 1, k), k) == (n - k + 1)/(k + 1) term = (4*k + 1)*factorial(k)/factorial(2*k + 1) assert hypersimp(term, k) == ((4*k + 5)/(3 + 14*k + 8*k**2))/2 term = 1/((2*k - 1)*factorial(2*k + 1)) assert hypersimp(term, k) == (k - Rational(1, 2))/((k + 1)*(2*k + 1)*(2*k + 3)) term = binomial(n, k)*(-1)**k/factorial(k) assert hypersimp(term, k) == (k - n)/(k + 1)**2 assert hypersimp(2**(I*k) * 2**k, k) == 2**(1 + I) def test_nsimplify(): assert nsimplify(0) == 0 assert nsimplify(-1) == -1 assert nsimplify(1) == 1 assert nsimplify(1 + x) == 1 + x assert nsimplify(2.7) == Rational(27, 10) assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5))/2 assert nsimplify((1 + sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2 assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2 assert nsimplify(exp(5*pi*I/3, evaluate=False)) == Rational(1, 2) - sqrt(3)*I/2 assert nsimplify(sin(3*pi/5, evaluate=False)) == sqrt(sqrt(5)/8 + Rational(5, 8)) assert nsimplify(sqrt(atan('1', evaluate=False))*(2 + I), [pi]) == \ sqrt(pi) + sqrt(pi)/2*I assert nsimplify(2 + exp(2*atan('1/4')*I)) == Rational(49, 17) + 8*I/17 assert nsimplify(pi, tolerance=0.01) == Rational(22, 7) assert nsimplify(pi, tolerance=0.001) == Rational(355, 113) assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3) assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504) assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == cbrt(2) assert nsimplify(x + .5, rational=True) == Rational(1, 2) + x assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x assert nsimplify(log(3).evalf(), rational=True) == Rational(109861228866811, 100000000000000) assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi*log(2)/8 assert nsimplify(Float(0.272198261287950).evalf(3), [pi, log(2)]) == \ -pi/4 - log(2) + Rational(7, 4) assert nsimplify(x/7.0) == x/7 assert nsimplify(pi/1e2) == pi/100 assert nsimplify(pi/1e2, rational=False) == pi/100.0 assert nsimplify(pi/1e-7) == 10000000*pi assert not nsimplify( factor(-3.0*z**2*(z**2)**(-2.5) + 3*(z**2)**(-1.5))).atoms(Float) e = x**0.0 assert e.is_Pow and nsimplify(x**0.0) == 1 assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3) assert nsimplify(3.333333, tolerance=0.01, rational=True) == Rational(10, 3) assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3) assert nsimplify(3.666666, tolerance=0.01, rational=True) == Rational(11, 3) assert nsimplify(33, tolerance=10, rational=True) == 33 assert nsimplify(33.33, tolerance=10, rational=True) == 30 assert nsimplify(37.76, tolerance=10, rational=True) == 40 assert nsimplify(-203.1) == -Rational(2031, 10) assert nsimplify(+.2, tolerance=0) == Rational(+1, 5) assert nsimplify(-.2, tolerance=0) == Rational(-1, 5) assert nsimplify(.2222, tolerance=0) == Rational(1111, 5000) assert nsimplify(-.2222, tolerance=0) == -Rational(1111, 5000) # issue sympy/sympy#7211, PR sympy/sympy#4112 assert nsimplify(Float(2e-8)) == Rational(1, 50000000) # issue sympy/sympy#7322 direct test assert nsimplify(1e-42, rational=True) != 0 # issue sympy/sympy#10336 inf = Float('inf') infs = (-oo, oo, inf, -inf) for i in infs: ans = sign(i)*oo assert nsimplify(i) == ans assert nsimplify(i + x) == x + ans assert nsimplify(Sum(1/n**2, (n, 1, oo)), [pi]) == pi**2/6 def test_sympyissue_9448(): expr = (1/(1 - (-1)**Rational(2, 3) - cbrt(-1)) + 1/(1 + (-1)**Rational(2, 3) + cbrt(-1))) assert nsimplify(expr) == Rational(1, 2) def test_extract_minus_sign(): assert simplify(-x/-y) == x/y assert simplify(-x/y) == -x/y assert simplify(x/y) == x/y assert simplify(x/-y) == -x/y assert simplify(-x/0) == zoo*x assert simplify(Rational(-5, 0)) == zoo assert simplify(-a*x/(-y - b)) == a*x/(b + y) def test_diff(): f = Function('f') g = Function('g') assert simplify(g(x).diff(x)*f(x).diff(x) - f(x).diff(x)*g(x).diff(x)) == 0 assert simplify(2*f(x)*f(x).diff(x) - diff(f(x)**2, x)) == 0 assert simplify(diff(1/f(x), x) + f(x).diff(x)/f(x)**2) == 0 assert simplify(f(x).diff(x, y) - f(x).diff(y, x)) == 0 def test_logcombine_1(): z, w = symbols('z,w', positive=True) b = Symbol('b', real=True) assert logcombine(log(x) + 2*log(y)) == log(x) + 2*log(y) assert logcombine(log(x) + 2*log(y), force=True) == log(x*y**2) assert logcombine(a*log(w) + log(z)) == a*log(w) + log(z) assert logcombine(b*log(z) + b*log(x)) == log(z**b) + b*log(x) assert logcombine(b*log(z) - log(w)) == log(z**b/w) assert logcombine(log(x)*log(z)) == log(x)*log(z) assert logcombine(log(w)*log(x)) == log(w)*log(x) assert logcombine(cos(-2*log(z) + b*log(w))) in [cos(log(w**b/z**2)), cos(log(z**2/w**b))] assert logcombine(log(log(x) - log(y)) - log(z), force=True) == \ log(log(x/y)/z) assert logcombine((2 + I)*log(x), force=True) == (2 + I)*log(x) assert logcombine((x**2 + log(x) - log(y))/(x*y), force=True) == \ (x**2 + log(x/y))/(x*y) # the following could also give log(z*x**log(y**2)), what we # are testing is that a canonical result is obtained assert logcombine(log(x)*2*log(y) + log(z), force=True) == \ log(z*y**log(x**2)) assert logcombine((x*y + sqrt(x**4 + y**4) + log(x) - log(y))/(pi*x**Rational(2, 3) * sqrt(y)**3), force=True) == ( x*y + sqrt(x**4 + y**4) + log(x/y))/(pi*x**Rational(2, 3) * y**Rational(3, 2)) assert logcombine(gamma(-log(x/y))*acos(-log(x/y)), force=True) == \ acos(-log(x/y))*gamma(-log(x/y)) assert logcombine(2*log(z)*log(w)*log(x) + log(z) + log(w)) == \ log(z**log(w**2))*log(x) + log(w*z) assert logcombine(3*log(w) + 3*log(z)) == log(w**3*z**3) assert logcombine(x*(y + 1) + log(2) + log(3)) == x*(y + 1) + log(6) assert logcombine((x + y)*log(w) + (-x - y)*log(3)) == (x + y)*log(w/3) def test_logcombine_complex_coeff(): i = Integral((sin(x**2) + cos(x**3))/x, x) assert logcombine(i, force=True) == i assert logcombine(i + 2*log(x), force=True) == i + log(x**2) def test_posify(): assert sstr(posify( x + Symbol('p', positive=True) + Symbol('n', negative=True))) == '(n + p + _x, {_x: x})' eq, rep = posify(1/x) assert log(eq).expand().subs(rep) == -log(x) assert sstr(posify([x, 1 + x])) == '([_x, _x + 1], {_x: x})' p = symbols('p', positive=True) n = symbols('n', negative=True) orig = [x, n, p] modified, reps = posify(orig) assert sstr(modified) == '[_x, n, p]' assert [w.subs(reps) for w in modified] == orig assert sstr(Integral(posify(1/x + y)[0], (y, 1, 3)).expand()) == \ 'Integral(1/_x, (y, 1, 3)) + Integral(_y, (y, 1, 3))' assert sstr(Sum(posify(1/x**n)[0], (n, 1, 3)).expand()) == \ 'Sum(_x**(-n), (n, 1, 3))' def test_sympyissue_4194(): # simplify should call cancel f = Function('f') assert simplify((4*x + 6*f(y))/(2*x + 3*f(y))) == 2 def test_as_content_primitive(): # although the _as_content_primitive methods do not alter the underlying structure, # the as_content_primitive function will touch up the expression and join # bases that would otherwise have not been joined. assert ((x*(2 + 2*x)*(3*x + 3)**2)).as_content_primitive() == \ (18, x*(x + 1)**3) assert (2 + 2*x + 2*y*(3 + 3*y)).as_content_primitive() == \ (2, x + 3*y*(y + 1) + 1) assert ((2 + 6*x)**2).as_content_primitive() == (4, (3*x + 1)**2) assert ((2 + 6*x)**(2*y)).as_content_primitive() == \ (1, (_keep_coeff(Integer(2), (3*x + 1)))**(2*y)) assert (5 + 10*x + 2*y*(3 + 3*y)).as_content_primitive() == \ (1, 10*x + 6*y*(y + 1) + 5) assert ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive() == \ (11, x*(y + 1)) assert ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive() == \ (121, x**2*(y + 1)**2) assert (y**2).as_content_primitive() == (1, y**2) assert oo.as_content_primitive() == (1, oo) eq = x**(2 + y) assert (eq).as_content_primitive() == (1, eq) assert (Rational(1, 2)**(2 + x)).as_content_primitive() == (Rational(1, 4), 2**-x) assert (Rational(-1, 2)**(2 + x)).as_content_primitive() == \ (Rational(1, 4), Rational(-1, 2)**x) assert (Rational(-1, 2)**(2 + x)).as_content_primitive() == \ (Rational(1, 4), Rational(-1, 2)**x) assert (4**((1 + y)/2)).as_content_primitive() == (2, 4**(y/2)) assert (3**((1 + y)/2)).as_content_primitive() == \ (1, 3**(Mul(Rational(1, 2), 1 + y, evaluate=False))) assert (5**Rational(3, 4)).as_content_primitive() == (1, 5**Rational(3, 4)) assert (5**Rational(7, 4)).as_content_primitive() == (5, 5**Rational(3, 4)) assert Add(5*z/7, 0.5*x, 3*y/2, evaluate=False).as_content_primitive() == \ (Rational(1, 14), 7.0*x + 21*y + 10*z) assert (2**Rational(3, 4) + root(2, 4)*sqrt(3)).as_content_primitive(radical=True) == \ (1, root(2, 4)*(sqrt(2) + sqrt(3))) def test_signsimp(): e = x*(-x + 1) + x*(x - 1) assert signsimp(Eq(e, 0)) is true assert abs(x - 1) == abs(1 - x) def test_besselsimp(): assert besselsimp(exp(-I*pi*y/2)*besseli(y, z*exp_polar(I*pi/2))) == \ besselj(y, z) assert besselsimp(exp(-I*pi*a/2)*besseli(a, 2*sqrt(x)*exp_polar(I*pi/2))) == \ besselj(a, 2*sqrt(x)) assert besselsimp(sqrt(2)*sqrt(pi)*root(x, 4)*exp(I*pi/4)*exp(-I*pi*a/2) * besseli(-Rational(1, 2), sqrt(x)*exp_polar(I*pi/2)) * besseli(a, sqrt(x)*exp_polar(I*pi/2))/2) == \ besselj(a, sqrt(x)) * cos(sqrt(x)) assert besselsimp(besseli(Rational(-1, 2), z)) == \ sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besseli(a, z*exp_polar(-I*pi/2))) == \ exp(-I*pi*a/2)*besselj(a, z) assert cosine_transform(1/t*sin(a/t), t, y) == \ sqrt(2)*sqrt(pi)*besselj(0, 2*sqrt(a)*sqrt(y))/2 def test_Piecewise(): e1 = x*(x + y) - y*(x + y) e2 = sin(x)**2 + cos(x)**2 e3 = expand((x + y)*y/x) s1 = simplify(e1) s2 = simplify(e2) s3 = simplify(e3) assert simplify(Piecewise((e1, x < e2), (e3, True))) == \ Piecewise((s1, x < s2), (s3, True)) def test_polymorphism(): class A(Basic): def _eval_simplify(self, **kwargs): return 1 a = A(5, 2) assert simplify(a) == 1 def test_sympyissue_from_PR1599(): n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True) assert simplify(I*sqrt(n1)) == -sqrt(-n1) def test_sympyissue_6811(): eq = (x + 2*y)*(2*x + 2) assert simplify(eq) == (x + 1)*(x + 2*y)*2 # reject the 2-arg Mul -- these are a headache for test writing assert simplify(eq.expand()) == 2*x**2 + 4*x*y + 2*x + 4*y def test_sympyissue_6920(): e = [cos(x) + I*sin(x), cos(x) - I*sin(x), cosh(x) - sinh(x), cosh(x) + sinh(x)] ok = [exp(I*x), exp(-I*x), exp(-x), exp(x)] # wrap in f to show that the change happens wherever ei occurs f = Function('f') assert [simplify(f(ei)).args[0] for ei in e] == ok def test_sympyissue_7001(): assert (simplify(-(r*Piecewise((4*pi/3, r <= R), (-8*pi*R**3/(3*r**3), True)) + 2*Piecewise((4*pi*r/3, r <= R), (4*pi*R**3/(3*r**2), True)))/(4*pi*r)) == Piecewise((-1, r <= R), (0, True))) def test_inequality_no_auto_simplify(): # no simplify on creation but can be simplified lhs = cos(x)**2 + sin(x)**2 rhs = 2 e = Lt(lhs, rhs) assert e == Lt(lhs, rhs, evaluate=False) assert simplify(e) def test_sympyissue_9398(): assert cancel(1e-14) != 0 assert cancel(1e-14*I) != 0 assert simplify(1e-14) != 0 assert simplify(1e-14*I) != 0 assert (I*Number(1.)*Number(10)**Number(-14)).simplify() != 0 assert cancel(1e-20) != 0 assert cancel(1e-20*I) != 0 assert simplify(1e-20) != 0 assert simplify(1e-20*I) != 0 assert cancel(1e-100) != 0 assert cancel(1e-100*I) != 0 assert simplify(1e-100) != 0 assert simplify(1e-100*I) != 0 f = Float('1e-1000', 15) assert cancel(f) != 0 assert cancel(f*I) != 0 assert simplify(f) != 0 assert simplify(f*I) != 0 def test_sympyissue_6249(): A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) p = A*B - B*A assert cancel(p) == p assert combsimp(p) == p assert factor(p) == p assert separatevars(p) == p assert sqrtdenest(p) == p M = MatrixSymbol('M', 2, 1) assert simplify(M[0]/2) == M[0]/2 def test_clear_coefficients(): assert clear_coefficients(4*y*(6*x + 3)) == (y*(2*x + 1), 0) assert clear_coefficients(4*y*(6*x + 3) - 2) == (y*(2*x + 1), Rational(1, 6)) assert clear_coefficients(4*y*(6*x + 3) - 2, x) == (y*(2*x + 1), x/12 + Rational(1, 6)) assert clear_coefficients(sqrt(2) - 2) == (sqrt(2), 2) assert clear_coefficients(4*sqrt(2) - 2) == (sqrt(2), Rational(1, 2)) assert clear_coefficients(Integer(3), x) == (0, x - 3) assert clear_coefficients(oo, x) == (oo, x) assert clear_coefficients(-pi, x) == (pi, -x) assert clear_coefficients(2 - pi/3, x) == (pi, -3*x + 6) def test_sympyissue_9296(): q = symbols('q_1:5') dq = symbols('dq_1:5') a = (dq[0]*(0.1*(0.01*sin(q[2]) + 0.01*sin(q[1] + q[2]))*cos(q[1] + q[2]) + 0.01*(0.1*sin(q[2]) + 0.1*sin(q[1] + q[2]))*cos(q[1] + q[2]) + 0.05*(-0.05*cos(q[1]) - 0.025)*sin(q[1]) + 0.01*(-0.1*cos(q[2]) - 0.1*cos(q[1] + q[2]))*sin(q[1] + q[2]) + 0.1*(-0.01*cos(q[2]) - 0.01*cos(q[1] + q[2]))*sin(q[1] + q[2]) + 0.0025*sin(q[1])*cos(q[1]) - 0.00125*sin(q[1]))) b = dq[1]*(-0.0025*sin(q[1]) + 0.002*sin(q[2])*cos(q[1] + q[2]) - 0.002*sin(q[1] + q[2])*cos(q[2])) r = simplify(a + b).replace(lambda x: x.is_Float and abs(x) < 1e-15, lambda x: 0) assert r == (-Float('0.0045000000000000005', dps=15)*dq[0]*sin(q[1]) - Float('0.0045000000000000005', dps=15)*dq[1]*sin(q[1])) def test_sympyissue_9630(): psi = (-0.999999972295856*sin(13.3579685223169*x/y) + 1.0*cos(13.3579685223169*x/y) + 0.999999972295856*sinh(13.3579685223169*x/y) - 1.0*cosh(13.3579685223169*x/y)) assert simplify(psi) == psi def test_sympyissue_12792(): expr = (0.25*y*sin(x)/(0.25*cos(x)**2 - 1.0*cos(x) + 1) + (z - 0.5)*(-0.25*y*sin(x)*cos(x)**2 / (0.0625*cos(x)**4 - 0.5*cos(x)**3 + 1.5*cos(x)**2 - 2.0*cos(x) + 1) + 0.5*y*sin(x)*cos(x)/(0.0625*cos(x)**4 - 0.5*cos(x)**3 + 1.5*cos(x)**2 - 2.0*cos(x) + 1) + 0.25*cos(x)**3 / (0.0625*cos(x)**4 - 0.5*cos(x)**3 + 1.5*cos(x)**2 - 2.0*cos(x) + 1) - 1.0*cos(x)**2/(0.0625*cos(x)**4 - 0.5*cos(x)**3 + 1.5*cos(x)**2 - 2.0*cos(x) + 1) + 1.0*cos(x)/(0.0625*cos(x)**4 - 0.5*cos(x)**3 + 1.5*cos(x)**2 - 2.0*cos(x) + 1) - 1/(0.25*cos(x)**2 - 1.0*cos(x) + 1)) - 0.25*cos(x) / (0.25*cos(x)**2 - 1.0*cos(x) + 1) + 0.5/(0.25*cos(x)**2 - 1.0*cos(x) + 1)) expr_simp = simplify(expr) assert expr_simp.equals(expr) def test_sympyissue_12506(): expr = 1.0 * cos(x) + 2.0 * cos(asin(0.5 * sin(x))) expr = expr.diff((x, 2)) expr_simp = expr.simplify() assert expr_simp.equals(expr) def test_sympyissue_13115(): q_1, q_2, q_3 = symbols('q_1:4') Mq = Matrix([[(1.0*cos(q_2) + 0.5*cos(q_2 + q_3))**2*sin(q_1)**2 + (1.0*cos(q_2) + 0.5*cos(q_2 + q_3))**2*cos(q_1)**2 + 0.25*sin(q_1)**2*cos(q_2)**2 + 0.25*cos(q_1)**2*cos(q_2)**2, 0, 0], [0, (-1.0*sin(q_2) - 0.5*sin(q_2 + q_3))**2*sin(q_1)**2 + (-1.0*sin(q_2) - 0.5*sin(q_2 + q_3))**2*cos(q_1)**2 + (-1.0*cos(q_2) - 0.5*cos(q_2 + q_3))**2 + 0.25*sin(q_1)**2*sin(q_2)**2 + 0.25*sin(q_2)**2*cos(q_1)**2 + 0.25*cos(q_2)**2, -0.5*(-1.0*sin(q_2) - 0.5*sin(q_2 + q_3))*sin(q_1)**2*sin(q_2 + q_3) - 0.5*(-1.0*sin(q_2) - 0.5*sin(q_2 + q_3))*sin(q_2 + q_3)*cos(q_1)**2 - 0.5*(-1.0*cos(q_2) - 0.5*cos(q_2 + q_3))*cos(q_2 + q_3)], [0, -0.5*(-1.0*sin(q_2) - 0.5*sin(q_2 + q_3))*sin(q_1)**2*sin(q_2 + q_3) - 0.5*(-1.0*sin(q_2) - 0.5*sin(q_2 + q_3))*sin(q_2 + q_3)*cos(q_1)**2 - 0.5*(-1.0*cos(q_2) - 0.5*cos(q_2 + q_3))*cos(q_2 + q_3), 0.25*sin(q_1)**2*sin(q_2 + q_3)**2 + 0.25*sin(q_2 + q_3)**2*cos(q_1)**2 + 0.25*cos(q_2 + q_3)**2]]) Mqs = simplify(Mq) assert Mqs.subs({q_1: 0, q_2: 0, q_3: 0}) == Matrix([[2.5, 0, 0], [0, 2.5, 0.75], [0, 0.75, 0.25]]) @pytest.mark.xfail def test_simplify_algebraic_numbers(): e = (3 + 4*I)**Rational(3, 2) assert simplify(e) == 2 + 11*I # issue sympy/sympy#4401 @pytest.mark.timeout(20) def test_sympyissue_21641(): assert (simplify(65712362363534280139543*ln(Rational(49, 50)) / 2441406250000000000) == -65712362363534280139543*log(50)/2441406250000000000 + 65712362363534280139543*log(49)/2441406250000000000)
40.365682
117
0.523868
9828404d36d9f36d8a21be2c1f751db6754e8e30
2,065
py
Python
mp_template/app/routes.py
ang-jason/fip_powerx_mini_projects-foxtrot
37e3671969b516369e2d1c7cab5890b75c489f56
[ "MIT" ]
12
2021-09-03T08:00:47.000Z
2021-11-21T03:45:21.000Z
mp_template/app/routes.py
ang-jason/fip_powerx_mini_projects-foxtrot
37e3671969b516369e2d1c7cab5890b75c489f56
[ "MIT" ]
8
2021-06-17T03:16:09.000Z
2021-10-06T03:41:57.000Z
mp_template/app/routes.py
ang-jason/fip_powerx_mini_projects-foxtrot
37e3671969b516369e2d1c7cab5890b75c489f56
[ "MIT" ]
36
2021-07-02T06:06:42.000Z
2022-01-25T08:31:34.000Z
from app import application from flask import render_template, flash, redirect, url_for from app.forms import LoginForm, RegistrationForm from flask_login import current_user, login_user, logout_user, login_required from app.models import User from werkzeug.urls import url_parse from app import db from flask import request from app.serverlibrary import * @application.route('/') @application.route('/index') @login_required def index(): return render_template('index.html', title='Home') # write down your handler for the routes here @application.route('/users') @login_required def users(): users = User.query.all() # mergesort(users, lambda item: item.username) usernames = [u.username for u in users] return render_template('users.html', title='Users', users=usernames) @application.route('/login', methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) return render_template('login.html', title='Sign In', form=form) @application.route('/logout') def logout(): logout_user() return redirect(url_for('index')) @application.route('/register', methods=['GET', 'POST']) def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user.') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
30.820896
77
0.748668
dcb19f470c8c4bcc205f8983e32566d117e52c6e
7,218
py
Python
allennlp/allennlp/training/learning_rate_schedulers/slanted_triangular.py
rahular/joint-coref-srl
cd85fb4e11af1a1ea400ed657d0a4511c1d6c6be
[ "MIT" ]
null
null
null
allennlp/allennlp/training/learning_rate_schedulers/slanted_triangular.py
rahular/joint-coref-srl
cd85fb4e11af1a1ea400ed657d0a4511c1d6c6be
[ "MIT" ]
null
null
null
allennlp/allennlp/training/learning_rate_schedulers/slanted_triangular.py
rahular/joint-coref-srl
cd85fb4e11af1a1ea400ed657d0a4511c1d6c6be
[ "MIT" ]
null
null
null
import logging from typing import List from overrides import overrides import torch from allennlp.training.learning_rate_schedulers.learning_rate_scheduler import ( LearningRateScheduler, ) logger = logging.getLogger(__name__) @LearningRateScheduler.register("slanted_triangular") class SlantedTriangular(LearningRateScheduler): """ Implements the Slanted Triangular Learning Rate schedule with optional gradual unfreezing. The schedule corresponds to first linearly increasing the learning rate and annealing the learning based on a fixed ratio. If we gradually unfreeze, then in the first epoch of training, only the top layer is trained; in the second epoch, the top two layers are trained, etc. During freezing, the learning rate is increased and annealed over one epoch. After freezing finished, the learning rate is increased and annealed over the remaining training iterations. Note that with this schedule, early stopping should typically be avoided. # Parameters num_epochs : `int`, required. The total number of epochs for which the model should be trained. num_steps_per_epoch : `int`, required. The number of steps (updates, batches) per training epoch. cut_frac : `float`, optional (default = 0.1). The fraction of the steps to increase the learning rate. ratio : `float`, optional (default = 32). The ratio of the smallest to the (largest) base learning rate. gradual_unfreezing : `bool`, optional (default = False). Whether gradual unfreezing should be used. discriminative_fine_tuning : `bool`, optional (default = False). Whether discriminative fine-tuning (different learning rates per layer) are used. decay_factor : `float`, optional (default = 0.38). The decay factor by which the learning rate is reduced with discriminative fine-tuning when going a layer deeper. """ def __init__( self, optimizer: torch.optim.Optimizer, num_epochs: int, num_steps_per_epoch: int, cut_frac: float = 0.1, ratio: int = 32, last_epoch: int = -1, gradual_unfreezing: bool = False, discriminative_fine_tuning: bool = False, decay_factor: float = 0.38, ) -> None: self.num_epochs = num_epochs self.num_steps_per_epoch = num_steps_per_epoch self.cut_frac = cut_frac self.ratio = ratio self.gradual_unfreezing = gradual_unfreezing self.freezing_current = self.gradual_unfreezing self.is_first_epoch = True # track the actual number of steps for each epoch self.batch_num_total_epoch_end: List[int] = [] if self.gradual_unfreezing: assert not optimizer.param_groups[-1][ "params" ], "The default group should be empty." if self.gradual_unfreezing or discriminative_fine_tuning: assert len(optimizer.param_groups) > 2, ( "There should be at least 3 param_groups (2 + empty default group)" " for gradual unfreezing / discriminative fine-tuning to make sense." ) super().__init__(optimizer, last_epoch) if discriminative_fine_tuning: # skip the last param_group if it is has no parameters exponent = 0 for i in range(len(self.base_values) - 1, -1, -1): param_group = optimizer.param_groups[i] if param_group["params"]: param_group["lr"] = self.base_values[i] * decay_factor ** exponent self.base_values[i] = param_group["lr"] exponent += 1 # set up for the first batch self.last_batch_num_total = -1 self.step_batch(0) @overrides def step(self, metric: float = None, epoch: int = None) -> None: if len(self.batch_num_total_epoch_end) == 0: self.batch_num_total_epoch_end.append(0) else: self.batch_num_total_epoch_end.append(self.last_batch_num_total) if self.gradual_unfreezing: # the method is called once when initialising before the # first epoch (epoch -1) and then always at the end of each # epoch; so the first time, with epoch id -1, we want to set # up for epoch #1; the second time, with epoch id 0, # we want to set up for epoch #2, etc. if self.is_first_epoch: num_layers_to_unfreeze = 1 self.is_first_epoch = False else: num_layers_to_unfreeze = epoch + 2 if num_layers_to_unfreeze >= len(self.optimizer.param_groups) - 1: logger.info("Gradual unfreezing finished. Training all layers.") self.freezing_current = False else: logger.info( f"Gradual unfreezing. Training only the top {num_layers_to_unfreeze} layers." ) for i, param_group in enumerate(reversed(self.optimizer.param_groups)): for param in param_group["params"]: # i = 0 is the default group; we care about i > 0 param.requires_grad = bool(i <= num_layers_to_unfreeze) def step_batch(self, batch_num_total: int = None): if batch_num_total is None: batch_num_total = self.last_batch_num_total + 1 self.last_batch_num_total = batch_num_total for param_group, learning_rate in zip( self.optimizer.param_groups, self.get_values() ): param_group["lr"] = learning_rate def get_values(self): # get the actual number of batches per epoch seen in training if len(self.batch_num_total_epoch_end) > 1: # have finished an epoch actual_num_steps_per_epoch = int( self.batch_num_total_epoch_end[-1] / (len(self.batch_num_total_epoch_end) - 1) ) else: actual_num_steps_per_epoch = max( self.num_steps_per_epoch, self.last_batch_num_total ) if self.freezing_current: # if we still freeze, we restrict the schedule to the current epoch num_steps = actual_num_steps_per_epoch step = min( self.last_batch_num_total - self.batch_num_total_epoch_end[-1], num_steps, ) else: # otherwise we use the schedule for the rest of training if not self.gradual_unfreezing: frozen_steps = 0 else: num_frozen_epochs = len(self.optimizer.param_groups) - 2 frozen_steps = self.batch_num_total_epoch_end[num_frozen_epochs] num_steps = self.num_epochs * actual_num_steps_per_epoch - frozen_steps step = min(self.last_batch_num_total - frozen_steps, num_steps) cut = int(num_steps * self.cut_frac) prop = step / cut if step < cut else 1 - (step - cut) / (num_steps - cut) return [ lr * (1 + prop * (self.ratio - 1)) / self.ratio for lr in self.base_values ]
43.221557
97
0.631477
2616e1acb4d6c9923e78026ec8d3168d6109b685
2,495
py
Python
ttslab/tokenizers.py
jkleczar/ttslab
33fe0c3f88c1533816b2602b52e4162760d9c5f0
[ "BSD-3-Clause" ]
null
null
null
ttslab/tokenizers.py
jkleczar/ttslab
33fe0c3f88c1533816b2602b52e4162760d9c5f0
[ "BSD-3-Clause" ]
null
null
null
ttslab/tokenizers.py
jkleczar/ttslab
33fe0c3f88c1533816b2602b52e4162760d9c5f0
[ "BSD-3-Clause" ]
1
2019-02-25T10:27:41.000Z
2019-02-25T10:27:41.000Z
# -*- coding: utf-8 -*- """ Contains tokenizer UttProcessor implementations... Think about ways of documenting requirements properly... """ from __future__ import unicode_literals, division, print_function #Py2 __author__ = "Daniel van Niekerk" __email__ = "dvn.demitasse@gmail.com" import re import unicodedata from collections import OrderedDict from uttprocessor import * def anycharsin(s, stemplate): for c in s: if c in stemplate: return True return False class DefaultTokenizer(UttProcessor): """ Perform basic "tokenization" based on "text" contained in Utterance... Utt Requirements: Relations: None Features: text Provides: Relations: Token """ DEFAULT_PUNCTUATION = '"`.,:;!?(){}[]-' def __init__(self, voice, punctuation=None): UttProcessor.__init__(self, voice=voice) if punctuation is not None: self.punctuation = punctuation else: self.punctuation = DefaultTokenizer.DEFAULT_PUNCTUATION self.processes = {"default": OrderedDict([("checkinput", None), ("tokenizer", None)])} def checkinput(self, utt, processname): if not "text" in utt: raise UttProcessorError("Utterance needs to have 'text' feature...") return utt def tokenizer(self, utt, processname): text = utt["text"] rawtokens = text.split() #simply splitting on whitespace... token_rel = utt.new_relation("Token") for rawtoken in rawtokens: #adding only single char to pre- or post-punctuation... if rawtoken[0] in self.punctuation: prepunctuation = rawtoken[0] else: prepunctuation = None if rawtoken[-1] in self.punctuation: postpunctuation = rawtoken[-1] else: postpunctuation = None #strip all punctuation... rawtoken = rawtoken.strip(self.punctuation) #if anything left, add to token_rel: if rawtoken: item = token_rel.append_item() item["name"] = rawtoken if prepunctuation: item["prepunc"] = prepunctuation if postpunctuation: item["postpunc"] = postpunctuation return utt
30.426829
80
0.569138
f9c8157cb6411003eb15133f866d7f7604c1463a
2,118
py
Python
azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/models/workload_protectable_item_resource.py
JonathanGailliez/azure-sdk-for-python
f0f051bfd27f8ea512aea6fc0c3212ee9ee0029b
[ "MIT" ]
1
2021-09-07T18:36:04.000Z
2021-09-07T18:36:04.000Z
azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/models/workload_protectable_item_resource.py
JonathanGailliez/azure-sdk-for-python
f0f051bfd27f8ea512aea6fc0c3212ee9ee0029b
[ "MIT" ]
2
2019-10-02T23:37:38.000Z
2020-10-02T01:17:31.000Z
azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/models/workload_protectable_item_resource.py
JonathanGailliez/azure-sdk-for-python
f0f051bfd27f8ea512aea6fc0c3212ee9ee0029b
[ "MIT" ]
1
2019-06-17T22:18:23.000Z
2019-06-17T22:18:23.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .resource import Resource class WorkloadProtectableItemResource(Resource): """Base class for backup item. Workload-specific backup items are derived from this class. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id represents the complete path to the resource. :vartype id: str :ivar name: Resource name associated with the resource. :vartype name: str :ivar type: Resource type represents the complete path of the form Namespace/ResourceType/ResourceType/... :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param e_tag: Optional ETag. :type e_tag: str :param properties: WorkloadProtectableItemResource properties :type properties: ~azure.mgmt.recoveryservicesbackup.models.WorkloadProtectableItem """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'e_tag': {'key': 'eTag', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'WorkloadProtectableItem'}, } def __init__(self, **kwargs): super(WorkloadProtectableItemResource, self).__init__(**kwargs) self.properties = kwargs.get('properties', None)
35.898305
82
0.603399
55a0e111d5f7e519d1889fe413cb26ead5c334e4
7,559
py
Python
openmdao/utils/array_utils.py
fzahle/OpenMDAO
ce53b0a0862ac1162d5daad7b0ca34ae085ee47c
[ "Apache-2.0" ]
null
null
null
openmdao/utils/array_utils.py
fzahle/OpenMDAO
ce53b0a0862ac1162d5daad7b0ca34ae085ee47c
[ "Apache-2.0" ]
null
null
null
openmdao/utils/array_utils.py
fzahle/OpenMDAO
ce53b0a0862ac1162d5daad7b0ca34ae085ee47c
[ "Apache-2.0" ]
null
null
null
""" Utils for dealing with arrays. """ from __future__ import print_function, division import sys import six from six.moves import range import numpy as np def evenly_distrib_idxs(num_divisions, arr_size): """ Return evenly distributed entries for the given array size. Given a number of divisions and the size of an array, chop the array up into pieces according to number of divisions, keeping the distribution of entries as even as possible. Parameters ---------- num_divisions : int Number of parts to divide the array into. arr_size : int Number of entries in the array. Returns ------- tuple a tuple of (sizes, offsets), where sizes and offsets contain values for all divisions. """ base = arr_size // num_divisions leftover = arr_size % num_divisions sizes = np.full(num_divisions, base, dtype=int) # evenly distribute the remainder across size-leftover procs, # instead of giving the whole remainder to one proc sizes[:leftover] += 1 offsets = np.zeros(num_divisions, dtype=int) offsets[1:] = np.cumsum(sizes)[:-1] return sizes, offsets def take_nth(rank, size, seq): """ Iterate returning every nth value. Return an iterator over the sequence that returns every nth element of seq based on the given rank within a group of the given size. For example, if size = 2, a rank of 0 returns even indexed elements and a rank of 1 returns odd indexed elements. Parameters ---------- rank : int MPI rank of this process. size : int Size of the array we're taking nth entries from. seq : iter Iterator containing the values being returned. """ assert(rank < size) it = iter(seq) while True: for proc in range(size): if rank == proc: try: yield six.next(it) except StopIteration: return else: try: six.next(it) except StopIteration: return def convert_neg(arr, dim): """ Convert any negative indices into their positive equivalent. Parameters ---------- arr : ndarray Array having negative indices converted. dim : int Dimension of the array. Returns ------- ndarray The converted array. """ arr[arr < 0] += dim return arr def array_viz(arr, prob=None, of=None, wrt=None, stream=sys.stdout): """ Display the structure of a boolean array in a compact form. If prob, of, and wrt are supplied, print the name of the response alongside each row and print the names of the design vars, aligned with each column, at the bottom. Parameters ---------- arr : ndarray Array being visualized. prob : Problem or None Problem object. of : list of str or None Names of response variables used in derivative calculation. wrt : list of str or None Names of design variables used in derivative calculation. stream : file-like Stream where output will be written. """ if len(arr.shape) != 2: raise RuntimeError("array_viz only works for 2d arrays.") if prob is not None: if of is None: of = prob.driver._get_ordered_nl_responses() if wrt is None: wrt = list(prob.driver._designvars) if prob is None or of is None or wrt is None: for r in range(arr.shape[0]): for c in range(arr.shape[1]): if arr[r, c]: stream.write('x') else: stream.write('.') stream.write(' %d\n' % r) else: row = 0 for res in of: for r in range(row, row + prob.driver._responses[res]['size']): col = 0 for dv in wrt: for c in range(col, col + prob.driver._designvars[dv]['size']): if arr[r, c]: stream.write('x') else: stream.write('.') col = c + 1 stream.write(' %d %s\n' % (r, res)) row = r + 1 start = 0 for name in wrt: tab = ' ' * start stream.write('%s|%s\n' % (tab, name)) start += prob.driver._designvars[name]['size'] def array_connection_compatible(shape1, shape2): """ Return True if the two arrays shapes are compatible. Array shapes are compatible if the underlying data has the same size and is stored in the same contiguous order for the two shapes. Parameters ---------- shape1 : tuple of int Shape of the first array. shape2 : tuple of int Shape of the second array. Returns ------- bool True if the two shapes are compatible for connection, else False. """ ashape1 = np.asarray(shape1, dtype=int) ashape2 = np.asarray(shape2, dtype=int) size1 = np.prod(ashape1) size2 = np.prod(ashape2) # Shapes are not connection-compatible if size is different if size1 != size2: return False nz1 = np.where(ashape1 > 1)[0] nz2 = np.where(ashape2 > 1)[0] if len(nz1) > 0: fundamental_shape1 = ashape1[np.min(nz1): np.max(nz1) + 1] else: fundamental_shape1 = np.ones((1,)) if len(nz2) > 0: fundamental_shape2 = ashape2[np.min(nz2): np.max(nz2) + 1] else: fundamental_shape2 = np.ones((1,)) return np.all(fundamental_shape1 == fundamental_shape2) def tile_sparse_jac(data, rows, cols, nrow, ncol, num_nodes): """ Assemble a sprase csr jacobian for a vectorized component. Parameters ---------- data : ndarray Array of values rows : index array Array of row indices. cols : index array Array of column indices. nrow : int Number of rows in sub jacobian. ncol : int Number of columns in sub jacobian. num_nodes : int Number of vectorized copies to tile. Returns ------- ndarray, ndarray, ndarray CSR Sparse jacobian of size num_nodes*nrow by num_nodes*ncol """ nnz = len(rows) if np.isscalar(data): data = data * np.ones(nnz) if not np.isscalar(nrow): nrow = np.prod(nrow) if not np.isscalar(ncol): ncol = np.prod(ncol) data = np.tile(data, num_nodes) rows = np.tile(rows, num_nodes) + np.repeat(np.arange(num_nodes), nnz) * nrow cols = np.tile(cols, num_nodes) + np.repeat(np.arange(num_nodes), nnz) * ncol return data, rows, cols def _global2local_offsets(global_offsets): """ Given existing global offsets, return a copy with offsets localized to each process. Parameters ---------- global_offsets : dict Arrays of global offsets keyed by vec_name and deriv direction. Returns ------- dict Arrays of local offsets keyed by vec_name and deriv direction. """ offsets = {} for vec_name in global_offsets: offsets[vec_name] = off_vn = {} for type_ in global_offsets[vec_name]: goff = global_offsets[vec_name][type_] off_vn[type_] = goff.copy() if goff[0].size > 0: # adjust offsets to be local in each process off_vn[type_] -= goff[:, 0].reshape((goff.shape[0], 1)) return offsets
27.487273
88
0.584998
a106957cabf3a33dfbcd0e0bbd60b2409c02be2c
2,644
py
Python
imdb_sentiment/vocab.py
shazi4399/machine-learning-example
0e332bc53ff85a11887012f7d5b09be9597bb4ef
[ "Apache-2.0" ]
16
2021-07-09T08:40:50.000Z
2022-03-29T03:21:18.000Z
imdb_sentiment/vocab.py
shazi4399/machine-learning-example
0e332bc53ff85a11887012f7d5b09be9597bb4ef
[ "Apache-2.0" ]
null
null
null
imdb_sentiment/vocab.py
shazi4399/machine-learning-example
0e332bc53ff85a11887012f7d5b09be9597bb4ef
[ "Apache-2.0" ]
15
2021-06-07T11:20:38.000Z
2022-03-08T15:48:50.000Z
""" 文本序列化 """ class Vocab: UNK_TAG = "<UNK>" # 表示未知字符 PAD_TAG = "<PAD>" # 填充符 PAD = 0 UNK = 1 def __init__(self): self.dict = { # 保存词语和对应的数字 self.UNK_TAG: self.UNK, self.PAD_TAG: self.PAD } self.count = {} # 统计词频的 def fit(self, sentence): """ 接受句子,统计词频 :param sentence:[str,str,str] :return:None """ for word in sentence: self.count[word] = self.count.get(word, 0) + 1 # 所有的句子fit之后,self.count就有了所有词语的词频 def build_vocab(self, min_count=1, max_count=None, max_features=None): """ 根据条件构造 词典 :param min_count:最小词频 :param max_count: 最大词频 :param max_features: 最大词语数 :return: """ if min_count is not None: self.count = {word: count for word, count in self.count.items() if count >= min_count} if max_count is not None: self.count = {word: count for word, count in self.count.items() if count <= max_count} if max_features is not None: # [(k,v),(k,v)....] --->{k:v,k:v} self.count = dict(sorted(self.count.items(), lambda x: x[-1], reverse=True)[:max_features]) for word in self.count: self.dict[word] = len(self.dict) # 每次word对应一个数字 # 把dict进行翻转 self.inverse_dict = dict(zip(self.dict.values(), self.dict.keys())) def transform(self, sentence, max_len=None): """ 把句子转化为数字序列 :param sentence:[str,str,str] :return: [int,int,int] """ if len(sentence) > max_len: sentence = sentence[:max_len] else: sentence = sentence + [self.PAD_TAG] * (max_len - len(sentence)) # 填充PAD return [self.dict.get(i, 1) for i in sentence] def inverse_transform(self, incides): """ 把数字序列转化为字符 :param incides: [int,int,int] :return: [str,str,str] """ return [self.inverse_dict.get(i, "<UNK>") for i in incides] def __len__(self): return len(self.dict) # 以下是调试代码 if __name__ == '__main__': sentences = [["今天", "天气", "很", "好"], ["今天", "去", "吃", "什么"]] ws = Vocab() for sentence in sentences: # 统计词频 ws.fit(sentence) # 构造词典 ws.build_vocab(min_count=1) print(ws.dict) # 把句子转换成数字序列 ret = ws.transform(["好", "好", "好", "好", "好", "好", "好", "热", "呀"], max_len=13) print(ret) # 把数字序列转换成句子 ret = ws.inverse_transform(ret) print(ret) pass
28.73913
104
0.513994
8ee7edb84411d1ee38eeea117c0f0529592c0840
3,677
py
Python
source/svm_vowelsound_classification.py
Hanumanth004/classification_using_svm
be244e82c2d34063f9ef3bdcdc0dd162ab6ce6ca
[ "MIT" ]
null
null
null
source/svm_vowelsound_classification.py
Hanumanth004/classification_using_svm
be244e82c2d34063f9ef3bdcdc0dd162ab6ce6ca
[ "MIT" ]
null
null
null
source/svm_vowelsound_classification.py
Hanumanth004/classification_using_svm
be244e82c2d34063f9ef3bdcdc0dd162ab6ce6ca
[ "MIT" ]
null
null
null
import numpy as np from random import randint import sys import csv from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report from sklearn import preprocessing def str_column_to_float(X_data, column): for row in X_data: row[column]=float(row[column].strip()) sample=[] with open(sys.argv[1], 'rb') as f: reader=csv.reader(f.read().splitlines()) for row in reader: sample.append(row) for i in range(len(sample[0])): str_column_to_float(sample, i) X_data=sample X_tr=[] label=[] for i in X_data: X_tr.append(i[:-1]) label.append(i[-1]) scaler = preprocessing.StandardScaler() X_tr = scaler.fit_transform(X_tr) #min_max_scaler = preprocessing.MinMaxScaler() #X_tr= min_max_scaler.fit_transform(X_tr) #max_abs_scaler = preprocessing.MaxAbsScaler() #X_tr = max_abs_scaler.fit_transform(X_tr) #X_tr=X_tr[0:300] #label=label[0:300] """ param_grid = [ {'estimator__C': [1, 10, 100, 1000, 10000], 'estimator__kernel': ['linear']}, {'estimator__C': [1, 10, 100, 1000, 10000], 'estimator__gamma': [1e-2, 1e-3, 1e-4], 'estimator__kernel': ['rbf', 'poly']}, ] """ """ param_grid = [ {'estimator__C': [1, 10, 100, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000], 'estimator__gamma': [1e-2, 1e-3, 1e-4], 'estimator__kernel': ['rbf', 'poly', 'sigmoid', 'linear']}, ] """ """ param_grid = [ {'estimator__C': [0.001, 0.01, 0.1, 1, 10, 100, 1000], 'estimator__gamma': [1e-3, 1e-2, 1e-1, 1], 'estimator__kernel': ['rbf', 'poly', 'sigmoid', 'linear']}, ] """ param_grid = [ {'C': [1, 10, 80, 90, 100, 110, 120, 130, 1000, 10000], 'kernel': ['linear']}, {'C': [1, 10, 100, 1000, 10000], 'gamma': [1e-3, 1e-4], 'kernel': ['rbf', 'poly']}, ] sample=[] with open(sys.argv[2], 'rb') as f: reader=csv.reader(f.read().splitlines()) for row in reader: sample.append(row) for i in range(len(sample[0])): str_column_to_float(sample, i) X_data=sample X_val=[] label1=[] for i in X_data: X_val.append(i[:-1]) label1.append(i[-1]) #X_val=min_max_scaler.transform(X_val) X_val=scaler.transform(X_val) #X_val=max_abs_scaler.transform(X_val) model_to_set=[SVC(decision_function_shape='ovo', kernel='rbf'), SVC(decision_function_shape='ovr', kernel='rbf')] scores = ['precision', 'recall'] print("Tuning hyper-parameters") for model in model_to_set: for score in scores: clf = GridSearchCV(model, param_grid, cv=3, n_jobs=6) clf.fit(X_tr, label) print("Best parameters set found on development set:") print() print(clf.best_params_) print() means = clf.cv_results_['mean_test_score'] stds = clf.cv_results_['std_test_score'] for mean, std, params in zip(means, stds, clf.cv_results_['params']): print("%0.3f (+/-%0.03f) for %r" % (mean, std * 2, params)) print() print("Detailed classification report:") print() print("The model is trained on the full development set.") print("The scores are computed on the full evaluation set.") print() y_true, y_pred = label1, clf.predict(X_val) print(classification_report(y_true, y_pred)) print() predict=clf.predict(X_tr) count=0 for i in xrange(len(label)): if label[i]==predict[i]: count+=1 print " training accuracy:%f" % (float(count)/len(label)) predict=clf.predict(X_val) count=0 for i in xrange(len(label1)): if label1[i]==predict[i]: count+=1 print " validation accuracy:%f" % (float(count)/len(label1))
26.453237
188
0.645907
cea2bc44a132dfd9908c7addc147c0ea82a82f71
6,768
py
Python
pysilico_server/camera_controller/camera_controller.py
ArcetriAdaptiveOptics/pysilico_server
ebdfa06dbfa889e5f2dde21e44859c8a2868e11a
[ "MIT" ]
null
null
null
pysilico_server/camera_controller/camera_controller.py
ArcetriAdaptiveOptics/pysilico_server
ebdfa06dbfa889e5f2dde21e44859c8a2868e11a
[ "MIT" ]
1
2022-01-25T14:40:46.000Z
2022-01-25T14:40:46.000Z
pysilico_server/camera_controller/camera_controller.py
ArcetriAdaptiveOptics/pysilico_server
ebdfa06dbfa889e5f2dde21e44859c8a2868e11a
[ "MIT" ]
null
null
null
import threading import time import numpy as np from plico.utils.hackerable import Hackerable from plico.utils.snapshotable import Snapshotable from plico.utils.stepable import Stepable from plico.utils.serverinfoable import ServerInfoable from plico.utils.logger import Logger from plico.utils.decorator import override, logEnterAndExit, synchronized from plico.utils.timekeeper import TimeKeeper from pysilico.types.camera_frame import CameraFrame from pysilico.types.camera_status import CameraStatus from rebin import rebin class CameraController(Stepable, Snapshotable, Hackerable, ServerInfoable): def __init__(self, servername, ports, camera, replySocket, publisherSocket, statusSocket, displaySocket, rpcHandler, timeMod=time): self._camera = camera self._replySocket = replySocket self._publisherSocket = publisherSocket self._statusSocket = statusSocket self._displaySocket = displaySocket self._rpcHandler = rpcHandler self._timeMod = timeMod self._logger = Logger.of('CameraController') Hackerable.__init__(self, self._logger) ServerInfoable.__init__(self, servername, ports, self._logger) self._isTerminated = False self._stepCounter = 0 self._frameCounter = 0 self._lastDisplayTimestamp = 0 self._displayIntervalInSec = 0.05 self._timekeep = TimeKeeper() self._cameraStatus = None self._mutexStatus = threading.RLock() self._camera.registerCallback(self._publishFrame) self._darkFrame = None self._mutexDarkFrame = threading.RLock() @override def step(self): self._rpcHandler.handleRequest(self, self._replySocket, multi=True) self._publishStatus() if self._timekeep.inc(): self._logger.notice( 'Stepping at %5.2f Hz. FrameCounter %d' % ( self._timekeep.rate, self._camera.getFrameCounter())) self._stepCounter += 1 def getStepCounter(self): return self._stepCounter def terminate(self): self._logger.notice("Got request to terminate") try: self._camera.stopAcquisition() self._camera.deinitialize() except Exception as e: self._logger.warn("Could not stop camera acquisition: %s" % str(e)) self._isTerminated = True @override def isTerminated(self): return self._isTerminated def getShape(self): assert False, 'Should not be used, client uses getStatus instead' def getDtype(self): assert False, 'Should not be used, client uses getStatus instead' @logEnterAndExit('Entering setExposureTime', 'Executed setExposureTime') def setExposureTime(self, exposureTimeInMilliSeconds): self._camera.setExposureTime(exposureTimeInMilliSeconds) with self._mutexStatus: self._cameraStatus = None def _getExposureTime(self): return self._getCameraStatus().exposureTimeInMilliSec @logEnterAndExit('Entering setBinning', 'Executed setBinning') def setBinning(self, binning): self._camera.setBinning(binning) with self._mutexStatus: self._cameraStatus = None def getBinning(self): assert False, 'Should not be used, client uses getStatus instead' def getDarkFrame(self): with self._mutexDarkFrame: return self._darkFrame @logEnterAndExit('Entering setDarkFrame', 'Executed setDarkFrame') def setDarkFrame(self, darkFrame): with self._mutexDarkFrame: self._darkFrame = darkFrame def _getCorrectedFrame(self, frame): if self._darkFrame is not None: with self._mutexDarkFrame: return CameraFrame.fromNumpyArray( frame.toNumpyArray() - self._darkFrame.toNumpyArray(), frame.counter()) else: return frame def getSnapshot(self, prefix): assert False, 'Should not be used, client uses getStatus instead' def _publishFrame(self, frame): correctedFrame = self._getCorrectedFrame(frame) self._rpcHandler.sendCameraFrame(self._publisherSocket, correctedFrame) self._logger.debug('frame %d published' % correctedFrame.counter()) self._publishForDisplay(correctedFrame) def _downsizeForDisplay(self, frame): DISPLAY_FRAME_SIZE = 256. minSize = np.min(frame.toNumpyArray().shape) downsizeBy = np.int(np.ceil( minSize / DISPLAY_FRAME_SIZE)) if downsizeBy > 1: array = self._downsizeBySampling(frame.toNumpyArray(), downsizeBy) else: array = frame.toNumpyArray() return CameraFrame.fromNumpyArray(np.float32(array), frame.counter()) def _downsizeByRebin(self, frame, factor): return rebin(frame, factor) * factor**2 def _downsizeBySampling(self, frame, factor): return frame[::factor, ::factor] def _publishForDisplay(self, frame): now = self._timeMod.time() if now - self._lastDisplayTimestamp < self._displayIntervalInSec: return downsizedFrame = self._downsizeForDisplay(frame) self._rpcHandler.sendCameraFrame(self._displaySocket, downsizedFrame) self._lastDisplayTimestamp = now @synchronized("_mutexStatus") def _getCameraStatus(self): if self._cameraStatus is None: self._logger.debug('get CameraStatus') self._cameraStatus = CameraStatus( self._camera.name(), self._camera.cols(), self._camera.rows(), self._camera.dtype(), self._camera.getBinning(), self._camera.exposureTime(), self._camera.getFrameRate()) return self._cameraStatus def _publishStatus(self): self._rpcHandler.publishPickable(self._statusSocket, self._getCameraStatus()) @logEnterAndExit('Entering setFrameRate', 'Executed setFrameRate') def setFrameRate(self, frameRate): self._camera.setFrameRate(frameRate) with self._mutexStatus: self._cameraStatus = None
36
79
0.617169
eac60f6fda9b54023cf006b5935312f0b584cfc9
4,109
py
Python
packages/watchmen-model/src/watchmen_model/indicator/navigation.py
Indexical-Metrics-Measure-Advisory/watchmen
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
[ "MIT" ]
null
null
null
packages/watchmen-model/src/watchmen_model/indicator/navigation.py
Indexical-Metrics-Measure-Advisory/watchmen
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
[ "MIT" ]
null
null
null
packages/watchmen-model/src/watchmen_model/indicator/navigation.py
Indexical-Metrics-Measure-Advisory/watchmen
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
[ "MIT" ]
null
null
null
from enum import Enum from typing import List, Optional, Union from pydantic import BaseModel from watchmen_model.common import Auditable, BucketId, DataModel, FactorId, IndicatorId, NavigationId, UserBasedTuple from watchmen_utilities import ArrayHelper, is_not_blank from .indicator import IndicatorAggregateArithmetic class NavigationIndicatorCriteria(DataModel, BaseModel): factorId: FactorId = None class NavigationIndicatorCriteriaOnBucket(NavigationIndicatorCriteria): """ fill when use predefined bucket """ bucketId: BucketId = None bucketSegmentName: str = None class NavigationIndicatorCriteriaOperator(str, Enum): EQUALS = 'equals', NOT_EQUALS = 'not-equals', LESS = 'less', LESS_EQUALS = 'less-equals', MORE = 'more', MORE_EQUALS = 'more-equals', class NavigationIndicatorCriteriaOnExpression(NavigationIndicatorCriteria): operator: NavigationIndicatorCriteriaOperator = NavigationIndicatorCriteriaOperator.EQUALS value: str = None def construct_indicator_criteria( criteria: Optional[Union[dict, NavigationIndicatorCriteria]]) -> Optional[NavigationIndicatorCriteria]: if criteria is None: return None elif isinstance(criteria, NavigationIndicatorCriteria): return criteria else: bucket_id = criteria.get('bucketId') if is_not_blank(bucket_id): return NavigationIndicatorCriteriaOnBucket(**criteria) operator = criteria.get('operator') if is_not_blank(operator): return NavigationIndicatorCriteriaOnExpression(**criteria) else: return NavigationIndicatorCriteria(**criteria) def construct_indicator_criteria_list( criteria_list: Optional[list] = None) -> Optional[List[NavigationIndicatorCriteria]]: if criteria_list is None: return None else: return ArrayHelper(criteria_list).map(lambda x: construct_indicator_criteria(x)).to_list() class NavigationIndicator(DataModel, BaseModel): indicatorId: IndicatorId = None name: str = None aggregateArithmetic: IndicatorAggregateArithmetic = None formula: str = None includeInFinalScore: bool = True criteria: List[NavigationIndicatorCriteria] = [] variableName: str = None def __setattr__(self, name, value): if name == 'criteria': super().__setattr__(name, construct_indicator_criteria_list(value)) else: super().__setattr__(name, value) MANUAL_COMPUTE_NAVIGATION_INDICATOR_ID = '-1' class ManualComputeNavigationIndicator(NavigationIndicator): """ for manual compute indicator, 1. indicatorId fixed as {@link MANUAL_COMPUTE_NAVIGATION_INDICATOR_ID}, 2. aggregateArithmetics fixed as {@link IndicatorAggregateArithmetic#MAX}, will be ignored anyway in runtime 3. criteria fixed as zero length array, will be ignored anyway in runtime """ indicatorId: IndicatorId = MANUAL_COMPUTE_NAVIGATION_INDICATOR_ID aggregateArithmetic: IndicatorAggregateArithmetic = IndicatorAggregateArithmetic.MAX class NavigationTimeRangeType(str, Enum): YEAR = 'year', MONTH = 'month' def construct_indicator(indicator: Optional[Union[dict, NavigationIndicator]]) -> Optional[NavigationIndicator]: if indicator is None: return None elif isinstance(indicator, NavigationIndicator): return indicator else: indicator_id = indicator.get('indicatorId') if indicator_id == MANUAL_COMPUTE_NAVIGATION_INDICATOR_ID: return ManualComputeNavigationIndicator(**indicator) else: return NavigationIndicator(**indicator) def construct_indicators(indicators: Optional[list] = None) -> Optional[List[NavigationIndicator]]: if indicators is None: return None else: return ArrayHelper(indicators).map(lambda x: construct_indicator(x)).to_list() class Navigation(UserBasedTuple, Auditable, BaseModel): navigationId: NavigationId = None name: str = None description: str = None timeRangeType: NavigationTimeRangeType = NavigationTimeRangeType.YEAR timeRangeYear: str = None timeRangeMonth: str = None compareWithPreviousTimeRange: bool = False indicators: List[NavigationIndicator] = [] def __setattr__(self, name, value): if name == 'indicators': super().__setattr__(name, construct_indicators(value)) else: super().__setattr__(name, value)
31.128788
117
0.794597
ca9c86b2029cfe365f3b64bc16bf7b5ae7e51745
85,186
py
Python
cripts/core/cripts_mongoengine.py
lakiw/cripts
43f62891a3724e1ec60629887d97c421fb302163
[ "MIT" ]
2
2017-04-06T12:26:11.000Z
2018-11-05T19:17:15.000Z
cripts/core/cripts_mongoengine.py
lakiw/cripts
43f62891a3724e1ec60629887d97c421fb302163
[ "MIT" ]
9
2016-09-28T10:19:10.000Z
2017-02-24T17:58:43.000Z
cripts/core/cripts_mongoengine.py
lakiw/cripts
43f62891a3724e1ec60629887d97c421fb302163
[ "MIT" ]
null
null
null
import datetime import json, yaml import io import csv from bson import json_util, ObjectId from dateutil.parser import parse from django.conf import settings from django.core.urlresolvers import reverse from django.template.loader import render_to_string from mongoengine import Document, EmbeddedDocument, DynamicEmbeddedDocument from mongoengine import StringField, ListField, EmbeddedDocumentField from mongoengine import IntField, DateTimeField, ObjectIdField from mongoengine.base import BaseDocument, ValidationError # Determine if we should be caching queries or not. from mongoengine import QuerySet as QS from pprint import pformat from cripts.core.user_tools import user_sources, is_admin from cripts.core.fields import CriptsDateTimeField from cripts.core.class_mapper import class_from_id, class_from_type from cripts.vocabulary.relationships import RelationshipTypes from cripts.vocabulary.objects import ObjectTypes # Hack to fix an issue with non-cached querysets and django-tastypie-mongoengine # The issue is in django-tastypie-mongoengine in resources.py from what I can # tell. try: from mongoengine.queryset import tranform as mongoengine_tranform except ImportError: mongoengine_tranform = None QUERY_TERMS_ALL = getattr(mongoengine_tranform, 'MATCH_OPERATORS', ( 'ne', 'gt', 'gte', 'lt', 'lte', 'in', 'nin', 'mod', 'all', 'size', 'exists', 'not', 'within_distance', 'within_spherical_distance', 'within_box', 'within_polygon', 'near', 'near_sphere', 'contains', 'icontains', 'startswith', 'istartswith', 'endswith', 'iendswith', 'exact', 'iexact', 'match' )) class Query(object): """ Query class to hold available query terms. """ query_terms = dict([(query_term, None) for query_term in QUERY_TERMS_ALL]) class CriptsQuerySet(QS): """ CRIPTs default QuerySet. Used to override methods like .only() and to extend it with other methods we want to perform on a QuerySet object. """ _len = None query = Query() def __len__(self): """ Modified version of the default __len__() which allows us to get the length with or without caching enabled. """ if self._len is not None: return self._len if self._has_more: # populate the cache list(self._iter_results()) self._len = len(self._result_cache) else: self._len = self.count() return self._len def only(self, *fields): """ Modified version of the default only() which allows us to add default fields we always want to include. """ #Always include schema_version so we can migrate if needed. if 'schema_version' not in fields: fields = fields + ('schema_version',) return super(CriptsQuerySet, self).only(*fields) def from_json(self, json_data): """ Converts JSON data to unsaved objects. Takes either a Python list of individual JSON objects or the result of calling json.dumps on a Python list of Python dictionaries. :param json_data: List or result of json.dumps. :type json_data: list or str :returns: :class:`cripts.core.cripts_mongoengine.CriptsQuerySet` """ print("running_from_json") if not isinstance(json_data, list): son_data = json_util.loads(json_data) return [self._document._from_son(data) for data in son_data] else: #Python list of JSON objects return [self._document.from_json(data) for data in json_data] def to_dict(self, excludes=[], projection=[]): """ Converts CriptsQuerySet to a list of dictionaries. :param excludes: List fields to exclude in each document. :type excludes: list :param projection: List fields to limit results on. :type projectsion: list :returns: list of dictionaries """ return [obj.to_dict(excludes,projection) for obj in self] def to_csv(self, fields): """ Converts CriptsQuerySet to CSV formatted string. :param fields: List fields to return for each document. :type fields: list :returns: str """ filter_keys = [ 'id', 'password', 'password_reset', 'schema_version', ] if not fields: fields = self[0]._data.keys() # Create a local copy fields = fields[:] for key in filter_keys: if key in fields: fields.remove(key) csvout = ",".join(fields) + "\n" csvout += "".join(obj.to_csv(fields) for obj in self) return csvout def to_json(self, exclude=[]): """ Converts a CriptsQuerySet to JSON. :param exclude: Fields to exclude from each document. :type exclude: list :returns: json """ print("running_to_json") return json.dumps([obj.to_dict(exclude) for obj in self], default=json_handler) def from_yaml(self, yaml_data): """ Converts YAML data to a list of unsaved objects. :param yaml_data: The YAML to convert. :type yaml_data: list :returns: list """ return [self._document.from_yaml(doc) for doc in yaml_data] def to_yaml(self, exclude=[]): """ Converts a CriptsQuerySet to a list of YAML docs. :param exclude: Fields to exclude from each document. :type exclude: list :returns: list """ return [doc.to_yaml(exclude) for doc in self] def sanitize_sources(self, username=None): """ Sanitize each document in a CriptsQuerySet for source information and return the results as a list. :param username: The user which requested the data. :type username: str :returns: list """ if not username: return self sources = user_sources(username) final_list = [] for doc in self: doc.sanitize_sources(username, sources) final_list.append(doc) return final_list class CriptsDocumentFormatter(object): """ Class to inherit from to gain the ability to convert a top-level object class to another format. """ def to_json(self): """ Return the object in JSON format. """ print("running to_json in document formatter") return self.to_mongo() def to_dict(self): """ Return the object as a dict. """ return self.to_mongo().to_dict() def __str__(self): """ Allow us to use `print`. """ return self.to_json() def merge(self, arg_dict=None, overwrite=False, **kwargs): """ Merge a dictionary into a top-level object class. :param arg_dict: The dictionary to get data from. :type arg_dict: dict :param overwrite: Whether or not to overwrite data in the object. :type overwrite: boolean """ merge(self, arg_dict=arg_dict, overwrite=overwrite) class CriptsStatusDocument(BaseDocument): """ Inherit to add status to a top-level object. """ status = StringField(default="New") def set_status(self, status): """ Set the status of a top-level object. :param status: The status to set: ('New', 'In Progress', 'Analyzed', Deprecated') """ if status in ('New', 'In Progress', 'Analyzed', 'Deprecated'): self.status = status if status == 'Deprecated' and 'actions' in self: for action in self.actions: action.active = "off" class CriptsBaseDocument(BaseDocument): """ Inherit to add a created and modified date to a top-level object. """ created = CriptsDateTimeField(default=datetime.datetime.now) # modified will be overwritten on save modified = CriptsDateTimeField() class CriptsSchemaDocument(BaseDocument): """ Inherit to add a schema_version to a top-level object. Default schema_version is 0 so that later, on .save(), we can tell if a document coming from the DB never had a schema_version assigned and raise an error. """ schema_version = IntField(default=0) class UnsupportedAttrs(DynamicEmbeddedDocument, CriptsDocumentFormatter): """ Inherit to allow a top-level object to store unsupported attributes. """ meta = {} class CriptsDocument(BaseDocument): """ Mixin for adding CRIPTs specific functionality to the MongoEngine module. All CRIPTs MongoEngine-based classes should inherit from this class in addition to MongoEngine's Document. NOTE: this class uses some undocumented methods and attributes from MongoEngine's BaseDocument and may need to be revisited if/when the code is updated. """ meta = { 'duplicate_attrs':[], 'migrated': False, 'migrating': False, 'needs_migration': False, 'queryset_class': CriptsQuerySet } unsupported_attrs = EmbeddedDocumentField(UnsupportedAttrs) def __init__(self, **values): """ Override .save() and .delete() with our own custom versions. """ if hasattr(self, 'save'): #.save() is normally defined on a Document, not BaseDocument, so # we'll have to monkey patch to call our save. self.save = self._custom_save if hasattr(self, 'delete'): #.delete() is normally defined on a Document, not BaseDocument, so # we'll have to monkey patch to call our delete. self.delete = self._custom_delete self._meta['strict'] = False super(CriptsDocument, self).__init__(**values) def _custom_save(self, force_insert=False, validate=True, clean=False, write_concern=None, cascade=None, cascade_kwargs=None, _refs=None, username=None, **kwargs): """ Custom save function. Extended to check for valid schema versions, automatically update modified times, and audit the changes made. """ from cripts.core.handlers import audit_entry if hasattr(self, 'schema_version') and not self.schema_version: #Check that documents retrieved from the DB have a recognized # schema_version if not self._created: raise UnrecognizedSchemaError(self) #If it's a new document, set the appropriate schema version elif hasattr(self, '_meta') and 'latest_schema_version' in self._meta: self.schema_version = self._meta['latest_schema_version'] #TODO: convert this to using UTC if hasattr(self, 'modified'): self.modified = datetime.datetime.now() do_audit = False if self.id: audit_entry(self, username, "save") else: do_audit = True super(self.__class__, self).save(force_insert=force_insert, validate=validate, clean=clean, write_concern=write_concern, cascade=cascade, cascade_kwargs=cascade_kwargs, _refs=_refs) if do_audit: audit_entry(self, username, "save", new_doc=True) return def _custom_delete(self, username=None, **write_concern): """ Custom delete function. Overridden to allow us to extend to other parts of CRIPTs and clean up dangling relationships, comments, objects, GridFS files, bucket_list counts, and favorites. """ from cripts.core.handlers import audit_entry, alter_bucket_list audit_entry(self, username, "delete") if self._has_method("delete_all_relationships"): self.delete_all_relationships(username=username) if self._has_method("delete_all_comments"): self.delete_all_comments() if self._has_method("delete_all_analysis_results"): self.delete_all_analysis_results() if self._has_method("delete_all_objects"): self.delete_all_objects() if self._has_method("delete_all_favorites"): self.delete_all_favorites() if hasattr(self, 'filedata'): self.filedata.delete() if hasattr(self, 'bucket_list'): alter_bucket_list(self, self.bucket_list, -1) super(self.__class__, self).delete() return def __setattr__(self, name, value): """ Overriden to handle unsupported attributes. """ #Make sure name is a valid field for MongoDB. Also, name cannot begin with # underscore because that indicates a private MongoEngine attribute. if (not self._dynamic and hasattr(self, 'unsupported_attrs') and not name in self._fields and not name.startswith('_') and not name.startswith('$') and not '.' in name and name not in ('save', 'delete')): if not self.unsupported_attrs: self.unsupported_attrs = UnsupportedAttrs() self.unsupported_attrs.__setattr__(name, value) else: super(CriptsDocument, self).__setattr__(name, value) def _has_method(self, method): """ Convenience method for determining if a method exists for this class. :param method: The method to check for. :type method: str :returns: True, False """ if hasattr(self, method) and callable(getattr(self, method)): return True else: return False @classmethod def _from_son(cls, son, _auto_dereference=True, only_fields=None, created=False): """ Override the default _from_son(). Allows us to move attributes in the database to unsupported_attrs if needed, validate the schema_version, and automatically migrate to newer schema versions. """ doc = super(CriptsDocument, cls)._from_son(son, _auto_dereference) #Make sure any fields that are unsupported but exist in the database # get added to the document's unsupported_attributes field. #Get database names for all fields that *should* exist on the object. db_fields = [val.db_field for key,val in cls._fields.iteritems()] #custom __setattr__ does logic of moving fields to unsupported_fields [doc.__setattr__("%s"%key, val) for key,val in son.iteritems() if key not in db_fields] #After a document is retrieved from the database, and any unsupported # fields have been moved to unsupported_attrs, make sure the original # fields will get removed from the document when it's saved. if hasattr(doc, 'unsupported_attrs'): if doc.unsupported_attrs is not None: for attr in doc.unsupported_attrs: #mark for deletion if not hasattr(doc, '_changed_fields'): doc._changed_fields = [] doc._changed_fields.append(attr) # Check for a schema_version. Raise exception so we don't # infinitely loop through attempting to migrate. if hasattr(doc, 'schema_version'): if doc.schema_version == 0: raise UnrecognizedSchemaError(doc) # perform migration, if needed if hasattr(doc, '_meta'): if ('schema_version' in doc and 'latest_schema_version' in doc._meta and doc.schema_version < doc._meta['latest_schema_version']): # mark for migration doc._meta['needs_migration'] = True # reload doc to get full document from database if (doc._meta.get('needs_migration', False) and not doc._meta.get('migrating', False)): doc._meta['migrating'] = True doc.reload() try: doc.migrate() doc._meta['migrated'] = True doc._meta['needs_migration'] = False doc._meta['migrating'] = False except Exception as e: e.tlo = doc.id raise e return doc def migrate(self): """ Should be overridden by classes which inherit this class. """ pass def merge(self, arg_dict=None, overwrite=False, **kwargs): """ Merge a dictionary into a top-level object class. :param arg_dict: The dictionary to get data from. :type arg_dict: dict :param overwrite: Whether or not to overwrite data in the object. :type overwrite: boolean """ merge(self, arg_dict=arg_dict, overwrite=overwrite) def to_csv(self, fields=[],headers=False): """ Convert a class into a CSV. :param fields: Fields to include in the CSV. :type fields: list :param headers: Whether or not to write out column headers. :type headers: boolean :returns: str """ if not fields: fields = self._data.keys() csv_string = io.BytesIO() csv_wr = csv.writer(csv_string) if headers: csv_wr.writerow([f.encode('utf-8') for f in fields]) # Build the CSV Row row = [] for field in fields: if field in self._data: data = "" if field == "aliases" and self._has_method("get_aliases"): data = ";".join(self.get_aliases()) elif field == "source" and self._has_method("get_source_names"): data = ';'.join(self.get_source_names()) elif field == "tickets": data = ';'.join(self.get_tickets()) else: data = self._data[field] if not hasattr(data, 'encode'): # Convert non-string data types data = unicode(data) row.append(data.encode('utf-8')) csv_wr.writerow(row) return csv_string.getvalue() def to_dict(self, exclude=[], include=[]): """ Return the object's _data as a python dictionary. All fields will be converted to base python types so that no MongoEngine fields remain. :param exclude: list of fields to exclude in the result. :type exclude: list :param include: list of fields to include in the result. :type include: list :returns: dict """ #MongoEngine's to_mongo() returns an object in a MongoDB friendly # dictionary format. If we have no extra processing to do, just # return that. data = self.to_mongo() # # Include, Exclude, return # Check projection in db_field_map # After the to_mongo, the fields have changed newproj = [] for p in include: if p in self._db_field_map: p = self._db_field_map[p] elif p == "id": # _id is not in the db_field_map p = "_id" newproj.append(p) if include: result = {} for k, v in data.items(): if k in newproj and k not in exclude: if k == "_id": k = "id" result[k] = v return result elif exclude: result = {} for k, v in data.items(): if k in exclude: continue if k == "_id": k = "id" result[k] = v return result return data def _json_yaml_convert(self, exclude=[]): """ Helper to convert to a dict before converting to JSON. :param exclude: list of fields to exclude. :type exclude: list :returns: json """ d = self.to_dict(exclude) return json.dumps(d, default=json_handler) @classmethod def from_json(cls, json_data): """ Converts JSON data to an unsaved document instance. NOTE: this method already exists in mongoengine 0.8, so it can be removed from here when the codebase is updated. :returns: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` """ return cls._from_son(json_util.loads(json_data)) def to_json(self, exclude=[]): """ Convert to JSON. :param exclude: list of fields to exclude. :type exclude: list :returns: json """ print("doing to json in cripts document") return self._json_yaml_convert(exclude) @classmethod def from_yaml(cls, yaml_data): """ Converts YAML data to an unsaved document instance. :returns: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` """ return cls._from_son(yaml.load(yaml_data)) def to_yaml(self, exclude=[]): """ Convert to JSON. :param exclude: list of fields to exclude. :type exclude: list :returns: json """ return yaml.dump(yaml.load(self._json_yaml_convert(exclude)), default_flow_style=False) def __str__(self): """ Allow us to print the class in a readable fashion. :returns: str """ return pformat(self.to_dict()) class EmbeddedPreferredAction(EmbeddedDocument, CriptsDocumentFormatter): """ Embedded Preferred Action """ object_type = StringField() object_field = StringField() object_value = StringField() class Action(CriptsDocument, CriptsSchemaDocument, Document): """ Action type class. """ meta = { "collection": settings.COL_IDB_ACTIONS, "cripts_type": 'Action', "latest_schema_version": 1, "schema_doc": { 'name': 'The name of this Action', 'active': 'Enabled in the UI (on/off)', 'object_types': 'List of TLOs this is for', 'preferred': 'List of dictionaries defining where this is preferred' }, } name = StringField() active = StringField(default="on") object_types = ListField(StringField()) preferred = ListField(EmbeddedDocumentField(EmbeddedPreferredAction)) class EmbeddedAction(EmbeddedDocument, CriptsDocumentFormatter): """ Embedded action class. """ action_type = StringField() active = StringField() analyst = StringField() begin_date = CriptsDateTimeField(default=datetime.datetime.now) date = CriptsDateTimeField(default=datetime.datetime.now) end_date = CriptsDateTimeField() performed_date = CriptsDateTimeField(default=datetime.datetime.now) reason = StringField() class CriptsActionsDocument(BaseDocument): """ Inherit if you want to track actions information on a top-level object. """ actions = ListField(EmbeddedDocumentField(EmbeddedAction)) def add_action(self, type_, active, analyst, begin_date, end_date, performed_date, reason, date=None): """ Add an action to an Indicator. :param type_: The type of action. :type type_: str :param active: Whether this action is active or not. :param active: str ("on", "off") :param analyst: The user adding this action. :type analyst: str :param begin_date: The date this action begins. :type begin_date: datetime.datetime :param end_date: The date this action ends. :type end_date: datetime.datetime :param performed_date: The date this action was performed. :type performed_date: datetime.datetime :param reason: The reason for this action. :type reason: str :param date: The date this action was added to CRIPTs. :type date: datetime.datetime """ ea = EmbeddedAction() ea.action_type = type_ ea.active = active ea.analyst = analyst ea.begin_date = begin_date ea.end_date = end_date ea.performed_date = performed_date ea.reason = reason if date: ea.date = date self.actions.append(ea) def delete_action(self, date=None, action=None): """ Delete an action. :param date: The date of the action to delete. :type date: datetime.datetime :param action: The action to delete. :type action: str """ if not date or not action: return for t in self.actions: if t.date == date and t.action_type == action: self.actions.remove(t) break def edit_action(self, type_, active, analyst, begin_date, end_date, performed_date, reason, date=None): """ Edit an action for an Indicator. :param type_: The type of action. :type type_: str :param active: Whether this action is active or not. :param active: str ("on", "off") :param analyst: The user editing this action. :type analyst: str :param begin_date: The date this action begins. :type begin_date: datetime.datetime :param end_date: The date this action ends. :type end_date: datetime.datetime :param performed_date: The date this action was performed. :type performed_date: datetime.datetime :param reason: The reason for this action. :type reason: str :param date: The date this action was added to CRIPTs. :type date: datetime.datetime """ if not date: return for t in self.actions: if t.date == date and t.action_type == type_: self.actions.remove(t) ea = EmbeddedAction() ea.action_type = type_ ea.active = active ea.analyst = analyst ea.begin_date = begin_date ea.end_date = end_date ea.performed_date = performed_date ea.reason = reason ea.date = date self.actions.append(ea) break # Embedded Documents common to most classes class EmbeddedSource(EmbeddedDocument, CriptsDocumentFormatter): """ Embedded Source. """ class SourceInstance(EmbeddedDocument, CriptsDocumentFormatter): """ Information on the instance of this source. """ analyst = StringField() date = CriptsDateTimeField(default=datetime.datetime.now) method = StringField() reference = StringField() def __eq__(self, other): """ Two source instances are equal if their data attributes are equal """ if isinstance(other, type(self)): if (self.analyst == other.analyst and self.date == other.date and self.method == other.method and self.reference == other.reference): # all data attributes are equal, so sourceinstances are equal return True return False instances = ListField(EmbeddedDocumentField(SourceInstance)) name = StringField() class CriptsSourceDocument(BaseDocument): """ Inherit if you want to track source information on a top-level object. """ source = ListField(EmbeddedDocumentField(EmbeddedSource), required=True) def add_source(self, source_item=None, source=None, method='', reference='', date=None, analyst=None): """ Add a source instance to this top-level object. :param source_item: An entire source instance. :type source_item: :class:`cripts.core.cripts_mongoengine.EmbeddedSource` :param source: Name of the source. :type source: str :param method: Method of acquisition. :type method: str :param reference: Reference to the data from the source. :type reference: str :param date: The date of acquisition. :type date: datetime.datetime :param analyst: The user adding the source instance. :type analyst: str """ s = None if source and analyst: if not date: date = datetime.datetime.now() s = EmbeddedSource() s.name = source i = EmbeddedSource.SourceInstance() i.date = date i.reference = reference i.method = method i.analyst = analyst s.instances = [i] if not isinstance(source_item, EmbeddedSource): source_item = s if isinstance(source_item, EmbeddedSource): match = None if method or reference: # if method or reference is given, use it for instance in source_item.instances: instance.method = method or instance.method instance.reference = reference or instance.reference for c, s in enumerate(self.source): if s.name == source_item.name: # find index of matching source match = c break if match is not None: # if source exists, add instances to it # Don't add exact duplicates for new_inst in source_item.instances: for exist_inst in self.source[match].instances: if new_inst == exist_inst: break else: self.source[match].instances.append(new_inst) else: # else, add as new source self.source.append(source_item) def edit_source(self, source=None, date=None, method='', reference='', analyst=None): """ Edit a source instance from this top-level object. :param source: Name of the source. :type source: str :param date: The date of acquisition to match on. :type date: datetime.datetime :param method: Method of acquisition. :type method: str :param reference: Reference to the data from the source. :type reference: str :param analyst: The user editing the source instance. :type analyst: str """ if source and date: for c, s in enumerate(self.source): if s.name == source: for i, si in enumerate(s.instances): if si.date == date: self.source[c].instances[i].method = method self.source[c].instances[i].reference = reference self.source[c].instances[i].analyst = analyst def remove_source(self, source=None, date=None, remove_all=False): """ Remove a source or source instance from a top-level object. :param source: Name of the source. :type source: str :param date: Date to match on. :type date: datetime.datetime :param remove_all: Remove all instances of this source. :type remove_all: boolean :returns: dict with keys "success" (boolean) and "message" (str) """ keepone = {'success': False, 'message': "Must leave at least one source for access controls. " "If you wish to change the source, please assign a new source and then remove the old."} if not source: return {'success': False, 'message': 'No source to locate'} if not remove_all and not date: return {'success': False, 'message': 'Not removing all and no date to find.'} for s in self.source: if s.name == source: if remove_all: if len(self.source) > 1: self.source.remove(s) message = "Deleted source %s" % source return {'success': True, 'message': message} else: return keepone else: for si in s.instances: if si.date == date: if len(s.instances) > 1: s.instances.remove(si) message = "Deleted instance of %s" % source return {'success': True, 'message': message} else: if len(self.source) > 1: self.source.remove(s) message = "Deleted source %s" % source return {'success': True, 'message': message} else: return keepone def sanitize_sources(self, username=None, sources=None): """ Sanitize the source list down to only those a user has access to see. :param username: The user requesting this data. :type username: str :param sources: A list of sources the user has access to. :type sources: list """ if username and hasattr(self, 'source'): length = len(self.source) if not sources: sources = user_sources(username) # use slice to modify in place in case any code is referencing # the source already will reflect the changes as well self.source[:] = [s for s in self.source if s.name in sources] # a bit of a hack but we add a poorly formatted source to the # source list which has an instances length equal to the amount # of sources that were sanitized out of the user's list. # not tested but this has the added benefit of throwing a # ValidationError if someone were to try and save() this. new_length = len(self.source) if length > new_length: i_length = length - new_length s = EmbeddedSource() s.name = "Other" s.instances = [0] * i_length self.source.append(s) def get_source_names(self): """ Return a list of source names that have provided this data. """ return [obj['name'] for obj in self._data['source']] class EmbeddedTicket(EmbeddedDocument, CriptsDocumentFormatter): """ Embedded Ticket Class. """ analyst = StringField() date = CriptsDateTimeField(default=datetime.datetime.now) ticket_number = StringField() class EmbeddedTickets(BaseDocument): """ Embedded Tickets List. """ tickets = ListField(EmbeddedDocumentField(EmbeddedTicket)) def is_ticket_exist(self, ticket_number): """ Does this ticket already exist? :param ticket_number: The ticket to look for. :type ticket_number: str :returns: True, False """ for ticket in self.tickets: if ticket_number == ticket.ticket_number: return True; return False; def add_ticket(self, tickets, analyst=None, date=None): """ Add a ticket to this top-level object. :param tickets: The ticket(s) to add. :type tickets: str, list, or :class:`cripts.core.cripts_mongoengine.EmbeddedTicket` :param analyst: The user adding this ticket. :type analyst: str :param date: The date for the ticket. :type date: datetime.datetime. """ if isinstance(tickets, basestring): tickets = tickets.split(',') elif not isinstance(tickets, list): tickets = [tickets] for ticket in tickets: if isinstance(ticket, EmbeddedTicket): if not self.is_ticket_exist(ticket.ticket_number): # stop dups self.tickets.append(ticket) elif isinstance(ticket, basestring): if ticket and not self.is_ticket_exist(ticket): # stop dups et = EmbeddedTicket() et.analyst = analyst et.ticket_number = ticket if date: et.date = date self.tickets.append(et) def edit_ticket(self, analyst, ticket_number, date=None): """ Edit a ticket this top-level object. :param analyst: The user editing this ticket. :type analyst: str :param ticket_number: The new ticket value. :type ticket_number: str :param date: The date for the ticket. :type date: datetime.datetime. """ if not date: return for t in self.tickets: if t.date == date: self.tickets.remove(t) et = EmbeddedTicket() et.analyst = analyst et.ticket_number = ticket_number et.date = date self.tickets.append(et) break def delete_ticket(self, date=None): """ Delete a ticket from this top-level object. :param date: The date the ticket was added. :type date: datetime.datetime """ if not date: return for t in self.tickets: if t.date == date: self.tickets.remove(t) break def get_tickets(self): """ Get the tickets for this top-level object. :returns: list """ return [obj['ticket_number'] for obj in self._data['tickets']] class Releasability(EmbeddedDocument, CriptsDocumentFormatter): """ Releasability Class. """ class ReleaseInstance(EmbeddedDocument, CriptsDocumentFormatter): """ Releasability Instance Class. """ analyst = StringField() date = DateTimeField() note = StringField() name = StringField() analyst = StringField() instances = ListField(EmbeddedDocumentField(ReleaseInstance)) class UnrecognizedSchemaError(ValidationError): """ Error if the schema for a document is not found or unrecognized. """ def __init__(self, doc, **kwargs): message = "Document schema is unrecognized: %s" % doc.schema_version self.schema = doc._meta['schema_doc'] self.doc = doc.to_dict() super(UnrecognizedSchemaError, self).__init__(message=message, field_name='schema_version', **kwargs) class EmbeddedObject(EmbeddedDocument, CriptsDocumentFormatter): """ Embedded Object Class. """ analyst = StringField() date = CriptsDateTimeField(default=datetime.datetime.now) source = ListField(EmbeddedDocumentField(EmbeddedSource), required=True) object_type = StringField(required=True, db_field="type") value = StringField(required=True) class EmbeddedRelationship(EmbeddedDocument, CriptsDocumentFormatter): """ Embedded Relationship Class. """ relationship = StringField(required=True) relationship_date = CriptsDateTimeField() object_id = ObjectIdField(required=True, db_field="value") date = CriptsDateTimeField(default=datetime.datetime.now) rel_type = StringField(db_field="type", required=True) analyst = StringField() rel_reason = StringField() rel_confidence = StringField(default='unknown', required=True) class CriptsBaseAttributes(CriptsDocument, CriptsBaseDocument, CriptsSchemaDocument, CriptsStatusDocument, EmbeddedTickets): """ CRIPTs Base Attributes Class. The main class that should be inherited if you are making a new top-level object. Adds all of the standard top-level object features. """ analyst = StringField() bucket_list = ListField(StringField()) description = StringField() obj = ListField(EmbeddedDocumentField(EmbeddedObject), db_field="objects") relationships = ListField(EmbeddedDocumentField(EmbeddedRelationship)) releasability = ListField(EmbeddedDocumentField(Releasability)) sectors = ListField(StringField()) def add_bucket_list(self, tags, analyst, append=True): """ Add buckets to this top-level object. :param tags: The buckets to be added. :type tags: list, str :param analyst: The analyst adding these buckets. :type analyst: str :param append: Whether or not to replace or append these buckets. :type append: boolean """ from cripts.core.handlers import alter_bucket_list # Track the addition or subtraction of tags. # Get the bucket_list for the object, find out if this is an addition # or subtraction of a bucket_list. if isinstance(tags, list) and len(tags) == 1 and tags[0] == '': parsed_tags = [] elif isinstance(tags, (str, unicode)): parsed_tags = tags.split(',') else: parsed_tags = tags parsed_tags = [t.strip() for t in parsed_tags] names = None if len(self.bucket_list) >= len(parsed_tags): names = [x for x in self.bucket_list if x not in parsed_tags and x != ''] val = -1 else: names = [x for x in parsed_tags if x not in self.bucket_list and x != ''] val = 1 if names: alter_bucket_list(self, names, val) if append: for t in parsed_tags: if t and t not in self.bucket_list: self.bucket_list.append(t) else: self.bucket_list = parsed_tags def get_bucket_list_string(self): """ Collapse the list of buckets into a single comma-separated string. :returns: str """ return ','.join(str(x) for x in self.bucket_list) def add_sector_list(self, sectors, analyst, append=True): """ Add sectors to this top-level object. :param sectors: The sectors to be added. :type tags: list, str :param analyst: The analyst adding these sectors. :type analyst: str :param append: Whether or not to replace or append these sectors. :type append: boolean """ from cripts.core.handlers import alter_sector_list # Track the addition or subtraction of tags. # Get the sectors for the object, find out if this is an addition # or subtraction of a sector. if isinstance(sectors, list) and len(sectors) == 1 and sectors[0] == '': parsed_sectors = [] elif isinstance(sectors, (str, unicode)): parsed_sectors = sectors.split(',') else: parsed_sectors = sectors parsed_sectors = [s.strip() for s in parsed_sectors] names = None if len(self.sectors) >= len(parsed_sectors): names = [x for x in self.sectors if x not in parsed_sectors and x != ''] val = -1 else: names = [x for x in parsed_sectors if x not in self.sectors and x != ''] val = 1 if names: alter_sector_list(self, names, val) if append: for t in parsed_sectors: if t not in self.sectors: self.sectors.append(t) else: self.sectors = parsed_sectors def get_sectors_list_string(self): """ Collapse the list of sectors into a single comma-separated string. :returns: str """ return ','.join(str(x) for x in self.sectors) def get_comments(self): """ Get the comments for this top-level object. :returns: list """ from cripts.comments.handlers import get_comments comments = get_comments(self.id, self._meta['cripts_type']) return comments def delete_all_comments(self): """ Delete all comments for this top-level object. """ from cripts.comments.comment import Comment Comment.objects(obj_id=self.id, obj_type=self._meta['cripts_type']).delete() def add_object(self, object_type, value, source, method, reference, analyst, object_item=None): """ Add an object to this top-level object. :param object_type: The Object Type being added. :type object_type: str :param value: The value of the object being added. :type value: str :param source: The name of the source adding this object. :type source: str :param method: The method in which the object was added or gathered. :type method: str :param reference: A reference to the original object. :type reference: str :param analyst: The user adding this object. :type analyst: str :param object_item: An entire object ready to be added. :type object_item: :class:`cripts.core.cripts_mongoengine.EmbeddedObject` :returns: dict with keys: "success" (boolean) "message" (str) "object" (EmbeddedObject) """ if not isinstance(object_item, EmbeddedObject): object_item = EmbeddedObject() object_item.analyst = analyst src = create_embedded_source(source, method=method, reference=reference, analyst=analyst) if not src: return {'success': False, 'message': 'Invalid Source'} object_item.source = [src] object_item.object_type = object_type object_item.value = value for o in self.obj: if (o.object_type == object_item.object_type and o.value == object_item.value): return {'success': False, 'object': o, 'message': 'Object already exists'} self.obj.append(object_item) return {'success': True, 'object': object_item} def remove_object(self, object_type, value): """ Remove an object from this top-level object. :param object_type: The type of the object being removed. :type object_type: str :param value: The value of the object being removed. :type value: str """ for o in self.obj: if (o.object_type == object_type and o.value == value): from cripts.objects.handlers import delete_object_file self.obj.remove(o) delete_object_file(value) break def delete_all_analysis_results(self): """ Delete all analysis results for this top-level object. """ from cripts.services.analysis_result import AnalysisResult results = AnalysisResult.objects(object_id=str(self.id)) for result in results: result.delete() def delete_all_objects(self): """ Delete all objects for this top-level object. """ from cripts.objects.handlers import delete_object_file for o in self.obj: if o.object_type == ObjectTypes.FILE_UPLOAD: delete_object_file(o.value) self.obj = [] def delete_all_favorites(self): """ Delete all favorites for this top-level object. """ from cripts.core.user import CRIPTsUser users = CRIPTsUser.objects() for user in users: type_ = self._meta['cripts_type'] if type_ in user.favorites and str(self.id) in user.favorites[type_]: user.favorites[type_].remove(str(self.id)) user.save() def update_object_value(self, object_type, value, new_value): """ Update the value for an object on this top-level object. :param object_type: The type of the object being updated. :type object_type: str :param value: The value of the object being updated. :type value: str :param new_value: The new value of the object being updated. :type new_value: str """ for c, o in enumerate(self.obj): if (o.object_type == object_type and o.value == value): self.obj[c].value = new_value break def update_object_source(self, object_type, value, new_source=None, new_method='', new_reference='', analyst=None): """ Update the source for an object on this top-level object. :param object_type: The type of the object being updated. :type object_type: str :param value: The value of the object being updated. :type value: str :param new_source: The name of the new source. :type new_source: str :param new_method: The method of the new source. :type new_method: str :param new_reference: The reference of the new source. :type new_reference: str :param analyst: The user updating the source. :type analyst: str """ for c, o in enumerate(self.obj): if (o.object_type == object_type and o.value == value): if not analyst: analyst = self.obj[c].source[0].intances[0].analyst source = [create_embedded_source(new_source, method=new_method, reference=new_reference, analyst=analyst)] self.obj[c].source = source break def sort_objects(self): """ Sort the objects for this top-level object. :returns: dict """ o_dict = dict((o.object_type,[]) for o in self.obj) o_dict['Other'] = 0 o_dict['Count'] = len(self.obj) for o in self.obj: o_dict[o.object_type].append(o.to_dict()) return o_dict def add_relationship(self, rel_item, rel_type, rel_date=None, analyst=None, rel_confidence='unknown', rel_reason='', get_rels=False): """ Add a relationship to this top-level object. The rel_item will be saved. It is up to the caller to save "self". :param rel_item: The top-level object to relate to. :type rel_item: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` :param rel_type: The type of relationship. :type rel_type: str :param rel_date: The date this relationship applies. :type rel_date: datetime.datetime :param analyst: The user forging this relationship. :type analyst: str :param rel_confidence: The confidence of the relationship. :type rel_confidence: str :param rel_reason: The reason for the relationship. :type rel_reason: str :param get_rels: If True, return all relationships after forging. If False, return the new EmbeddedRelationship object :type get_rels: boolean :returns: dict with keys: "success" (boolean) "message" (str if failed, else dict or EmbeddedRelationship) """ # Prevent class from having a relationship to itself if self == rel_item: return {'success': False, 'message': 'Cannot forge relationship to oneself'} # get reverse relationship rev_type = RelationshipTypes.inverse(rel_type) if rev_type is None: return {'success': False, 'message': 'Could not find relationship type'} date = datetime.datetime.now() # setup the relationship for me my_rel = EmbeddedRelationship() my_rel.relationship = rel_type my_rel.rel_type = rel_item._meta['cripts_type'] my_rel.analyst = analyst my_rel.date = date my_rel.relationship_date = rel_date my_rel.object_id = rel_item.id my_rel.rel_confidence = rel_confidence my_rel.rel_reason = rel_reason # setup the relationship for them their_rel = EmbeddedRelationship() their_rel.relationship = rev_type their_rel.rel_type = self._meta['cripts_type'] their_rel.analyst = analyst their_rel.date = date their_rel.relationship_date = rel_date their_rel.object_id = self.id their_rel.rel_confidence = rel_confidence their_rel.rel_reason = rel_reason # variables for detecting if an existing relationship exists my_existing_rel = None their_existing_rel = None # check for existing relationship before blindly adding for r in self.relationships: if (r.object_id == my_rel.object_id and r.relationship == my_rel.relationship and (not rel_date or r.relationship_date == rel_date) and r.rel_type == my_rel.rel_type): my_existing_rel = r break # If relationship already exists then exit loop for r in rel_item.relationships: if (r.object_id == their_rel.object_id and r.relationship == their_rel.relationship and (not rel_date or r.relationship_date == rel_date) and r.rel_type == their_rel.rel_type): their_existing_rel = r break # If relationship already exists then exit loop # If the relationship already exists on both sides then do nothing if my_existing_rel and their_existing_rel: return {'success': False, 'message': 'Relationship already exists'} # Repair unreciprocated relationships if not my_existing_rel: # If my rel does not exist then add it if their_existing_rel: # If their rel exists then use its data my_rel.analyst = their_existing_rel.analyst my_rel.date = their_existing_rel.date my_rel.relationship_date = their_existing_rel.relationship_date my_rel.rel_confidence = their_existing_rel.rel_confidence my_rel.rel_reason = their_existing_rel.rel_reason self.relationships.append(my_rel) # add my new relationship if not their_existing_rel: # If their rel does not exist then add it if my_existing_rel: # If my rel exists then use its data their_rel.analyst = my_existing_rel.analyst their_rel.date = my_existing_rel.date their_rel.relationship_date = my_existing_rel.relationship_date their_rel.rel_confidence = my_existing_rel.rel_confidence their_rel.rel_reason = my_existing_rel.rel_reason rel_item.relationships.append(their_rel) # add to passed rel_item # updating DB this way can be much faster than saving entire TLO rel_item.update(add_to_set__relationships=their_rel) if get_rels: results = {'success': True, 'message': self.sort_relationships(analyst, meta=True)} else: results = {'success': True, 'message': my_rel} return results def _modify_relationship(self, rel_item=None, rel_id=None, type_=None, rel_type=None, rel_date=None, new_type=None, new_date=None, new_confidence='unknown', new_reason="N/A", modification=None, analyst=None): """ Modify a relationship to this top-level object. If rel_item is provided it will be used, otherwise rel_id and type_ must be provided. :param rel_item: The top-level object to relate to. :type rel_item: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` :param rel_id: The ObjectId of the top-level object to relate to. :type rel_id: str :param type_: The type of top-level object to relate to. :type type_: str :param rel_type: The type of relationship. :type rel_type: str :param rel_date: The date this relationship applies. :type rel_date: datetime.datetime :param new_type: The new relationship type. :type new_type: str :param new_date: The new relationship date. :type new_date: datetime.datetime :param new_confidence: The new confidence. :type new_confidence: str :param new_reason: The new reason. :type new_reason: str :param modification: What type of modification this is ("type", "delete", "date", "confidence"). :type modification: str :param analyst: The user forging this relationship. :type analyst: str :returns: dict with keys "success" (boolean) and "message" (str) """ got_rel = True if not rel_item: got_rel = False if isinstance(rel_id, basestring) and isinstance(type_, basestring): rel_item = class_from_id(type_, rel_id) else: return {'success': False, 'message': 'Could not find object'} if isinstance(new_date, basestring): new_date = parse(new_date, fuzzy=True) if rel_item and rel_type and modification: # get reverse relationship rev_type = RelationshipTypes.inverse(rel_type) if rev_type is None: return {'success': False, 'message': 'Could not find relationship type'} if modification == "type": # get new reverse relationship new_rev_type = RelationshipTypes.inverse(new_type) if new_rev_type is None: return {'success': False, 'message': 'Could not find reverse relationship type'} for c, r in enumerate(self.relationships): if rel_date: if (r.object_id == rel_item.id and r.relationship == rel_type and r.relationship_date == rel_date and r.rel_type == rel_item._meta['cripts_type']): if modification == "type": self.relationships[c].relationship = new_type elif modification == "date": self.relationships[c].relationship_date = new_date elif modification == "confidence": self.relationships[c].rel_confidence = new_confidence elif modification == "reason": self.relationships[c].rel_reason = new_reason elif modification == "delete": self.relationships.remove(r) break else: if (r.object_id == rel_item.id and r.relationship == rel_type and r.rel_type == rel_item._meta['cripts_type']): if modification == "type": self.relationships[c].relationship = new_type elif modification == "date": self.relationships[c].relationship_date = new_date elif modification == "confidence": self.relationships[c].rel_confidence = new_confidence elif modification == "reason": self.relationships[c].rel_reason = new_reason elif modification == "delete": self.relationships.remove(r) break for c, r in enumerate(rel_item.relationships): if rel_date: if (r.object_id == self.id and r.relationship == rev_type and r.relationship_date == rel_date and r.rel_type == self._meta['cripts_type']): if modification == "type": rel_item.relationships[c].relationship = new_rev_type elif modification == "date": rel_item.relationships[c].relationship_date = new_date elif modification == "confidence": rel_item.relationships[c].rel_confidence = new_confidence elif modification == "reason": rel_item.relationships[c].rel_reason = new_reason elif modification == "delete": rel_item.relationships.remove(r) break else: if (r.object_id == self.id and r.relationship == rev_type and r.rel_type == self._meta['cripts_type']): if modification == "type": rel_item.relationships[c].relationship = new_rev_type elif modification == "date": rel_item.relationships[c].relationship_date = new_date elif modification == "confidence": rel_item.relationships[c].rel_confidence = new_confidence elif modification == "reason": rel_item.relationships[c].rel_reason = new_reason elif modification == "delete": rel_item.relationships.remove(r) break if not got_rel: rel_item.save(username=analyst) if modification == "delete": return {'success': True, 'message': 'Relationship deleted'} else: return {'success': True, 'message': 'Relationship modified'} else: return {'success': False, 'message': 'Need valid object and relationship type'} def edit_relationship_date(self, rel_item=None, rel_id=None, type_=None, rel_type=None, rel_date=None, new_date=None, analyst=None): """ Modify a relationship date for a relationship to this top-level object. If rel_item is provided it will be used, otherwise rel_id and type_ must be provided. :param rel_item: The top-level object to relate to. :type rel_item: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` :param rel_id: The ObjectId of the top-level object to relate to. :type rel_id: str :param type_: The type of top-level object to relate to. :type type_: str :param rel_type: The type of relationship. :type rel_type: str :param rel_date: The date this relationship applies. :type rel_date: datetime.datetime :param new_date: The new relationship date. :type new_date: datetime.datetime :param analyst: The user editing this relationship. :type analyst: str :returns: dict with keys "success" (boolean) and "message" (str) """ return self._modify_relationship(rel_item=rel_item, rel_id=rel_id, type_=type_, rel_type=rel_type, rel_date=rel_date, new_date=new_date, modification="date", analyst=analyst) def edit_relationship_type(self, rel_item=None, rel_id=None, type_=None, rel_type=None, rel_date=None, new_type=None, analyst=None): """ Modify a relationship type for a relationship to this top-level object. If rel_item is provided it will be used, otherwise rel_id and type_ must be provided. :param rel_item: The top-level object to relate to. :type rel_item: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` :param rel_id: The ObjectId of the top-level object to relate to. :type rel_id: str :param type_: The type of top-level object to relate to. :type type_: str :param rel_type: The type of relationship. :type rel_type: str :param rel_date: The date this relationship applies. :type rel_date: datetime.datetime :param new_type: The new relationship type. :type new_type: str :param analyst: The user editing this relationship. :type analyst: str :returns: dict with keys "success" (boolean) and "message" (str) """ return self._modify_relationship(rel_item=rel_item, rel_id=rel_id, type_=type_, rel_type=rel_type, rel_date=rel_date, new_type=new_type, modification="type", analyst=analyst) def edit_relationship_confidence(self, rel_item=None, rel_id=None, type_=None, rel_type=None, rel_date=None, new_confidence='unknown', analyst=None): """ Modify a relationship type for a relationship to this top-level object. If rel_item is provided it will be used, otherwise rel_id and type_ must be provided. :param rel_item: The top-level object to relate to. :type rel_item: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` :param rel_id: The ObjectId of the top-level object to relate to. :type rel_id: str :param type_: The type of top-level object to relate to. :type type_: str :param rel_type: The type of relationship. :type rel_type: str :param rel_date: The date this relationship applies. :type rel_date: datetime.datetime :param new_confidence: The new confidence of the relationship. :type new_confidence: str :param analyst: The user editing this relationship. :type analyst: str :returns: dict with keys "success" (boolean) and "message" (str) """ return self._modify_relationship(rel_item=rel_item, rel_id=rel_id, type_=type_, rel_type=rel_type, rel_date=rel_date, new_confidence=new_confidence, modification="confidence", analyst=analyst) def edit_relationship_reason(self, rel_item=None, rel_id=None, type_=None, rel_type=None, rel_date=None, new_reason="N/A", analyst=None): """ Modify a relationship type for a relationship to this top-level object. If rel_item is provided it will be used, otherwise rel_id and type_ must be provided. :param rel_item: The top-level object to relate to. :type rel_item: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` :param rel_id: The ObjectId of the top-level object to relate to. :type rel_id: str :param type_: The type of top-level object to relate to. :type type_: str :param rel_type: The type of relationship. :type rel_type: str :param rel_date: The date this relationship applies. :type rel_date: datetime.datetime :param new_confidence: The new confidence of the relationship. :type new_confidence: int :param analyst: The user editing this relationship. :type analyst: str :returns: dict with keys "success" (boolean) and "message" (str) """ return self._modify_relationship(rel_item=rel_item, rel_id=rel_id, type_=type_, rel_type=rel_type, rel_date=rel_date, new_reason=new_reason, modification="reason", analyst=analyst) def delete_relationship(self, rel_item=None, rel_id=None, type_=None, rel_type=None, rel_date=None, analyst=None, *args, **kwargs): """ Delete a relationship from a relationship to this top-level object. If rel_item is provided it will be used, otherwise rel_id and type_ must be provided. :param rel_item: The top-level object to remove relationship to. :type rel_item: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` :param rel_id: The ObjectId of the top-level object to relate to. :type rel_id: str :param type_: The type of top-level object to relate to. :type type_: str :param rel_type: The type of relationship. :type rel_type: str :param rel_date: The date this relationship applies. :type rel_date: datetime.datetime :param analyst: The user removing this relationship. :type analyst: str :returns: dict with keys "success" (boolean) and "message" (str) """ return self._modify_relationship(rel_item=rel_item, rel_id=rel_id, type_=type_, rel_type=rel_type, rel_date=rel_date, analyst=analyst, modification="delete") def delete_all_relationships(self, username=None): """ Delete all relationships from this top-level object. :param username: The user deleting all of the relationships. :type username: str """ for r in self.relationships[:]: if r.relationship_date: self.delete_relationship(rel_id=str(r.object_id), type_=r.rel_type, rel_type=r.relationship, rel_date=r.relationship_date, analyst=username) else: self.delete_relationship(rel_id=str(r.object_id), type_=r.rel_type, rel_type=r.relationship, analyst=username) def sort_relationships(self, username=None, meta=False): """ Sort the relationships for inclusion in a template. :param username: The user requesting the relationships. :type username: str :param meta: Limit the results to only a subset of metadata. :type meta: boolean :returns: dict """ if len(self.relationships) < 1: return {} rel_dict = dict((r.rel_type,[]) for r in self.relationships) query_dict = { 'Dataset': ('id'), 'EmailAddress': ('id','address'), 'Event': ('id', 'title', 'event_type', 'description'), 'Hash': ('id'), 'Target': ('id'), 'UserName': ('id','name'), } rel_dict['Other'] = 0 rel_dict['Count'] = len(self.relationships) if not meta: for r in self.relationships: rd = r.to_dict() rel_dict[rd['type']].append(rd) return rel_dict elif username: user_source_access = user_sources(username) for r in self.relationships: rd = r.to_dict() obj_class = class_from_type(rd['type']) # TODO: these should be limited to the fields above, or at # least exclude larger fields that we don't need. fields = query_dict.get(rd['type']) if r.rel_type not in ["Campaign", "Target"]: obj = obj_class.objects(id=rd['value'], source__name__in=user_source_access).only(*fields).first() else: obj = obj_class.objects(id=rd['value']).only(*fields).first() if obj: # we can't add and remove attributes on the class # so convert it to a dict that we can manipulate. result = obj.to_dict() if "_id" in result: result["id"] = result["_id"] if "type" in result: result["ind_type"] = result["type"] del result["type"] if "value" in result: result["ind_value"] = result["value"] del result["value"] # turn this relationship into a dict so we can update # it with the object information rd.update(result) rel_dict[rd['type']].append(rd) else: rel_dict['Other'] += 1 return rel_dict else: return {} def get_relationship_objects(self, username=None, sources=None): """ Return the top-level objects this top-level object is related to. :param username: The user requesting these top-level objects. :type username: str :param sources: The user's source access list to limit by. :type sources: list :returns: list """ results = [] if not username: return results if not hasattr(self, 'relationships'): return results if not sources: sources = user_sources(username) for r in self.relationships: rd = r.to_dict() obj_class = class_from_type(rd['type']) if r.rel_type not in ["Campaign", "Target"]: obj = obj_class.objects(id=rd['value'], source__name__in=sources).first() else: obj = obj_class.objects(id=rd['value']).first() if obj: results.append(obj) return results def add_releasability(self, source_item=None, analyst=None, *args, **kwargs): """ Add a source as releasable for this top-level object. :param source_item: The source to allow releasability for. :type source_item: dict or :class:`cripts.core.cripts_mongoengine.Releasability` :param analyst: The user marking this as releasable. :type analyst: str """ if isinstance(source_item, Releasability): rels = self.releasability for r in rels: if r.name == source_item.name: break else: if analyst: source_item.analyst = analyst self.releasability.append(source_item) elif isinstance(source_item, dict): rels = self.releasability for r in rels: if r.name == source_item['name']: break else: if analyst: source_item['analyst'] = analyst self.releasability.append(Releasability(**source_item)) else: rel = Releasability(**kwargs) if analyst: rel.analyst = analyst rels = self.releasability for r in rels: if r.name == rel.name: break else: self.releasability.append(rel) def add_releasability_instance(self, name=None, instance=None, *args, **kwargs): """ Add an instance of releasing this top-level object to a source. :param name: The name of the source that received the data. :type name: str :param instance: The instance of releasability. :type instance: :class:`cripts.core.cripts_mongoengine.Releasability.ReleaseInstance` """ if isinstance(instance, Releasability.ReleaseInstance): for r in self.releasability: if r.name == name: r.instances.append(instance) def remove_releasability(self, name=None, *args, **kwargs): """ Remove a source as releasable for this top-level object. :param name: The name of the source to remove from releasability. :type name: str """ if isinstance(name, basestring): for r in self.releasability: if r.name == name and len(r.instances) == 0: self.releasability.remove(r) break def remove_releasability_instance(self, name=None, date=None, *args, **kwargs): """ Remove an instance of releasing this top-level object to a source. :param name: The name of the source. :type name: str :param date: The date of the instance to remove. :type date: datetime.datetime """ if not isinstance(date, datetime.datetime): date = parse(date, fuzzy=True) for r in self.releasability: if r.name == name: for ri in r.instances: if ri.date == date: r.instances.remove(ri) def sanitize_relationships(self, username=None, sources=None): """ Sanitize the relationships list down to only what the user can see based on source access. :param username: The user to sanitize for. :type username: str :param source: The user's source list. :type source: list """ if username: if not sources: sources = user_sources(username) final_rels = [] for r in self.relationships: rd = r.to_dict() obj_class = class_from_type(rd['type']) if r.rel_type not in ["Campaign", "Target"]: obj = obj_class.objects(id=rd['value'], source__name__in=sources).only('id').first() else: obj = obj_class.objects(id=rd['value']).only('id').first() if obj: final_rels.append(r) self.relationships = final_rels def sanitize_releasability(self, username=None, sources=None): """ Sanitize releasability list down to only what the user can see based on source access. :param username: The user to sanitize for. :type username: str :param source: The user's source list. :type source: list """ if username: if not sources: sources = user_sources(username) # use slice to modify in place in case any code is referencing # the source already will reflect the changes as well self.releasability[:] = [r for r in self.releasability if r.name in sources] def sanitize(self, username=None, sources=None, rels=True): """ Sanitize this top-level object down to only what the user can see based on source access. :param username: The user to sanitize for. :type username: str :param source: The user's source list. :type source: list :param rels: Whether or not to sanitize relationships. :type rels: boolean """ if username: if not sources: sources = user_sources(username) if hasattr(self, 'source'): self.sanitize_sources(username, sources) if hasattr(self, 'releasability'): self.sanitize_releasability(username, sources) if rels: if hasattr(self, 'relationships'): self.sanitize_relationships(username, sources) def get_analysis_results(self): """ Get analysis results for this TLO. :returns: list """ from cripts.services.analysis_result import AnalysisResult return AnalysisResult.objects(object_id=str(self.id)) def get_details_url(self): """ Generic function that generates a details url for a :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` object. """ mapper = self._meta.get('jtable_opts') if mapper is not None: details_url = mapper['details_url'] details_url_key = mapper['details_url_key'] try: return reverse(details_url, args=(unicode(self[details_url_key]),)) except Exception: return None else: return None def merge(self, arg_dict=None, overwrite=False, **kwargs): """ Merge attributes into self. If arg_dict is supplied, it should be either a dictionary or another object that can be iterated over like a dictionary's iteritems (e.g., a list of two-tuples). If arg_dict is not supplied, attributes can also be defined with named keyword arguments; attributes supplied as keyword arguments will be ignored if arg_dict is not None. If overwrite is True, any attributes passed to merge will be assigned to the object, regardless of whether those attributes already exist. If overwrite is False, pre-existing attributes will be preserved. """ if not arg_dict: arg_dict = kwargs if isinstance(arg_dict, dict): iterator = arg_dict.iteritems() else: iterator = arg_dict if overwrite: for k,v in iterator: if k != '_id' and k != 'schema_version': self.__setattr__(k, v) else: for k,v in iterator: check = getattr(self, k, None) if not check: self.__setattr__(k, v) elif hasattr(self, '_meta') and 'duplicate_attrs' in self._meta: self._meta['duplicate_attrs'].append((k,v)) # this is a duplicate of the function in data_tools to prevent # circular imports. long term the one in data_tools might go # away as most json conversion will happen using .to_json() # on the object. def json_handler(obj): """ Handles converting datetimes and Mongo ObjectIds to string. Usage: json.dumps(..., default=json_handler) """ if isinstance(obj, datetime.datetime): return datetime.datetime.strftime(obj, settings.PY_DATETIME_FORMAT) elif isinstance(obj, ObjectId): return str(obj) def create_embedded_source(name, source_instance=None, date=None, reference='', method='', analyst=None): """ Create an EmbeddedSource object. If source_instance is provided it will be used, otherwise date, reference, and method will be used. :param name: The name of the source. :type name: str :param source_instance: An instance of this source. :type source_instance: :class:`cripts.core.cripts_mongoengine.EmbeddedSource.SourceInstance` :param date: The date for the source instance. :type date: datetime.datetime :param reference: The reference for this source instance. :type reference: str :param method: The method for this source instance. :type method: str :param analyst: The user creating this embedded source. :type analyst: str :returns: None, :class:`cripts.core.cripts_mongoengine.EmbeddedSource` """ if isinstance(name, basestring): s = EmbeddedSource() s.name = name if isinstance(source_instance, EmbeddedSource.SourceInstance): s.instances = [source_instance] else: if not date: date = datetime.datetime.now() i = EmbeddedSource.SourceInstance() i.date = date i.reference = reference i.method = method i.analyst = analyst s.instances = [i] return s else: return None
37.444396
107
0.578064
57fd108dad45c5413c131685e8c7865ef9f49411
1,673
py
Python
cogs/reaction.py
MySekwel/discord.py-MySQL
89b343f3619150ff1cf7560ddc31efa3d1e58312
[ "Apache-2.0" ]
2
2021-02-06T15:26:23.000Z
2022-01-29T02:18:01.000Z
cogs/reaction.py
MySekwel/Sakila
89b343f3619150ff1cf7560ddc31efa3d1e58312
[ "Apache-2.0" ]
null
null
null
cogs/reaction.py
MySekwel/Sakila
89b343f3619150ff1cf7560ddc31efa3d1e58312
[ "Apache-2.0" ]
1
2021-01-22T04:47:48.000Z
2021-01-22T04:47:48.000Z
from discord.ext import commands from cogs import user from main import Connection from utils import emoji_dictionary as emojii class React(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_raw_reaction_add(self, payload): emoji = payload.emoji channel = self.bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) author_id = message.author.id if payload.user_id in (self.bot.user.id, author_id) or self.bot.user.id == author_id: return if emoji.name == emojii.heart["red"] + emojii.special["variant"]: if user.get_uid(message.author): query = """ UPDATE users SET user_love=user_love+? WHERE uid=? """ Connection.SQL_Cursor.execute(query, (1, user.get_uid(message.author))) Connection.SQL_Handle.commit() if emoji.name == emojii.flower["rosette"] + emojii.special["variant"]: if user.get_uid(message.author): query = """ UPDATE users SET user_reputation=user_reputation+? WHERE uid=? """ Connection.SQL_Cursor.execute(query, (1, user.get_uid(message.author))) Connection.SQL_Handle.commit() async def on_raw_reaction_remove(self, payload): pass def setup(bot): bot.add_cog(React(bot))
32.173077
93
0.541542
27168dd0871f6c29ef4e5788a918e9c251850b54
739
py
Python
layerindex/migrations/0026_incfile.py
ebrent8/clear-linux-dissector-web
45f1f9b5a5753ab8b14ed3c99f1c9e68bb97a47c
[ "MIT" ]
3
2019-05-12T21:11:53.000Z
2019-09-15T18:11:21.000Z
layerindex/migrations/0026_incfile.py
ebrent8/clear-linux-dissector-web
45f1f9b5a5753ab8b14ed3c99f1c9e68bb97a47c
[ "MIT" ]
21
2019-06-26T05:01:01.000Z
2022-03-11T23:47:21.000Z
layerindex/migrations/0026_incfile.py
ebrent8/clear-linux-dissector-web
45f1f9b5a5753ab8b14ed3c99f1c9e68bb97a47c
[ "MIT" ]
8
2019-06-13T08:51:12.000Z
2021-02-17T11:14:46.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.11.12 on 2018-11-05 19:50 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('layerindex', '0025_update_retcode'), ] operations = [ migrations.CreateModel( name='IncFile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('path', models.CharField(max_length=255)), ('layerbranch', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='layerindex.LayerBranch')), ], ), ]
29.56
125
0.625169
5b454a90ce2a73c430d3450f36f2f5392359d4e8
786
py
Python
pythondata_cpu_blackparrot/system_verilog/black-parrot/external/basejump_stl/testing/bsg_cache/regression_v2/test_store_load2.py
litex-hub/pythondata-cpu-blackparrot
ba50883f12d33e1d834640640c84ddc9329bb68a
[ "BSD-3-Clause" ]
3
2021-05-12T21:57:55.000Z
2021-07-29T19:56:04.000Z
pythondata_cpu_blackparrot/system_verilog/black-parrot/external/basejump_stl/testing/bsg_cache/regression_v2/test_store_load2.py
litex-hub/litex-data-cpu-blackparrot
ba50883f12d33e1d834640640c84ddc9329bb68a
[ "BSD-3-Clause" ]
1
2020-05-02T02:41:24.000Z
2020-05-02T02:44:25.000Z
pythondata_cpu_blackparrot/system_verilog/black-parrot/external/basejump_stl/testing/bsg_cache/regression_v2/test_store_load2.py
litex-hub/litex-data-cpu-blackparrot
ba50883f12d33e1d834640640c84ddc9329bb68a
[ "BSD-3-Clause" ]
2
2020-05-01T08:33:19.000Z
2021-07-29T19:56:12.000Z
import sys import random from test_base import * class TestStoreLoad2(TestBase): def get_random_addr(self): tag = random.randint(0,15) index = random.randint(0,1) block_offset = random.randint(0,3) taddr = self.get_addr(tag,index,block_offset) return taddr def generate(self): self.clear_tag() random.seed(0) # increasing random delay for max_interval in range(100): for i in range(1000): self.send_nop(random.randint(0,max_interval)) store_not_load = random.randint(0,1) taddr = self.get_random_addr() if store_not_load: self.send_sw(taddr) else: self.send_lw(taddr) # done self.tg.done() # main() if __name__ == "__main__": t = TestStoreLoad2() t.generate()
20.684211
53
0.643766
cf3d0ee4a711e6e470320d304be9cccf5265130f
18,921
py
Python
lib/coginvasion/hood/DistributedDoor.py
theclashingfritz/Cog-Invasion-Online-Dump
2561abbacb3e2e288e06f3f04b935b5ed589c8f8
[ "Apache-2.0" ]
1
2020-03-12T16:44:10.000Z
2020-03-12T16:44:10.000Z
lib/coginvasion/hood/DistributedDoor.py
theclashingfritz/Cog-Invasion-Online-Dump
2561abbacb3e2e288e06f3f04b935b5ed589c8f8
[ "Apache-2.0" ]
null
null
null
lib/coginvasion/hood/DistributedDoor.py
theclashingfritz/Cog-Invasion-Online-Dump
2561abbacb3e2e288e06f3f04b935b5ed589c8f8
[ "Apache-2.0" ]
null
null
null
# uncompyle6 version 3.2.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] # Embedded file name: lib.coginvasion.hood.DistributedDoor from direct.directnotify.DirectNotifyGlobal import directNotify from direct.distributed import DistributedObject, ClockDelta, DelayDelete from direct.fsm.ClassicFSM import ClassicFSM from direct.fsm.State import State from direct.interval.IntervalGlobal import Parallel, ParallelEndTogether, Sequence from direct.interval.IntervalGlobal import Wait, Func, LerpQuatInterval, SoundInterval from direct.interval.IntervalGlobal import LerpPosInterval from lib.coginvasion.npc.NPCWalker import NPCWalkInterval class DistributedDoor(DistributedObject.DistributedObject): notify = directNotify.newCategory('DistributedDoor') notify.setInfo(True) INT_STANDARD = 0 EXT_STANDARD = 1 INT_HQ = 2 EXT_HQ = 3 EXT_GAGSHOP = 4 def __init__(self, cr): DistributedObject.DistributedObject.__init__(self, cr) self.rightFSM = ClassicFSM('DistributedDoor_right', [ State('off', self.enterOff, self.exitOff), State('closed', self.enterRightDoorClosed, self.exitRightDoorClosed, ['opening']), State('opening', self.enterRightDoorOpening, self.exitRightDoorOpening, ['open']), State('open', self.enterRightDoorOpen, self.exitRightDoorOpen, ['closing']), State('closing', self.enterRightDoorClosing, self.exitRightDoorClosing, ['closed'])], 'off', 'off') self.rightFSM.enterInitialState() self.leftFSM = ClassicFSM('DistributedDoor_left', [ State('off', self.enterOff, self.exitOff), State('closed', self.enterLeftDoorClosed, self.exitLeftDoorClosed, ['opening']), State('opening', self.enterLeftDoorOpening, self.exitLeftDoorOpening, ['open']), State('open', self.enterLeftDoorOpen, self.exitLeftDoorOpen, ['closing']), State('closing', self.enterLeftDoorClosing, self.exitLeftDoorClosing, ['closed'])], 'off', 'off') self.leftFSM.enterInitialState() self.avatarTracks = [] self.leftDoorState = '' self.rightDoorState = '' self.toZone = 0 self.block = 0 self.doorType = 0 self.doorIndex = 0 self.leftTrack = None self.rightTrack = None self.building = None self.doorNode = None self.leftDoor = None self.rightDoor = None self.doorOpenSound = None self.doorShutSound = None self.enterDoorWalkBackNode = None self.enterDoorWalkInNode = None self.exitDoorWalkFromNode = None self.exitDoorWalkToNode = None self.ready = False self.nodeProblemPolled = False self.suitTakingOver = 0 return def setSuitTakingOver(self, flag): self.suitTakingOver = flag def getSuitTakingOver(self): return self.suitTakingOver def setDoorIndex(self, index): self.doorIndex = index def getDoorIndex(self): return self.doorIndex def getLeftDoorOpenH(self): num = 0 if self.getDoorType() == self.INT_STANDARD or self.getDoorType() == self.INT_HQ: num = 70 else: if self.getDoorType() == self.EXT_STANDARD or self.getDoorType() == self.EXT_HQ: num = -110 if self.getDoorIndex() == 1 and not self.doorType == self.EXT_HQ or self.getDoorIndex() == 0 and self.doorType in [self.EXT_HQ, self.EXT_GAGSHOP]: return num - 180 return num def getLeftDoorClosedH(self): num = 0 if self.getDoorType() == self.INT_STANDARD or self.getDoorType() == self.INT_HQ: num = 180 else: if self.getDoorType() == self.EXT_STANDARD or self.getDoorType() == self.EXT_HQ: num = 0 if self.getDoorIndex() == 1 and not self.doorType == self.EXT_HQ or self.getDoorIndex() == 0 and self.doorType in [self.EXT_HQ, self.EXT_GAGSHOP]: return num - 180 return num def getRightDoorOpenH(self): num = 0 if self.getDoorType() == self.INT_STANDARD or self.getDoorType() == self.INT_HQ: num = -70 else: if self.getDoorType() == self.EXT_STANDARD or self.getDoorType() == self.EXT_HQ or self.getDoorType() == self.EXT_GAGSHOP: num = 110 if self.getDoorIndex() == 1 and not self.doorType == self.EXT_HQ or self.getDoorIndex() == 0 and self.doorType in [self.EXT_HQ, self.EXT_GAGSHOP]: return num - 180 return num def getRightDoorClosedH(self): num = 0 if self.getDoorType() == self.INT_STANDARD or self.getDoorType() == self.INT_HQ: num = 180 else: if self.getDoorType() == self.EXT_STANDARD or self.getDoorType() == self.EXT_HQ or self.getDoorType() == self.EXT_GAGSHOP: num = 0 if self.getDoorIndex() == 1 and not self.doorType == self.EXT_HQ or self.getDoorIndex() == 0 and self.doorType in [self.EXT_HQ, self.EXT_GAGSHOP]: return num - 180 return num def enterOff(self, ts=0): pass def exitOff(self): pass def enterRightDoorClosed(self, ts=0): self.rightDoor.setH(self.getRightDoorClosedH()) def exitRightDoorClosed(self): pass def enterRightDoorOpen(self, ts=0): self.rightDoor.setH(self.getRightDoorOpenH()) def exitRightDoorOpen(self): pass def enterRightDoorClosing(self, ts=0): if self.rightTrack: self.rightTrack.finish() self.rightTrack = None self.rightTrack = Sequence(LerpQuatInterval(self.rightDoor, duration=1.0, quat=(self.getRightDoorClosedH(), 0, 0), startHpr=( self.getRightDoorOpenH(), 0, 0), blendType='easeIn'), Func(self.toggleDoorHole, 'right'), Func(base.playSfx, self.doorShutSound, 0, 1, None, 0.0, self.rightDoor)) self.rightTrack.start() return def exitRightDoorClosing(self): if self.rightTrack: self.rightTrack.finish() self.rightTrack = None return def enterRightDoorOpening(self, ts=0): if self.rightTrack: self.rightTrack.finish() self.rightTrack = None self.rightTrack = Sequence(Wait(0.5), Parallel(Func(self.toggleDoorHole, 'right', True), LerpQuatInterval(self.rightDoor, duration=0.7, quat=(self.getRightDoorOpenH(), 0, 0), startHpr=( self.getRightDoorClosedH(), 0, 0), blendType='easeInOut'), SoundInterval(self.doorOpenSound, node=self.rightDoor))) self.rightTrack.start() return def exitRightDoorOpening(self): if self.rightTrack: self.rightTrack.finish() self.rightTrack = None return def enterLeftDoorClosed(self, ts=0): self.leftDoor.setH(self.getLeftDoorClosedH()) def exitLeftDoorClosed(self): pass def enterLeftDoorOpen(self, ts=0): self.leftDoor.setH(self.getLeftDoorOpenH()) def exitLeftDoorOpen(self): pass def enterLeftDoorClosing(self, ts=0): if self.leftTrack: self.leftTrack.finish() self.leftTrack = None self.leftTrack = Sequence(LerpQuatInterval(self.leftDoor, duration=1.0, quat=(self.getLeftDoorClosedH(), 0, 0), startHpr=( self.getLeftDoorOpenH(), 0, 0), blendType='easeIn'), Func(self.toggleDoorHole, 'left'), Func(base.playSfx, self.doorShutSound, 0, 1, None, 0.0, self.leftDoor)) self.leftTrack.start() return def exitLeftDoorClosing(self): if self.leftTrack: self.leftTrack.finish() self.leftTrack = None return def enterLeftDoorOpening(self, ts=0): if self.leftTrack: self.leftTrack.finish() self.leftTrack = None self.leftTrack = Sequence(Wait(0.5), Parallel(Func(self.toggleDoorHole, 'left', True), LerpQuatInterval(self.leftDoor, duration=0.7, quat=(self.getLeftDoorOpenH(), 0, 0), startHpr=( self.getLeftDoorClosedH(), 0, 0), blendType='easeInOut'), SoundInterval(self.doorOpenSound, node=self.leftDoor))) self.leftTrack.start() return def exitLeftDoorOpening(self): if self.leftTrack: self.leftTrack.finish() self.leftTrack = None return def setDoorType(self, door): self.doorType = door def getDoorType(self): return self.doorType def setBlock(self, block): self.block = block def getBlock(self): return self.block def setToZone(self, zone): self.toZone = zone def getToZone(self): return self.toZone def setLeftDoorState(self, state, timestamp): ts = ClockDelta.globalClockDelta.localElapsedTime(timestamp) self.leftDoorState = state if self.building: self.leftFSM.request(state, [ts]) def getLeftDoorState(self): return self.leftDoorState def setRightDoorState(self, state, timestamp): ts = ClockDelta.globalClockDelta.localElapsedTime(timestamp) self.rightDoorState = state if self.building: self.rightFSM.request(state, [ts]) def getRightDoorState(self): return self.rightDoorState def findBuilding(self): bldg = None if self.getDoorType() == self.EXT_STANDARD or self.getDoorType() == self.EXT_HQ or self.getDoorType() == self.EXT_GAGSHOP: bldg = self.cr.playGame.hood.loader.geom.find('**/??' + str(self.getBlock()) + ':*_landmark_*_DNARoot;+s') else: if self.getDoorType() == self.INT_STANDARD: bldg = render.find('**/leftDoor;+s').getParent() else: if self.getDoorType() == self.INT_HQ: bldg = render.find('**/door_origin_0').getParent() return bldg def findDoorNodePath(self): doorNode = None if self.getDoorType() in [self.EXT_STANDARD, self.EXT_GAGSHOP]: doorNode = self.building.find('**/*door_origin') else: if self.getDoorType() == self.EXT_HQ: doorNode = self.building.find('**/door_origin_' + str(self.doorIndex)) else: if self.getDoorType() == self.INT_STANDARD: doorNode = render.find('**/door_origin') else: if self.getDoorType() == self.INT_HQ: doorNode = render.find('**/door_origin_' + str(self.doorIndex)) return doorNode def findDoorNode(self, string): if self.doorType != self.INT_HQ: foundNode = self.building.find('**/door_' + str(self.getDoorIndex()) + '/**/' + string + '*;+s+i') if foundNode.isEmpty(): foundNode = self.building.find('**/' + string + '*;+s+i') else: foundNode = render.find('**/door_' + str(self.getDoorIndex()) + '/**/' + string + '*;+s+i') if foundNode.isEmpty(): foundNode = render.find('**/' + string + '*;+s+i') return foundNode def getTriggerName(self): if self.getDoorType() == self.INT_STANDARD or self.getDoorType() == self.EXT_STANDARD or self.getDoorType() == self.EXT_GAGSHOP: return 'door_trigger_' + str(self.getBlock()) if self.getDoorType() == self.EXT_HQ: return 'door_trigger_' + str(self.doorIndex) if self.getDoorType() == self.INT_HQ: return 'door_trigger_' + str(self.block) + '_' + str(self.doorIndex) def getEnterTriggerEvent(self): return 'enter' + self.getTriggerName() def getExitTriggerEvent(self): return 'exit' + self.getTriggerName() def __pollBuilding(self, task): try: self.building = self.findBuilding() except: return task.cont if self.building.isEmpty(): return task.cont self.generated() return task.done def _handleTrigger(self, entry): if not self.getSuitTakingOver(): self.cr.playGame.getPlace().fsm.request('stop') base.localAvatar.walkControls.setCollisionsActive(0) self.sendUpdate('requestEnter', []) def getAvatarEnterTrack(self, av): track = Sequence(name=av.uniqueName('avatarEnterDoorTrack')) track.append(Func(av.setAnimState, 'walkBack')) track.append(ParallelEndTogether(LerpPosInterval(av, duration=0.5, pos=self.enterDoorWalkBackNode.getPos(render), startPos=av.getPos(render)), LerpQuatInterval(av, duration=0.5, quat=self.enterDoorWalkInNode.getHpr(render), startHpr=av.getHpr(render)))) track.append(Func(av.setPlayRate, 1.0, 'walk')) track.append(Func(av.loop, 'neutral')) track.append(Wait(1.0)) track.append(Func(av.loop, 'walk')) parallel = Parallel() parallel.append(LerpPosInterval(av, duration=1.0, pos=self.enterDoorWalkInNode.getPos(render), startPos=self.enterDoorWalkBackNode.getPos(render))) if base.localAvatar.doId == av.doId: parallel.append(Sequence(Wait(0.5), Func(messenger.send, 'DistributedDoor_localAvatarGoingInDoor'), Wait(1.0))) track.append(parallel) if base.localAvatar.doId == av.doId: track.append(Func(messenger.send, 'DistributedDoor_localAvatarWentInDoor')) track.setDoneEvent(track.getName()) track.delayDelete = DelayDelete.DelayDelete(av, track.getName()) self.acceptOnce(track.getDoneEvent(), self.__avatarTrackDone, [track]) return track def getAvatarExitTrack(self, av): track = Sequence(name=av.uniqueName('avatarExitDoorTrack')) track.append(Wait(1.3)) track.append(Func(av.setAnimState, 'walk')) av.setPos(self.exitDoorWalkFromNode.getPos(render)) av.headsUp(self.exitDoorWalkToNode) track.append(LerpPosInterval(av, duration=1.2, pos=self.exitDoorWalkToNode.getPos(render), startPos=av.getPos(render))) track.append(Func(av.loop, 'neutral')) if base.localAvatar.doId == av.doId: track.append(Func(messenger.send, 'DistributedDoor_localAvatarCameOutOfDoor')) else: track.append(Func(av.startSmooth)) track.setDoneEvent(track.getName()) track.delayDelete = DelayDelete.DelayDelete(av, track.getName()) self.acceptOnce(track.getDoneEvent(), self.__avatarTrackDone, [track]) return track def __avatarTrackDone(self, track): if track: DelayDelete.cleanupDelayDeletes(track) if self.avatarTracks: self.avatarTracks.remove(track) def enterDoor(self, avatarId, timestamp): if not self.building: return ts = ClockDelta.globalClockDelta.localElapsedTime(timestamp) if avatarId == base.localAvatar.doId: self.cr.playGame.getPlace().fsm.request('doorIn', [self]) av = self.cr.doId2do.get(avatarId) if av: av.stopSmooth() track = self.getAvatarEnterTrack(av) self.avatarTracks.append(track) track.start() def exitDoor(self, avatarId, timestamp): if not self.building: return ts = ClockDelta.globalClockDelta.localElapsedTime(timestamp) av = self.cr.doId2do.get(avatarId) if av: if av.doId != base.localAvatar.doId: av.stopSmooth() track = self.getAvatarExitTrack(av) self.avatarTracks.append(track) track.start() def announceGenerate(self): DistributedObject.DistributedObject.announceGenerate(self) try: self.building = self.findBuilding() except: self.startBuildingPoll() return if self.building.isEmpty(): self.startBuildingPoll() return self.generated() def startBuildingPoll(self): base.taskMgr.add(self.__pollBuilding, self.uniqueName('pollBuilding')) def generated(self): self.doorNode = self.findDoorNodePath() self.rightDoor = self.findDoorNode('rightDoor') self.leftDoor = self.findDoorNode('leftDoor') self.enterDoorWalkBackNode = self.doorNode.attachNewNode(self.uniqueName('enterWalkBackNode')) self.enterDoorWalkBackNode.setPos(1.6, -5.5, 0.0) self.enterDoorWalkInNode = self.doorNode.attachNewNode(self.uniqueName('enterWalkInNode')) self.enterDoorWalkInNode.setPos(1.6, 3.0, 0.0) self.exitDoorWalkFromNode = self.doorNode.attachNewNode(self.uniqueName('exitWalkFromNode')) self.exitDoorWalkFromNode.setPos(-1.6, 3.0, 0.0) self.exitDoorWalkToNode = self.doorNode.attachNewNode(self.uniqueName('exitWalkToNode')) self.exitDoorWalkToNode.setPos(-1.6, -5.5, 0.0) self.doorOpenSound = base.audio3d.loadSfx('phase_3.5/audio/sfx/Door_Open_1.ogg') self.doorShutSound = base.audio3d.loadSfx('phase_3.5/audio/sfx/Door_Close_1.ogg') base.audio3d.attachSoundToObject(self.doorOpenSound, self.doorNode) base.audio3d.attachSoundToObject(self.doorShutSound, self.doorNode) self.acceptOnce(self.getEnterTriggerEvent(), self._handleTrigger) self.ready = True self.toggleDoorHole('Left') self.toggleDoorHole('Right') def toggleDoorHole(self, side, show=False): side = side.title() if self.building: hole = self.building.find('**/doorFrameHole%s' % side) if hole and not hole.isEmpty(): if not show: hole.hide() else: hole.show() def printBuildingPos(self): self.notify.info(self.building.getPos(render)) def disable(self): self.ignore('p') self.ignore(self.getEnterTriggerEvent()) base.taskMgr.remove(self.uniqueName('pollBuilding')) for track in self.avatarTracks: track.finish() self.avatarTracks = None self.building = None self.doorNode = None self.rightDoor = None self.leftDoor = None self.ready = None if self.enterDoorWalkBackNode: self.enterDoorWalkBackNode.removeNode() self.enterDoorWalkBackNode = None if self.enterDoorWalkInNode: self.enterDoorWalkInNode.removeNode() self.enterDoorWalkInNode = None if self.exitDoorWalkFromNode: self.exitDoorWalkFromNode.removeNode() self.exitDoorWalkFromNode = None if self.exitDoorWalkToNode: self.exitDoorWalkToNode.removeNode() self.exitDoorWalkToNode = None self.doorOpenSound = None self.doorShutSound = None DistributedObject.DistributedObject.disable(self) return
41.132609
261
0.635537
98170e6c9ed6645d6a491d68a78b820c2c6e9e05
764
py
Python
unitpy/units/time.py
jenders97/unitpy
a39fefe1c109b57c174eeba53b877f32f044de0f
[ "MIT" ]
null
null
null
unitpy/units/time.py
jenders97/unitpy
a39fefe1c109b57c174eeba53b877f32f044de0f
[ "MIT" ]
null
null
null
unitpy/units/time.py
jenders97/unitpy
a39fefe1c109b57c174eeba53b877f32f044de0f
[ "MIT" ]
null
null
null
from measurement.base import MeasureBase __all__ = [ 'Time', ] class Time(MeasureBase): """ Time measurements (generally for multidimensional measures). Please do not use this for handling durations of time unrelated to measure classes -- python's built-in datetime module has much better functionality for handling intervals of time than this class provides. """ STANDARD_UNIT = 's' UNITS = { 's': 1.0, 'min': 60.0, 'hr': 3600.0, 'day': 86400.0 } ALIAS = { 'second': 's', 'sec': 's', # For backward compatibility 'minute': 'min', 'm': 'min', 'hour': 'hr', 'h': 'hr', 'day': 'day', 'd': 'day' } SI_UNITS = ['s']
21.222222
74
0.541885
3b194ef87a1e59efa1782c14ca9a86e69b5e6366
102,213
py
Python
tensorflow/python/keras/engine/base_layer.py
dan-zheng/tensorflow
b4245c36bc9bcb752c0a2118728098b359fd97e2
[ "Apache-2.0" ]
2
2019-08-04T20:28:14.000Z
2019-10-27T23:26:42.000Z
tensorflow/python/keras/engine/base_layer.py
dan-zheng/tensorflow
b4245c36bc9bcb752c0a2118728098b359fd97e2
[ "Apache-2.0" ]
1
2019-08-19T08:03:52.000Z
2019-08-19T08:03:52.000Z
tensorflow/python/keras/engine/base_layer.py
dan-zheng/tensorflow
b4245c36bc9bcb752c0a2118728098b359fd97e2
[ "Apache-2.0" ]
1
2019-08-19T06:53:43.000Z
2019-08-19T06:53:43.000Z
# Copyright 2015 The TensorFlow Authors. 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. # ============================================================================== # pylint: disable=protected-access """Contains the base Layer class, from which all layers inherit.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import itertools import json import threading import numpy as np from six.moves import zip # pylint: disable=redefined-builtin from tensorflow.core.framework import node_def_pb2 from tensorflow.python.autograph.core import ag_ctx from tensorflow.python.autograph.impl import api as autograph from tensorflow.python.distribute import distribution_strategy_context as ds_context from tensorflow.python.distribute import values as distribute_values from tensorflow.python.eager import context from tensorflow.python.eager import execute from tensorflow.python.eager import function from tensorflow.python.framework import auto_control_deps from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import func_graph from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_spec from tensorflow.python.framework import tensor_util from tensorflow.python.keras import backend from tensorflow.python.keras import constraints from tensorflow.python.keras import initializers from tensorflow.python.keras import regularizers from tensorflow.python.keras.engine import base_layer_utils from tensorflow.python.keras.engine import input_spec from tensorflow.python.keras.engine import node as node_module from tensorflow.python.keras.mixed_precision.experimental import autocast_variable from tensorflow.python.keras.mixed_precision.experimental import policy from tensorflow.python.keras.saving.saved_model import save as saved_model from tensorflow.python.keras.utils import generic_utils from tensorflow.python.keras.utils import tf_utils # A module that only depends on `keras.layers` import these from here. from tensorflow.python.keras.utils.generic_utils import serialize_keras_object from tensorflow.python.keras.utils.generic_utils import to_snake_case # pylint: disable=unused-import from tensorflow.python.keras.utils.tf_utils import is_tensor_or_tensor_list # pylint: disable=unused-import from tensorflow.python.module import module from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variables as tf_variables from tensorflow.python.platform import tf_logging from tensorflow.python.training.tracking import base as trackable from tensorflow.python.training.tracking import data_structures from tensorflow.python.training.tracking import layer_utils as trackable_layer_utils from tensorflow.python.training.tracking import tracking from tensorflow.python.util import compat from tensorflow.python.util import deprecation from tensorflow.python.util import nest from tensorflow.python.util import object_identity from tensorflow.python.util import serialization from tensorflow.python.util import tf_inspect from tensorflow.python.util.tf_export import keras_export from tensorflow.tools.docs import doc_controls # Prefix that is added to the TF op layer names. _TF_OP_LAYER_NAME_PREFIX = 'tf_op_layer_' @keras_export('keras.layers.Layer') class Layer(module.Module): """Base layer class. This is the class from which all layers inherit. A layer is a class implementing common neural networks operations, such as convolution, batch norm, etc. These operations require managing weights, losses, updates, and inter-layer connectivity. Users will just instantiate a layer and then treat it as a callable. We recommend that descendants of `Layer` implement the following methods: * `__init__()`: Save configuration in member variables * `build()`: Called once from `__call__`, when we know the shapes of inputs and `dtype`. Should have the calls to `add_weight()`, and then call the super's `build()` (which sets `self.built = True`, which is nice in case the user wants to call `build()` manually before the first `__call__`). * `call()`: Called in `__call__` after making sure `build()` has been called once. Should actually perform the logic of applying the layer to the input tensors (which should be passed in as the first argument). Arguments: trainable: Boolean, whether the layer's variables should be trainable. name: String name of the layer. dtype: The dtype of the layer's computations and weights (default of `None` means use the type of the first input). dynamic: Set this to `True` if your layer should only be run eagerly, and should not be used to generate a static computation graph. This would be the case for a Tree-RNN or a recursive network, for example, or generally for any layer that manipulates tensors using Python control flow. If `False`, we assume that the layer can safely be used to generate a static computation graph. Read-only properties: name: The name of the layer (string). dtype: The dtype of the layer's computations and weights. If mixed precision is used with a `tf.keras.mixed_precision.experimental.Policy`, this is instead just the dtype of the layer's weights, as the computations are done in a different dtype. updates: List of update ops of this layer. losses: List of losses added by this layer. trainable_weights: List of variables to be included in backprop. non_trainable_weights: List of variables that should not be included in backprop. weights: The concatenation of the lists trainable_weights and non_trainable_weights (in this order). Mutable properties: trainable: Whether the layer should be trained (boolean). input_spec: Optional (list of) `InputSpec` object(s) specifying the constraints on inputs that can be accepted by the layer. """ # See tf.Module for the usage of this property. # The key for _obj_reference_counts_dict is a Trackable, which could be a # variable or layer etc. tf.Module._flatten will fail to flatten the key # since it is trying to convert Trackable to a string. This attribute can be # ignored even after the fix of nest lib, since the trackable object should # already been available as individual attributes. _obj_reference_counts_dict # just contains a copy of them. _TF_MODULE_IGNORED_PROPERTIES = frozenset(itertools.chain( ('_obj_reference_counts_dict',), module.Module._TF_MODULE_IGNORED_PROPERTIES )) @trackable.no_automatic_dependency_tracking def __init__(self, trainable=True, name=None, dtype=None, dynamic=False, **kwargs): # These properties should be set by the user via keyword arguments. # note that 'dtype', 'input_shape' and 'batch_input_shape' # are only applicable to input layers: do not pass these keywords # to non-input layers. allowed_kwargs = { 'input_shape', 'batch_input_shape', 'batch_size', 'weights', 'activity_regularizer', 'experimental_autocast' } # Validate optional keyword arguments. generic_utils.validate_kwargs(kwargs, allowed_kwargs) # Mutable properties # Indicates whether the layer's weights are updated during training # and whether the layer's updates are run during training. self._trainable = trainable # A stateful layer is a layer whose updates are run during inference too, # for instance stateful RNNs. self.stateful = False # Indicates whether `build` needs to be called upon layer call, to create # the layer's weights. self.built = False # Provides information about which inputs are compatible with the layer. self.input_spec = None self.supports_masking = False self._init_set_name(name) self._activity_regularizer = kwargs.pop('activity_regularizer', None) self._maybe_create_attribute('_trainable_weights', []) self._maybe_create_attribute('_non_trainable_weights', []) self._updates = [] # Object to store all thread local layer properties. self._thread_local = threading.local() # A list of zero-argument lambdas which return Tensors, used for variable # regularizers. self._callable_losses = [] # A list of symbolic Tensors containing activity regularizers and losses # manually added through `add_loss` in graph-building mode. self._losses = [] # A list of metric instances corresponding to the symbolic metric tensors # added using the `add_metric` API. self._metrics = [] self._set_dtype_policy(dtype) # Boolean indicating whether the layer automatically casts its inputs to the # layer's compute_dtype. self._autocast = kwargs.get('experimental_autocast', base_layer_utils.v2_dtype_behavior_enabled()) # Dependencies tracked via attribute assignment. self._maybe_create_attribute('_layers', []) # These lists will be filled via successive calls # to self._add_inbound_node(). self._inbound_nodes = [] self._outbound_nodes = [] self._init_call_fn_args() # Whether the `call` method can be used to build a TF graph without issues. self._dynamic = dynamic # Manage input shape information if passed. if 'input_shape' in kwargs or 'batch_input_shape' in kwargs: # In this case we will later create an input layer # to insert before the current layer if 'batch_input_shape' in kwargs: batch_input_shape = tuple(kwargs['batch_input_shape']) elif 'input_shape' in kwargs: if 'batch_size' in kwargs: batch_size = kwargs['batch_size'] else: batch_size = None batch_input_shape = (batch_size,) + tuple(kwargs['input_shape']) self._batch_input_shape = batch_input_shape # Manage initial weight values if passed. if 'weights' in kwargs: self._initial_weights = kwargs['weights'] else: self._initial_weights = None def build(self, input_shape): """Creates the variables of the layer (optional, for subclass implementers). This is a method that implementers of subclasses of `Layer` or `Model` can override if they need a state-creation step in-between layer instantiation and layer call. This is typically used to create the weights of `Layer` subclasses. Arguments: input_shape: Instance of `TensorShape`, or list of instances of `TensorShape` if the layer expects a list of inputs (one instance per input). """ self.built = True @doc_controls.for_subclass_implementers def call(self, inputs, **kwargs): # pylint: disable=unused-argument """This is where the layer's logic lives. Arguments: inputs: Input tensor, or list/tuple of input tensors. **kwargs: Additional keyword arguments. Returns: A tensor or list/tuple of tensors. """ return inputs @doc_controls.for_subclass_implementers def add_weight(self, name=None, shape=None, dtype=None, initializer=None, regularizer=None, trainable=None, constraint=None, partitioner=None, use_resource=None, synchronization=tf_variables.VariableSynchronization.AUTO, aggregation=tf_variables.VariableAggregation.NONE, **kwargs): """Adds a new variable to the layer. Arguments: name: Variable name. shape: Variable shape. Defaults to scalar if unspecified. dtype: The type of the variable. Defaults to `self.dtype` or `float32`. initializer: Initializer instance (callable). regularizer: Regularizer instance (callable). trainable: Boolean, whether the variable should be part of the layer's "trainable_variables" (e.g. variables, biases) or "non_trainable_variables" (e.g. BatchNorm mean and variance). Note that `trainable` cannot be `True` if `synchronization` is set to `ON_READ`. constraint: Constraint instance (callable). partitioner: Partitioner to be passed to the `Trackable` API. use_resource: Whether to use `ResourceVariable`. synchronization: Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class `tf.VariableSynchronization`. By default the synchronization is set to `AUTO` and the current `DistributionStrategy` chooses when to synchronize. If `synchronization` is set to `ON_READ`, `trainable` must not be set to `True`. aggregation: Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class `tf.VariableAggregation`. **kwargs: Additional keyword arguments. Accepted values are `getter` and `collections`. Returns: The created variable. Usually either a `Variable` or `ResourceVariable` instance. If `partitioner` is not `None`, a `PartitionedVariable` instance is returned. Raises: RuntimeError: If called with partitioned variable regularization and eager execution is enabled. ValueError: When giving unsupported dtype and no initializer or when trainable has been set to True with synchronization set as `ON_READ`. """ if shape is None: shape = () # Validate optional keyword arguments. for kwarg in kwargs: if kwarg not in ['getter', 'collections', 'experimental_autocast']: raise TypeError('Unknown keyword argument:', kwarg) getter = kwargs.pop('getter', base_layer_utils.make_variable) collections_arg = kwargs.pop('collections', None) # 'experimental_autocast' can be set to False by the caller to indicate an # AutoCastVariable should never be created. autocast = kwargs.pop('experimental_autocast', True) if dtype is None: dtype = self.dtype or backend.floatx() dtype = dtypes.as_dtype(dtype) if self._dtype_policy.variable_dtype is None: # The policy is "infer", so we infer the policy from the variable dtype. self._dtype_policy = policy.Policy(dtype.base_dtype.name) initializer = initializers.get(initializer) regularizer = regularizers.get(regularizer) constraint = constraints.get(constraint) if synchronization == tf_variables.VariableSynchronization.ON_READ: if trainable: raise ValueError( 'Synchronization value can be set to ' 'VariableSynchronization.ON_READ only for non-trainable variables. ' 'You have specified trainable=True and ' 'synchronization=VariableSynchronization.ON_READ.') else: # Set trainable to be false when variable is to be synced on read. trainable = False elif trainable is None: trainable = True # Initialize variable when no initializer provided if initializer is None: # If dtype is DT_FLOAT, provide a uniform unit scaling initializer if dtype.is_floating: initializer = initializers.glorot_uniform() # If dtype is DT_INT/DT_UINT, provide a default value `zero` # If dtype is DT_BOOL, provide a default value `FALSE` elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool: initializer = initializers.zeros() # NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here? else: raise ValueError('An initializer for variable %s of type %s is required' ' for layer %s' % (name, dtype.base_dtype, self.name)) if autocast and self._dtype_policy.should_cast_variables: # Wrap 'getter' with a version that returns an AutoCastVariable. old_getter = getter def getter(*args, **kwargs): # pylint: disable=function-redefined variable = old_getter(*args, **kwargs) if isinstance(variable, distribute_values.DistributedVariable): return autocast_variable.AutoCastDistributedVariable(variable) else: return autocast_variable.AutoCastVariable(variable) variable = self._add_variable_with_custom_getter( name=name, shape=shape, # TODO(allenl): a `make_variable` equivalent should be added as a # `Trackable` method. getter=getter, # Manage errors in Layer rather than Trackable. overwrite=True, initializer=initializer, dtype=dtype, constraint=constraint, trainable=trainable, partitioner=partitioner, use_resource=use_resource, collections=collections_arg, synchronization=synchronization, aggregation=aggregation) backend.track_variable(variable) if regularizer is not None: # TODO(fchollet): in the future, this should be handled at the # level of variable creation, and weight regularization losses # should be variable attributes. name_in_scope = variable.name[:variable.name.find(':')] self._handle_weight_regularization(name_in_scope, variable, regularizer) if trainable: self._trainable_weights.append(variable) else: self._non_trainable_weights.append(variable) return variable @base_layer_utils.default def get_config(self): """Returns the config of the layer. A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration. The config of a layer does not include connectivity information, nor the layer class name. These are handled by `Network` (one layer of abstraction above). Returns: Python dictionary. """ all_args = tf_inspect.getfullargspec(self.__init__).args config = {'name': self.name, 'trainable': self.trainable} if hasattr(self, '_batch_input_shape'): config['batch_input_shape'] = self._batch_input_shape if hasattr(self, 'dtype'): config['dtype'] = self.dtype if hasattr(self, 'dynamic'): # Only include `dynamic` in the `config` if it is `True` if self.dynamic: config['dynamic'] = self.dynamic elif 'dynamic' in all_args: all_args.remove('dynamic') expected_args = config.keys() # Finds all arguments in the `__init__` that are not in the config: extra_args = [arg for arg in all_args if arg not in expected_args] # Check that either the only argument in the `__init__` is `self`, # or that `get_config` has been overridden: if len(extra_args) > 1 and hasattr(self.get_config, '_is_default'): raise NotImplementedError('Layers with arguments in `__init__` must ' 'override `get_config`.') # TODO(reedwm): Handle serializing self._dtype_policy. return config @classmethod def from_config(cls, config): """Creates a layer from its config. This method is the reverse of `get_config`, capable of instantiating the same layer from the config dictionary. It does not handle layer connectivity (handled by Network), nor weights (handled by `set_weights`). Arguments: config: A Python dictionary, typically the output of get_config. Returns: A layer instance. """ return cls(**config) def compute_output_shape(self, input_shape): """Computes the output shape of the layer. If the layer has not been built, this method will call `build` on the layer. This assumes that the layer will later be used with inputs that match the input shape provided here. Arguments: input_shape: Shape tuple (tuple of integers) or list of shape tuples (one per output tensor of the layer). Shape tuples can include None for free dimensions, instead of an integer. Returns: An input shape tuple. """ if context.executing_eagerly(): # In this case we build the model first in order to do shape inference. # This is acceptable because the framework only calls # `compute_output_shape` on shape values that the layer would later be # built for. It would however cause issues in case a user attempts to # use `compute_output_shape` manually with shapes that are incompatible # with the shape the Layer will be called on (these users will have to # implement `compute_output_shape` themselves). self._maybe_build(input_shape) with context.graph_mode(): graph = func_graph.FuncGraph('graph') with graph.as_default(): input_shape = tf_utils.convert_shapes(input_shape, to_tuples=False) inputs = nest.map_structure( base_layer_utils.generate_placeholders_from_shape, input_shape) try: if self._expects_training_arg: outputs = self(inputs, training=False) else: outputs = self(inputs) except TypeError: raise NotImplementedError('We could not automatically infer ' 'the static shape of the layer\'s output.' ' Please implement the ' '`compute_output_shape` method on your ' 'layer (%s).' % self.__class__.__name__) return nest.map_structure(lambda t: t.shape, outputs) raise NotImplementedError @doc_controls.for_subclass_implementers def compute_output_signature(self, input_signature): """Compute the output tensor signature of the layer based on the inputs. Unlike a TensorShape object, a TensorSpec object contains both shape and dtype information for a tensor. This method allows layers to provide output dtype information if it is different from the input dtype. For any layer that doesn't implement this function, the framework will fall back to use `compute_output_shape`, and will assume that the output dtype matches the input dtype. Args: input_signature: Single TensorSpec or nested structure of TensorSpec objects, describing a candidate input for the layer. Returns: Single TensorSpec or nested structure of TensorSpec objects, describing how the layer would transform the provided input. Raises: TypeError: If input_signature contains a non-TensorSpec object. """ def check_type_return_shape(s): if not isinstance(s, tensor_spec.TensorSpec): raise TypeError( 'Only TensorSpec signature types are supported, ' 'but saw signature signature entry: {}.'.format(s)) return s.shape input_shape = nest.map_structure(check_type_return_shape, input_signature) output_shape = self.compute_output_shape(input_shape) dtype = self._compute_dtype if dtype is None: input_dtypes = [s.dtype for s in nest.flatten(input_signature)] # Default behavior when self.dtype is None, is to use the first input's # dtype. dtype = input_dtypes[0] return nest.map_structure( lambda s: tensor_spec.TensorSpec(dtype=dtype, shape=s), output_shape) @base_layer_utils.default def compute_mask(self, inputs, mask=None): # pylint: disable=unused-argument """Computes an output mask tensor. Arguments: inputs: Tensor or list of tensors. mask: Tensor or list of tensors. Returns: None or a tensor (or list of tensors, one per output tensor of the layer). """ if not self.supports_masking: if any(m is not None for m in nest.flatten(mask)): raise TypeError('Layer ' + self.name + ' does not support masking, ' 'but was passed an input_mask: ' + str(mask)) # masking not explicitly supported: return None as mask. return None # if masking is explicitly supported, by default # carry over the input mask return mask def __call__(self, inputs, *args, **kwargs): """Wraps `call`, applying pre- and post-processing steps. Arguments: inputs: input tensor(s). *args: additional positional arguments to be passed to `self.call`. **kwargs: additional keyword arguments to be passed to `self.call`. Returns: Output tensor(s). Note: - The following optional keyword arguments are reserved for specific uses: * `training`: Boolean scalar tensor of Python boolean indicating whether the `call` is meant for training or inference. * `mask`: Boolean input mask. - If the layer's `call` method takes a `mask` argument (as some Keras layers do), its default value will be set to the mask generated for `inputs` by the previous layer (if `input` did come from a layer that generated a corresponding mask, i.e. if it came from a Keras layer with masking support. Raises: ValueError: if the layer's `call` method returns None (an invalid value). """ call_context = base_layer_utils.call_context() input_list = nest.flatten(inputs) # We will attempt to build a TF graph if & only if all inputs are symbolic. # This is always the case in graph mode. It can also be the case in eager # mode when all inputs can be traced back to `keras.Input()` (when building # models using the functional API). build_graph = tf_utils.are_all_symbolic_tensors(input_list) # Accept NumPy and scalar inputs by converting to Tensors. if any(isinstance(x, (np.ndarray, float, int)) for x in input_list): def _convert_non_tensor(x): # Don't call `ops.convert_to_tensor` on all `inputs` because # `SparseTensors` can't be converted to `Tensor`. if isinstance(x, (np.ndarray, float, int)): return ops.convert_to_tensor(x) return x inputs = nest.map_structure(_convert_non_tensor, inputs) input_list = nest.flatten(inputs) # Handle `mask` propagation from previous layer to current layer. Masks can # be propagated explicitly via the `mask` argument, or implicitly via # setting the `_keras_mask` attribute on the inputs to a Layer. Masks passed # explicitly take priority. mask_arg_passed_by_framework = False input_masks = self._collect_input_masks(inputs, args, kwargs) if (self._expects_mask_arg and input_masks is not None and not self._call_arg_was_passed('mask', args, kwargs)): mask_arg_passed_by_framework = True kwargs['mask'] = input_masks # If `training` argument was not explicitly passed, propagate `training` # value from this layer's calling layer. training_arg_passed_by_framework = False # Priority 1: `training` was explicitly passed. if self._call_arg_was_passed('training', args, kwargs): training_value = self._get_call_arg_value('training', args, kwargs) if not self._expects_training_arg: kwargs.pop('training') else: training_value = None # Priority 2: `training` was passed to a parent layer. if call_context.training is not None: training_value = call_context.training # Priority 3a: `learning_phase()` has been set. elif backend.global_learning_phase_is_set(): training_value = backend.learning_phase() # Priority 3b: Pass the `learning_phase()` if in the Keras FuncGraph. elif build_graph: with backend.get_graph().as_default(): if base_layer_utils.is_in_keras_graph(): training_value = backend.learning_phase() if self._expects_training_arg and training_value is not None: kwargs['training'] = training_value training_arg_passed_by_framework = True # Only create Keras history if at least one tensor originates from a # `keras.Input`. Otherwise this Layer may be being used outside the Keras # framework. if build_graph and base_layer_utils.needs_keras_history(inputs): base_layer_utils.create_keras_history(inputs) # Clear eager losses on top level model call. # We are clearing the losses only on the top level model call and not on # every layer/model call because layer/model may be reused. if (base_layer_utils.is_in_eager_or_tf_function() and not call_context.in_call): self._clear_losses() with call_context.enter(self, inputs, build_graph, training_value): # Check input assumptions set after layer building, e.g. input shape. if build_graph: # Symbolic execution on symbolic tensors. We will attempt to build # the corresponding TF subgraph inside `backend.get_graph()` # TODO(reedwm): We should assert input compatibility after the inputs # are casted, not before. input_spec.assert_input_compatibility(self.input_spec, inputs, self.name) graph = backend.get_graph() with graph.as_default(), backend.name_scope(self._name_scope()): # Build layer if applicable (if the `build` method has been # overridden). self._maybe_build(inputs) cast_inputs = self._maybe_cast_inputs(inputs) # Wrapping `call` function in autograph to allow for dynamic control # flow and control dependencies in call. We are limiting this to # subclassed layers as autograph is strictly needed only for # subclassed layers and models. # tf_convert will respect the value of autograph setting in the # enclosing tf.function, if any. if (base_layer_utils.is_subclassed(self) and not base_layer_utils.from_saved_model(self)): call_fn = autograph.tf_convert( self.call, ag_ctx.control_status_ctx()) else: call_fn = self.call if not self.dynamic: try: with base_layer_utils.autocast_context_manager( self._compute_dtype): # Add auto_control_deps in V2 when they are not already added by # a `tf.function`. if (ops.executing_eagerly_outside_functions() and not base_layer_utils.is_in_eager_or_tf_function()): with auto_control_deps.AutomaticControlDependencies() as acd: outputs = call_fn(cast_inputs, *args, **kwargs) # Wrap Tensors in `outputs` in `tf.identity` to avoid # circular dependencies. outputs = base_layer_utils.mark_as_return(outputs, acd) else: outputs = call_fn(cast_inputs, *args, **kwargs) except errors.OperatorNotAllowedInGraphError as e: raise TypeError('You are attempting to use Python control ' 'flow in a layer that was not declared to be ' 'dynamic. Pass `dynamic=True` to the class ' 'constructor.\nEncountered error:\n"""\n' + str(e) + '\n"""') else: # We will use static shape inference to return symbolic tensors # matching the specifications of the layer outputs. # Since `self.dynamic` is True, we will never attempt to # run the underlying TF graph (which is disconnected). # TODO(fchollet): consider py_func as an alternative, which # would enable us to run the underlying graph if needed. outputs = self._symbolic_call(inputs) if outputs is None: raise ValueError('A layer\'s `call` method should return a ' 'Tensor or a list of Tensors, not None ' '(layer: ' + self.name + ').') if base_layer_utils.have_all_keras_metadata(inputs): if training_arg_passed_by_framework: kwargs.pop('training') if mask_arg_passed_by_framework: kwargs.pop('mask') inputs, outputs = self._set_connectivity_metadata_( inputs, outputs, args, kwargs) self._handle_activity_regularization(inputs, outputs) self._set_mask_metadata(inputs, outputs, input_masks) if hasattr(self, '_set_inputs') and not self.inputs: # Subclassed network: explicitly set metadata normally set by # a call to self._set_inputs(). # TODO(b/120997007): This should be done in Eager as well, but # causes garbage collection issues because of the placeholders # created on the default Keras graph. self._set_inputs(inputs, outputs) else: # Eager execution on data tensors. with backend.name_scope(self._name_scope()): self._maybe_build(inputs) cast_inputs = self._maybe_cast_inputs(inputs) with base_layer_utils.autocast_context_manager( self._compute_dtype): outputs = self.call(cast_inputs, *args, **kwargs) self._handle_activity_regularization(inputs, outputs) self._set_mask_metadata(inputs, outputs, input_masks) return outputs @property def dtype(self): return self._dtype_policy.variable_dtype @property def name(self): return self._name @property def dynamic(self): return self._dynamic @property def trainable(self): return self._trainable @trainable.setter def trainable(self, value): self._trainable = value for layer in getattr(self, '_layers', []): layer.trainable = value @property def activity_regularizer(self): """Optional regularizer function for the output of this layer.""" return self._activity_regularizer @activity_regularizer.setter def activity_regularizer(self, regularizer): """Optional regularizer function for the output of this layer.""" self._activity_regularizer = regularizer @property def input_spec(self): return self._input_spec @input_spec.setter # Must be decorated to prevent tracking, since the input_spec can be nested # InputSpec objects. @trackable.no_automatic_dependency_tracking def input_spec(self, value): for v in nest.flatten(value): if v is not None and not isinstance(v, InputSpec): raise TypeError('Layer input_spec must be an instance of InputSpec. ' 'Got: {}'.format(v)) self._input_spec = value @property def trainable_weights(self): if self.trainable: nested = self._gather_children_attribute('trainable_weights') return self._trainable_weights + nested else: return [] @property def non_trainable_weights(self): if self.trainable: nested = self._gather_children_attribute('non_trainable_weights') return self._non_trainable_weights + nested else: nested = self._gather_children_attribute('weights') return self._trainable_weights + self._non_trainable_weights + nested @property def weights(self): """Returns the list of all layer variables/weights. Returns: A list of variables. """ return self.trainable_weights + self.non_trainable_weights @property def updates(self): if not self.trainable and not self.stateful: return [] with backend.get_graph().as_default(): updates = [] for u in self._updates: if callable(u): try: u = u() except errors.InaccessibleTensorError: base_layer_utils.check_graph_consistency( method='add_update', force_raise=True) raise # check_graph_consistency may not always raise. base_layer_utils.check_graph_consistency(u, method='add_update') updates.append(u) return updates + self._gather_children_attribute('updates') @property def losses(self): """Losses which are associated with this `Layer`. Variable regularization tensors are created when this property is accessed, so it is eager safe: accessing `losses` under a `tf.GradientTape` will propagate gradients back to the corresponding variables. Returns: A list of tensors. """ collected_losses = [] # If any eager losses are present, we assume the model to be part of an # eager training loop (either a custom one or the one used when # `run_eagerly=True`), and so we always return just the eager losses in that # case. if self._eager_losses: collected_losses.extend(self._eager_losses) else: collected_losses.extend(self._losses) for regularizer in self._callable_losses: loss_tensor = regularizer() if loss_tensor is not None: collected_losses.append(loss_tensor) return collected_losses + self._gather_children_attribute('losses') @doc_controls.for_subclass_implementers def add_loss(self, losses, inputs=None): """Add loss tensor(s), potentially dependent on layer inputs. Some losses (for instance, activity regularization losses) may be dependent on the inputs passed when calling a layer. Hence, when reusing the same layer on different inputs `a` and `b`, some entries in `layer.losses` may be dependent on `a` and some on `b`. This method automatically keeps track of dependencies. This method can be used inside a subclassed layer or model's `call` function, in which case `losses` should be a Tensor or list of Tensors. Example: ```python class MyLayer(tf.keras.layers.Layer): def call(inputs, self): self.add_loss(tf.abs(tf.reduce_mean(inputs)), inputs=True) return inputs ``` This method can also be called directly on a Functional Model during construction. In this case, any loss Tensors passed to this Model must be symbolic and be able to be traced back to the model's `Input`s. These losses become part of the model's topology and are tracked in `get_config`. Example: ```python inputs = tf.keras.Input(shape=(10,)) x = tf.keras.layers.Dense(10)(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) # Actvity regularization. model.add_loss(tf.abs(tf.reduce_mean(x))) ``` If this is not the case for your loss (if, for example, your loss references a `Variable` of one of the model's layers), you can wrap your loss in a zero-argument lambda. These losses are not tracked as part of the model's topology since they can't be serialized. Example: ```python inputs = tf.keras.Input(shape=(10,)) x = tf.keras.layers.Dense(10)(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) # Weight regularization. model.add_loss(lambda: tf.reduce_mean(x.kernel)) ``` The `get_losses_for` method allows to retrieve the losses relevant to a specific set of inputs. Arguments: losses: Loss tensor, or list/tuple of tensors. Rather than tensors, losses may also be zero-argument callables which create a loss tensor. inputs: Ignored when executing eagerly. If anything other than None is passed, it signals the losses are conditional on some of the layer's inputs, and thus they should only be run where these inputs are available. This is the case for activity regularization losses, for instance. If `None` is passed, the losses are assumed to be unconditional, and will apply across all dataflows of the layer (e.g. weight regularization losses). """ def _tag_unconditional(loss): if callable(loss): loss = loss() if loss is None: return None # Will be filtered out when computing the .losses property if not tensor_util.is_tensor(loss): loss = ops.convert_to_tensor(loss, dtype=backend.floatx()) loss._unconditional_loss = (inputs is None) # pylint: disable=protected-access return loss losses = nest.flatten(losses) callable_losses = [] eager_losses = [] symbolic_losses = [] for loss in losses: if callable(loss): callable_losses.append(functools.partial(_tag_unconditional, loss)) continue if loss is None: continue if not tensor_util.is_tensor(loss): loss = ops.convert_to_tensor(loss, dtype=backend.floatx()) # TF Functions should take the eager path. if (tf_utils.is_symbolic_tensor(loss) and not base_layer_utils.is_in_tf_function()): symbolic_losses.append(_tag_unconditional(loss)) base_layer_utils.check_graph_consistency(loss, method='add_loss') elif tensor_util.is_tensor(loss): eager_losses.append(_tag_unconditional(loss)) self._callable_losses += callable_losses in_call_context = base_layer_utils.call_context().in_call if eager_losses and not in_call_context: raise ValueError( 'Expected a symbolic Tensors or a callable for the loss value. ' 'Please wrap your loss computation in a zero argument `lambda`.') self._eager_losses += eager_losses if in_call_context: for symbolic_loss in symbolic_losses: self._losses.append(symbolic_loss) else: for symbolic_loss in symbolic_losses: if getattr(self, '_is_graph_network', False): self._graph_network_add_loss(symbolic_loss) else: # Possible a loss was added in a Layer's `build`. self._losses.append(symbolic_loss) @trackable.no_automatic_dependency_tracking def _clear_losses(self): """Used every step in eager to reset losses.""" self._eager_losses = [] if hasattr(self, '_layers'): for layer in trackable_layer_utils.filter_empty_layer_containers( self._layers): layer._clear_losses() @property def metrics(self): return self._metrics + self._gather_children_attribute('metrics') @doc_controls.for_subclass_implementers def add_metric(self, value, aggregation=None, name=None): """Adds metric tensor to the layer. Args: value: Metric tensor. aggregation: Sample-wise metric reduction function. If `aggregation=None`, it indicates that the metric tensor provided has been aggregated already. eg, `bin_acc = BinaryAccuracy(name='acc')` followed by `model.add_metric(bin_acc(y_true, y_pred))`. If aggregation='mean', the given metric tensor will be sample-wise reduced using `mean` function. eg, `model.add_metric(tf.reduce_sum(outputs), name='output_mean', aggregation='mean')`. name: String metric name. Raises: ValueError: If `aggregation` is anything other than None or `mean`. """ if aggregation is not None and aggregation != 'mean': raise ValueError( 'We currently support only `mean` sample-wise metric aggregation. ' 'You provided aggregation=`%s`' % aggregation) from_metric_obj = hasattr(value, '_metric_obj') is_symbolic = tf_utils.is_symbolic_tensor(value) in_call_context = base_layer_utils.call_context().in_call if name is None and not from_metric_obj: # Eg. `self.add_metric(math_ops.reduce_sum(x), aggregation='mean')` # In eager mode, we use metric name to lookup a metric. Without a name, # a new Mean metric wrapper will be created on every model/layer call. # So, we raise an error when no name is provided. # We will do the same for symbolic mode for consistency although a name # will be generated if no name is provided. # We will not raise this error in the foll use case for the sake of # consistency as name in provided in the metric constructor. # mean = metrics.Mean(name='my_metric') # model.add_metric(mean(outputs)) raise ValueError('Please provide a name for your metric like ' '`self.add_metric(tf.reduce_sum(inputs), ' 'name=\'mean_activation\', aggregation=\'mean\')`') elif from_metric_obj: name = value._metric_obj.name if in_call_context: # TF Function path should take the eager path. if is_symbolic and not base_layer_utils.is_in_tf_function(): self._symbolic_add_metric(value, aggregation, name) else: self._eager_add_metric(value, aggregation, name) else: if not is_symbolic: raise ValueError('Expected a symbolic Tensor for the metric value, ' 'received: ' + str(value)) # Possible a metric was added in a Layer's `build`. if not getattr(self, '_is_graph_network', False): with backend.get_graph().as_default(): self._symbolic_add_metric(value, aggregation, name) return if from_metric_obj: raise ValueError('Using the result of calling a `Metric` object ' 'when calling `add_metric` on a Functional ' 'Model is not supported. Please pass the ' 'Tensor to monitor directly.') # Insert layers into the Keras Graph Network. self._graph_network_add_metric(value, aggregation, name) @deprecation.deprecated_args(None, '`inputs` is now automatically inferred', 'inputs') @doc_controls.for_subclass_implementers def add_update(self, updates, inputs=None): """Add update op(s), potentially dependent on layer inputs. Weight updates (for instance, the updates of the moving mean and variance in a BatchNormalization layer) may be dependent on the inputs passed when calling a layer. Hence, when reusing the same layer on different inputs `a` and `b`, some entries in `layer.updates` may be dependent on `a` and some on `b`. This method automatically keeps track of dependencies. The `get_updates_for` method allows to retrieve the updates relevant to a specific set of inputs. This call is ignored when eager execution is enabled (in that case, variable updates are run on the fly and thus do not need to be tracked for later execution). Arguments: updates: Update op, or list/tuple of update ops, or zero-arg callable that returns an update op. A zero-arg callable should be passed in order to disable running the updates by setting `trainable=False` on this Layer, when executing in Eager mode. inputs: Deprecated, will be automatically inferred. """ if ds_context.has_strategy() and ds_context.in_cross_replica_context(): # Updates don't need to be run in a cross-replica context. if (ops.executing_eagerly_outside_functions() and not base_layer_utils.is_in_keras_graph()): raise RuntimeError( # pylint: disable=g-doc-exception '`add_update` was called in a cross-replica context. This is not ' 'expected. If you require this feature, please file an issue.') return updates = generic_utils.to_list(updates) call_context = base_layer_utils.call_context() # All updates can be run immediately in Eager or in a tf.function. if base_layer_utils.is_in_eager_or_tf_function(): if not call_context.frozen: for update in updates: if callable(update): update() return if call_context.in_call: relevant_inputs = call_context.inputs else: inbound_nodes = getattr(self, '_inbound_nodes', []) relevant_inputs = [node.input_tensors for node in inbound_nodes] def process_update(x): """Standardize update ops. Arguments: x: Tensor, op, or callable. Returns: An update op. """ if callable(x): update = lambda: process_update(x()) if not ops.executing_eagerly_outside_functions(): # In V1 mode, call the callable right away and process. This is needed # for TPU strategy. return update() elif isinstance(x, ops.Operation): update = x elif hasattr(x, 'op'): update = x.op else: update = ops.convert_to_tensor(x) reachable = tf_utils.get_reachable_from_inputs(relevant_inputs, [update]) update._unconditional_update = update not in reachable return update updates = [process_update(x) for x in updates] # Non-callable Updates are run automatically inside `call` in V2, so # they do not need to be tracked later. if ops.executing_eagerly_outside_functions() and call_context.in_call: updates = [u for u in updates if callable(u)] self._updates += updates def set_weights(self, weights): """Sets the weights of the layer, from Numpy arrays. Arguments: weights: a list of Numpy arrays. The number of arrays and their shape must match number of the dimensions of the weights of the layer (i.e. it should match the output of `get_weights`). Raises: ValueError: If the provided weights list does not match the layer's specifications. """ params = self.weights if len(params) != len(weights): raise ValueError('You called `set_weights(weights)` on layer "' + self.name + '" with a weight list of length ' + str(len(weights)) + ', but the layer was expecting ' + str(len(params)) + ' weights. Provided weights: ' + str(weights)[:50] + '...') if not params: return weight_value_tuples = [] for p, w in zip(params, weights): ref_shape = p.shape if not ref_shape.is_compatible_with(w.shape): raise ValueError('Layer weight shape ' + str(ref_shape) + ' not compatible with ' 'provided weight shape ' + str(w.shape)) weight_value_tuples.append((p, w)) backend.batch_set_value(weight_value_tuples) def get_weights(self): """Returns the current weights of the layer. Returns: Weights values as a list of numpy arrays. """ params = self.weights return backend.batch_get_value(params) def get_updates_for(self, inputs): """Retrieves updates relevant to a specific set of inputs. Arguments: inputs: Input tensor or list/tuple of input tensors. Returns: List of update ops of the layer that depend on `inputs`. """ if inputs is None: # Requesting unconditional updates. return [u for u in self.updates if u._unconditional_update] # Requesting input-conditional updates. updates = [u for u in self.updates if not u._unconditional_update] inputs = nest.flatten(inputs) reachable = tf_utils.get_reachable_from_inputs(inputs, updates) return [u for u in updates if u in reachable] def get_losses_for(self, inputs): """Retrieves losses relevant to a specific set of inputs. Arguments: inputs: Input tensor or list/tuple of input tensors. Returns: List of loss tensors of the layer that depend on `inputs`. """ if inputs is None: # Requesting unconditional losses. return [l for l in self.losses if l._unconditional_loss] # Requesting input-conditional losses. losses = [l for l in self.losses if not l._unconditional_loss] inputs = nest.flatten(inputs) reachable = tf_utils.get_reachable_from_inputs(inputs, losses) return [l for l in losses if l in reachable] def get_input_mask_at(self, node_index): """Retrieves the input mask tensor(s) of a layer at a given node. Arguments: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A mask tensor (or list of tensors if the layer has multiple inputs). """ inputs = self.get_input_at(node_index) if isinstance(inputs, list): return [getattr(x, '_keras_mask', None) for x in inputs] else: return getattr(inputs, '_keras_mask', None) def get_output_mask_at(self, node_index): """Retrieves the output mask tensor(s) of a layer at a given node. Arguments: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A mask tensor (or list of tensors if the layer has multiple outputs). """ output = self.get_output_at(node_index) if isinstance(output, list): return [getattr(x, '_keras_mask', None) for x in output] else: return getattr(output, '_keras_mask', None) @property def input_mask(self): """Retrieves the input mask tensor(s) of a layer. Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer. Returns: Input mask tensor (potentially None) or list of input mask tensors. Raises: AttributeError: if the layer is connected to more than one incoming layers. """ inputs = self.input if isinstance(inputs, list): return [getattr(x, '_keras_mask', None) for x in inputs] else: return getattr(inputs, '_keras_mask', None) @property def output_mask(self): """Retrieves the output mask tensor(s) of a layer. Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer. Returns: Output mask tensor (potentially None) or list of output mask tensors. Raises: AttributeError: if the layer is connected to more than one incoming layers. """ output = self.output if isinstance(output, list): return [getattr(x, '_keras_mask', None) for x in output] else: return getattr(output, '_keras_mask', None) def get_input_shape_at(self, node_index): """Retrieves the input shape(s) of a layer at a given node. Arguments: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A shape tuple (or list of shape tuples if the layer has multiple inputs). Raises: RuntimeError: If called in Eager mode. """ return self._get_node_attribute_at_index(node_index, 'input_shapes', 'input shape') def get_output_shape_at(self, node_index): """Retrieves the output shape(s) of a layer at a given node. Arguments: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A shape tuple (or list of shape tuples if the layer has multiple outputs). Raises: RuntimeError: If called in Eager mode. """ return self._get_node_attribute_at_index(node_index, 'output_shapes', 'output shape') def get_input_at(self, node_index): """Retrieves the input tensor(s) of a layer at a given node. Arguments: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A tensor (or list of tensors if the layer has multiple inputs). Raises: RuntimeError: If called in Eager mode. """ return self._get_node_attribute_at_index(node_index, 'input_tensors', 'input') def get_output_at(self, node_index): """Retrieves the output tensor(s) of a layer at a given node. Arguments: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A tensor (or list of tensors if the layer has multiple outputs). Raises: RuntimeError: If called in Eager mode. """ return self._get_node_attribute_at_index(node_index, 'output_tensors', 'output') @property def input(self): """Retrieves the input tensor(s) of a layer. Only applicable if the layer has exactly one input, i.e. if it is connected to one incoming layer. Returns: Input tensor or list of input tensors. Raises: RuntimeError: If called in Eager mode. AttributeError: If no inbound nodes are found. """ if not self._inbound_nodes: raise AttributeError('Layer ' + self.name + ' is not connected, no input to return.') return self._get_node_attribute_at_index(0, 'input_tensors', 'input') @property def output(self): """Retrieves the output tensor(s) of a layer. Only applicable if the layer has exactly one output, i.e. if it is connected to one incoming layer. Returns: Output tensor or list of output tensors. Raises: AttributeError: if the layer is connected to more than one incoming layers. RuntimeError: if called in Eager mode. """ if not self._inbound_nodes: raise AttributeError('Layer ' + self.name + ' has no inbound nodes.') return self._get_node_attribute_at_index(0, 'output_tensors', 'output') @property def input_shape(self): """Retrieves the input shape(s) of a layer. Only applicable if the layer has exactly one input, i.e. if it is connected to one incoming layer, or if all inputs have the same shape. Returns: Input shape, as an integer shape tuple (or list of shape tuples, one tuple per input tensor). Raises: AttributeError: if the layer has no defined input_shape. RuntimeError: if called in Eager mode. """ if not self._inbound_nodes: raise AttributeError('The layer has never been called ' 'and thus has no defined input shape.') all_input_shapes = set( [str(node.input_shapes) for node in self._inbound_nodes]) if len(all_input_shapes) == 1: return self._inbound_nodes[0].input_shapes else: raise AttributeError('The layer "' + str(self.name) + ' has multiple inbound nodes, ' 'with different input shapes. Hence ' 'the notion of "input shape" is ' 'ill-defined for the layer. ' 'Use `get_input_shape_at(node_index)` ' 'instead.') def count_params(self): """Count the total number of scalars composing the weights. Returns: An integer count. Raises: ValueError: if the layer isn't yet built (in which case its weights aren't yet defined). """ if not self.built: if self.__class__.__name__ == 'Sequential': with tf_utils.maybe_init_scope(self): self._maybe_build() # pylint: disable=no-value-for-parameter else: raise ValueError('You tried to call `count_params` on ' + self.name + ', but the layer isn\'t built. ' 'You can build it manually via: `' + self.name + '.build(batch_input_shape)`.') return int(sum(np.prod(w.shape.as_list()) for w in self.weights)) @property def output_shape(self): """Retrieves the output shape(s) of a layer. Only applicable if the layer has one output, or if all outputs have the same shape. Returns: Output shape, as an integer shape tuple (or list of shape tuples, one tuple per output tensor). Raises: AttributeError: if the layer has no defined output shape. RuntimeError: if called in Eager mode. """ if not self._inbound_nodes: raise AttributeError('The layer has never been called ' 'and thus has no defined output shape.') all_output_shapes = set( [str(node.output_shapes) for node in self._inbound_nodes]) if len(all_output_shapes) == 1: return self._inbound_nodes[0].output_shapes else: raise AttributeError('The layer "%s"' ' has multiple inbound nodes, ' 'with different output shapes. Hence ' 'the notion of "output shape" is ' 'ill-defined for the layer. ' 'Use `get_output_shape_at(node_index)` ' 'instead.' % self.name) @property @doc_controls.do_not_doc_inheritable def inbound_nodes(self): """Deprecated, do NOT use! Only for compatibility with external Keras.""" return self._inbound_nodes @property @doc_controls.do_not_doc_inheritable def outbound_nodes(self): """Deprecated, do NOT use! Only for compatibility with external Keras.""" return self._outbound_nodes ############################################################################## # Methods & attributes below are public aliases of other methods. # ############################################################################## @deprecation.deprecated( date=None, instructions='Please use `layer.__call__` method instead.') @doc_controls.do_not_doc_inheritable def apply(self, inputs, *args, **kwargs): """Deprecated, do NOT use! This is an alias of `self.__call__`. Arguments: inputs: Input tensor(s). *args: additional positional arguments to be passed to `self.call`. **kwargs: additional keyword arguments to be passed to `self.call`. Returns: Output tensor(s). """ return self.__call__(inputs, *args, **kwargs) @deprecation.deprecated( date=None, instructions='Please use `layer.add_weight` method instead.') @doc_controls.do_not_doc_inheritable def add_variable(self, *args, **kwargs): """Deprecated, do NOT use! Alias for `add_weight`.""" return self.add_weight(*args, **kwargs) @property def variables(self): """Returns the list of all layer variables/weights. Alias of `self.weights`. Returns: A list of variables. """ return self.weights @property def trainable_variables(self): return self.trainable_weights @property def non_trainable_variables(self): return self.non_trainable_weights ############################################################################## # Methods & attributes below are all private and only used by the framework. # ############################################################################## def _set_dtype_policy(self, dtype): """Sets self._dtype_policy.""" if isinstance(dtype, policy.Policy): self._dtype_policy = dtype elif dtype: self._dtype_policy = policy.Policy(dtypes.as_dtype(dtype).name) else: self._dtype_policy = policy.global_policy() # This has no impact on the layer behavior, and is only used for printing # warnings. self._dtype_defaulted_to_floatx = (not dtype and policy.policy_defaults_to_floatx()) # TODO(reedwm): Expose this property? @property def _compute_dtype(self): """The layer's compute dtype. Unless mixed-precision is used, this is the same as `Layer.dtype`. If self._autocast is True, layer's will cast floating-point inputs to this. Returns: The layer's compute dtype. """ return self._dtype_policy.compute_dtype def _maybe_cast_inputs(self, inputs): """Maybe casts the inputs to the compute dtype. If self._compute_dtype is floating-point, and self_autocast is True, floating-point inputs are casted to self._compute_dtype. Args: inputs: Input tensor, or structure of input tensors. Returns: `inputs`, but tensors may have been casted to self._compute_dtype """ compute_dtype = self._compute_dtype if (self._autocast and compute_dtype and dtypes.as_dtype(compute_dtype).is_floating): def f(x): if (isinstance(x, ops.Tensor) and x.dtype.is_floating and x.dtype.base_dtype.name != compute_dtype): if self._dtype_defaulted_to_floatx: self._warn_about_input_casting(x.dtype.base_dtype) return math_ops.cast(x, compute_dtype) else: return x return nest.map_structure(f, inputs) else: return inputs def _warn_about_input_casting(self, input_dtype): # self._already_warned_about_input_casting is only retrieved or set in this # function. already_warned = getattr(self, '_already_warned_about_input_casting', False) if not already_warned: tf_logging.warn( "Layer {self.name} is casting an input tensor from dtype " "{input_dtype} to the layer's dtype of {layer_dtype}, which is new " "behavior in TensorFlow 2. The layer has dtype {layer_dtype} " "because it's dtype defaults to floatx.\n\n" "" "If you intended to run this layer in {layer_dtype}, you can safely " "ignore this warning. If in doubt, this warning is likely only an " "issue if you are porting a TensorFlow 1.X model to TensorFlow 2.\n\n" "" "To change all layers to have dtype {input_dtype} by default, call " "`tf.keras.backend.set_floatx('{input_dtype}')`. To change just this " "layer, pass dtype='{input_dtype}' to the layer constructor. If you " "are the author of this layer, you can disable autocasting by " "passing experimental_autocast=False to the base Layer " "constructor.\n".format( self=self, input_dtype=input_dtype.name, layer_dtype=self._compute_dtype)) self._already_warned_about_input_casting = True # _dtype used to be an attribute set in the constructor. We still expose it # because some clients still use it. # TODO(reedwm): Deprecate, then remove the _dtype property. @property def _dtype(self): # This is equivalent to returning self.dtype . We do not return self.dtype # as it would cause infinite recursion in a few subclasses, which override # "dtype" to return self._dtype. return self._dtype_policy.variable_dtype @_dtype.setter def _dtype(self, value): value = dtypes.as_dtype(value).name self._dtype_policy = policy.Policy(value) def _name_scope(self): return self.name def _init_set_name(self, name, zero_based=True): if not name: self._name = backend.unique_object_name( generic_utils.to_snake_case(self.__class__.__name__), zero_based=zero_based) else: self._name = name def _get_existing_metric(self, name=None): match = [m for m in self._metrics if m.name == name] if not match: return if len(match) > 1: raise ValueError( 'Please provide different names for the metrics you have added. ' 'We found {} metrics with the name: "{}"'.format(len(match), name)) return match[0] def _eager_add_metric(self, value, aggregation=None, name=None): # If the given metric is available in `metrics` list we just update state # on it, otherwise we create a new metric instance and # add it to the `metrics` list. metric_obj = getattr(value, '_metric_obj', None) if metric_obj: name = metric_obj.name match = self._get_existing_metric(name) if match: # Tensors that come from a Metric object already updated the Metric state. if not metric_obj: match(value) return if not metric_obj: assert aggregation is not None metric_obj, _ = base_layer_utils.create_mean_metric(value, name) self._metrics.append(metric_obj) def _symbolic_add_metric(self, value, aggregation=None, name=None): base_layer_utils.check_graph_consistency(value, method='add_metric') match = self._get_existing_metric(name) if aggregation is None: # Iterate over the metrics and check if the given metric exists already. # This can happen when a metric instance is created in subclassed model # layer `__init__` and we have tracked that instance already in # model.__setattr__. if match: result_tensor = value metric_obj = match elif hasattr(value, '_metric_obj'): # We track the instance using the metadata on the result tensor. result_tensor = value metric_obj = result_tensor._metric_obj self._metrics.append(metric_obj) else: raise ValueError( 'We do not support adding an aggregated metric result tensor that ' 'is not the output of a `tf.keras.metrics.Metric` metric instance. ' 'Without having access to the metric instance we cannot reset the ' 'state of a metric after every epoch during training. You can ' 'create a `tf.keras.metrics.Metric` instance and pass the result ' 'here or pass an un-aggregated result with `aggregation` parameter ' 'set as `mean`. For example: `self.add_metric(tf.reduce_sum(inputs)' ', name=\'mean_activation\', aggregation=\'mean\')`') else: # If a non-aggregated tensor is given as input (ie. `aggregation` is # explicitly set to `mean`), we wrap the tensor in `Mean` metric. if match: result_tensor = match(value) metric_obj = match else: metric_obj, result_tensor = base_layer_utils.create_mean_metric( value, name) self._metrics.append(metric_obj) def _handle_weight_regularization(self, name, variable, regularizer): """Create lambdas which compute regularization losses.""" def _loss_for_variable(v): """Creates a regularization loss `Tensor` for variable `v`.""" with backend.name_scope(name + '/Regularizer'): regularization = regularizer(v) return regularization if isinstance(variable, tf_variables.PartitionedVariable): for v in variable: self.add_loss(functools.partial(_loss_for_variable, v)) else: self.add_loss(functools.partial(_loss_for_variable, variable)) def _handle_activity_regularization(self, inputs, outputs): # Apply activity regularization. # Note that it should be applied every time the layer creates a new # output, since it is output-specific. if self._activity_regularizer: output_list = nest.flatten(outputs) with backend.name_scope('ActivityRegularizer'): for output in output_list: activity_loss = self._activity_regularizer(output) batch_size = math_ops.cast( array_ops.shape(output)[0], activity_loss.dtype) # Make activity regularization strength batch-agnostic. mean_activity_loss = activity_loss / batch_size base_layer_utils.check_graph_consistency( mean_activity_loss, method='activity_regularizer') self.add_loss(mean_activity_loss, inputs=inputs) def _set_mask_metadata(self, inputs, outputs, previous_mask): flat_outputs = nest.flatten(outputs) mask_already_computed = ( getattr(self, '_compute_output_and_mask_jointly', False) or all(getattr(x, '_keras_mask', None) is not None for x in flat_outputs)) # Only compute the mask if the Layer explicitly supports masking or has # overridden `compute_mask`. should_compute_mask = ( hasattr(self, 'compute_mask') and (self.supports_masking or not getattr(self.compute_mask, '_is_default', False))) if mask_already_computed: flat_masks = [getattr(x, '_keras_mask', None) for x in flat_outputs] elif not should_compute_mask: flat_masks = [None for _ in flat_outputs] else: output_masks = self.compute_mask(inputs, previous_mask) # `compute_mask` can return a single `None` even when a Layer # has multiple outputs. if output_masks is None: flat_masks = [None for _ in flat_outputs] else: flat_masks = nest.flatten(output_masks) for output, mask in zip(flat_outputs, flat_masks): try: output._keras_mask = mask except AttributeError: # C Type such as np.ndarray. pass if tf_utils.are_all_symbolic_tensors(flat_outputs): for output in flat_outputs: if getattr(output, '_keras_mask', None) is not None: # Do not track masks for `TensorFlowOpLayer` construction. output._keras_mask._keras_history_checked = True def _collect_input_masks(self, inputs, args, kwargs): """Checks if `mask` argument was passed, else gathers mask from inputs.""" if self._call_arg_was_passed('mask', args, kwargs): return self._get_call_arg_value('mask', args, kwargs) if not self._should_compute_mask: return None input_masks = nest.map_structure(lambda t: getattr(t, '_keras_mask', None), inputs) if generic_utils.is_all_none(input_masks): return None return input_masks def _call_arg_was_passed(self, arg_name, args, kwargs): if arg_name in kwargs: return True # Ignore `inputs` arg. if arg_name in dict(zip(self._call_fn_args[1:], args)): return True return False def _get_call_arg_value(self, arg_name, args, kwargs): if arg_name in kwargs: return kwargs[arg_name] # Ignore `inputs` arg. args_dict = dict(zip(self._call_fn_args[1:], args)) return args_dict[arg_name] def _set_connectivity_metadata_(self, inputs, outputs, args, kwargs): # If the layer returns tensors from its inputs, unmodified, # we copy them to avoid loss of tensor metadata. output_ls = nest.flatten(outputs) inputs_ls = object_identity.ObjectIdentitySet(nest.flatten(inputs)) output_ls_copy = [] for x in output_ls: if x in inputs_ls: with backend.name_scope(self.name): x = array_ops.identity(x) output_ls_copy.append(x) outputs = nest.pack_sequence_as(outputs, output_ls_copy) # Ignore `inputs` arg. arguments = dict(zip(self._call_fn_args[1:], args)) arguments.update(kwargs) # Add an inbound node to the layer, so it can keep track of this call. # This updates the layer history of the output tensor(s). self._add_inbound_node( input_tensors=inputs, output_tensors=outputs, arguments=arguments) return inputs, outputs def _add_inbound_node(self, input_tensors, output_tensors, arguments=None): """Internal method to create an inbound node for the layer. Arguments: input_tensors: list of input tensors. output_tensors: list of output tensors. arguments: dictionary of keyword arguments that were passed to the `call` method of the layer at the call that created the node. """ inbound_layers = nest.map_structure(lambda t: t._keras_history.layer, input_tensors) node_indices = nest.map_structure(lambda t: t._keras_history.node_index, input_tensors) tensor_indices = nest.map_structure(lambda t: t._keras_history.tensor_index, input_tensors) # Create node, add it to inbound nodes. node_module.Node( self, inbound_layers=inbound_layers, node_indices=node_indices, tensor_indices=tensor_indices, input_tensors=input_tensors, output_tensors=output_tensors, arguments=arguments) # Update tensor history metadata. # The metadata attribute consists of # 1) a layer instance # 2) a node index for the layer # 3) a tensor index for the node. # The allows layer reuse (multiple nodes per layer) and multi-output # or multi-input layers (e.g. a layer can return multiple tensors, # and each can be sent to a different layer). for i, tensor in enumerate(nest.flatten(output_tensors)): tensor._keras_history = KerasHistory(self, len(self._inbound_nodes) - 1, i) # pylint: disable=protected-access def _get_node_attribute_at_index(self, node_index, attr, attr_name): """Private utility to retrieves an attribute (e.g. inputs) from a node. This is used to implement the methods: - get_input_shape_at - get_output_shape_at - get_input_at etc... Arguments: node_index: Integer index of the node from which to retrieve the attribute. attr: Exact node attribute name. attr_name: Human-readable attribute name, for error messages. Returns: The layer's attribute `attr` at the node of index `node_index`. Raises: RuntimeError: If the layer has no inbound nodes, or if called in Eager mode. ValueError: If the index provided does not match any node. """ if not self._inbound_nodes: raise RuntimeError('The layer has never been called ' 'and thus has no defined ' + attr_name + '.') if not len(self._inbound_nodes) > node_index: raise ValueError('Asked to get ' + attr_name + ' at node ' + str(node_index) + ', but the layer has only ' + str(len(self._inbound_nodes)) + ' inbound nodes.') values = getattr(self._inbound_nodes[node_index], attr) if isinstance(values, list) and len(values) == 1: return values[0] else: return values def _maybe_build(self, inputs): # Check input assumptions set before layer building, e.g. input rank. if not self.built: input_spec.assert_input_compatibility( self.input_spec, inputs, self.name) input_list = nest.flatten(inputs) if input_list and self._dtype_policy.compute_dtype is None: try: dtype = input_list[0].dtype.base_dtype.name except AttributeError: pass else: self._dtype_policy = policy.with_input_dtype(self._dtype_policy, dtype) input_shapes = None if all(hasattr(x, 'shape') for x in input_list): input_shapes = nest.map_structure(lambda x: x.shape, inputs) # Only call `build` if the user has manually overridden the build method. if not hasattr(self.build, '_is_default'): # Any setup work performed only once should happen in an `init_scope` # to avoid creating symbolic Tensors that will later pollute any eager # operations. with tf_utils.maybe_init_scope(self): self.build(input_shapes) # We must set self.built since user defined build functions are not # constrained to set self.built. self.built = True # Optionally load weight values specified at layer instantiation. if getattr(self, '_initial_weights', None) is not None: self.set_weights(self._initial_weights) self._initial_weights = None def _symbolic_call(self, inputs): input_shapes = nest.map_structure(lambda x: x.shape, inputs) output_shapes = self.compute_output_shape(input_shapes) def _make_placeholder_like(shape): ph = backend.placeholder(shape=shape, dtype=self.dtype) ph._keras_mask = None return ph return nest.map_structure(_make_placeholder_like, output_shapes) def _get_trainable_state(self): """Get the `trainable` state of each sublayer. Returns: A dict mapping all sublayers to their `trainable` value. """ layers = trackable_layer_utils.filter_empty_layer_containers(self._layers) # Keep track of each top-level layers' `trainable` as well as the # state of all of its sublayers. trainable_state = {self: self.trainable} for layer in layers: trainable_state.update(layer._get_trainable_state()) return trainable_state def _set_trainable_state(self, trainable_state): """Set `trainable` state for each sublayer.""" layers = trackable_layer_utils.filter_empty_layer_containers(self._layers) if self in trainable_state: self.trainable = trainable_state[self] for layer in layers: layer._set_trainable_state(trainable_state) @property def _obj_reference_counts(self): """A dictionary counting the number of attributes referencing an object.""" self._maybe_create_attribute('_obj_reference_counts_dict', object_identity.ObjectIdentityDictionary()) return self._obj_reference_counts_dict def _maybe_create_attribute(self, name, default_value): """Create the attribute with the default value if it hasn't been created. This is useful for fields that is used for tracking purpose, _trainable_weights, or _layers. Note that user could create a layer subclass and assign an internal field before invoking the Layer.__init__(), the __setattr__() need to create the tracking fields and __init__() need to not override them. Args: name: String, the name of the attribute. default_value: Object, the default value of the attribute. """ if not hasattr(self, name): super(Layer, self).__setattr__(name, default_value) def __delattr__(self, name): # For any super.__delattr__() call, we will directly use the implementation # in Trackable and skip the behavior in AutoTrackable. The Layer was # originally use Trackable as base class, the change of using Module as base # class forced us to have AutoTrackable in the class hierarchy. Skipping # the __delattr__ and __setattr__ in AutoTrackable will keep the status quo. existing_value = getattr(self, name, None) # If this value is replacing an existing object assigned to an attribute, we # should clean it out to avoid leaking memory. First we check if there are # other attributes referencing it. reference_counts = self._obj_reference_counts if existing_value not in reference_counts: super(tracking.AutoTrackable, self).__delattr__(name) return reference_count = reference_counts[existing_value] if reference_count > 1: # There are other remaining references. We can't remove this object from # _layers etc. reference_counts[existing_value] = reference_count - 1 super(tracking.AutoTrackable, self).__delattr__(name) return else: # This is the last remaining reference. del reference_counts[existing_value] super(tracking.AutoTrackable, self).__delattr__(name) if (isinstance(existing_value, Layer) or trackable_layer_utils.has_weights(existing_value)): super(tracking.AutoTrackable, self).__setattr__( '_layers', [l for l in self._layers if l is not existing_value]) if isinstance(existing_value, tf_variables.Variable): super(tracking.AutoTrackable, self).__setattr__( '_trainable_weights', [w for w in self._trainable_weights if w is not existing_value]) super(tracking.AutoTrackable, self).__setattr__( '_non_trainable_weights', [w for w in self._non_trainable_weights if w is not existing_value]) def __setattr__(self, name, value): if (name == '_self_setattr_tracking' or not getattr(self, '_self_setattr_tracking', True) or getattr(self, '_is_graph_network', False) or # Exclude @property.setters from tracking hasattr(self.__class__, name)): try: super(tracking.AutoTrackable, self).__setattr__(name, value) except AttributeError: raise AttributeError( ('Can\'t set the attribute "{}", likely because it conflicts with ' 'an existing read-only @property of the object. Please choose a ' 'different name.').format(name)) return # Keep track of trackable objects, for the needs of `Network.save_weights`. value = data_structures.sticky_attribute_assignment( trackable=self, value=value, name=name) reference_counts = self._obj_reference_counts reference_counts[value] = reference_counts.get(value, 0) + 1 # Clean out the old attribute, which clears _layers and _trainable_weights # if necessary. try: self.__delattr__(name) except AttributeError: pass # TODO(scottzhu): Need to track Module object as well for weight tracking. # Be careful about metric if it becomes a Module in future. # Append value to self._layers if relevant # Sequential models use a separate layer tracking mechanism, so skip the # logic defined here for tracking layers. if (self.__class__.__name__ != 'Sequential' and (isinstance(value, Layer) or trackable_layer_utils.has_weights(value))): self._maybe_create_attribute('_layers', []) # We need to check object identity to avoid de-duplicating empty # container types which compare equal. if not any((layer is value for layer in self._layers)): self._layers.append(value) if hasattr(value, '_use_resource_variables'): # Legacy layers (V1 tf.layers) must always use # resource variables. value._use_resource_variables = True # Append value to list of trainable / non-trainable weights if relevant # TODO(b/125122625): This won't pick up on any variables added to a # list/dict after creation. for val in nest.flatten(value): # TODO(b/126450014): Remove `_UnreadVariable` check here when assign ops # no longer return True for isinstance Variable checks. if not isinstance(val, tf_variables.Variable): continue if isinstance(val, resource_variable_ops._UnreadVariable): # pylint: disable=protected-access continue # Users may add extra weights/variables # simply by assigning them to attributes (invalid for graph networks) self._maybe_create_attribute('_trainable_weights', []) self._maybe_create_attribute('_non_trainable_weights', []) if val.trainable: if any(val is w for w in self._trainable_weights): continue self._trainable_weights.append(val) else: if any(val is w for w in self._non_trainable_weights): continue self._non_trainable_weights.append(val) backend.track_variable(val) # Skip the auto trackable from tf.Module to keep status quo. See the comment # at __delattr__. super(tracking.AutoTrackable, self).__setattr__(name, value) def _gather_children_attribute(self, attribute): assert attribute in { 'weights', 'trainable_weights', 'non_trainable_weights', 'updates', 'losses', 'metrics' } if hasattr(self, '_layers'): nested_layers = trackable_layer_utils.filter_empty_layer_containers( self._layers) return list( itertools.chain.from_iterable( getattr(layer, attribute) for layer in nested_layers)) return [] # This is a hack so that the is_layer (within # training/trackable/layer_utils.py) check doesn't get the weights attr. # TODO(b/110718070): Remove when fixed. def _is_layer(self): return True def _init_call_fn_args(self): # Clear cached call function arguments. self.__class__._call_fn_args.fget.cache.pop(self, None) self.__class__._call_accepts_kwargs.fget.cache.pop(self, None) call_fn_args = self._call_fn_args self._expects_training_arg = ('training' in call_fn_args or self._call_accepts_kwargs) self._expects_mask_arg = ('mask' in call_fn_args or self._call_accepts_kwargs) @property @tracking.cached_per_instance def _call_fn_args(self): all_args = tf_inspect.getfullargspec(self.call).args # Scrub `self` that appears if a decorator was applied. if all_args and all_args[0] == 'self': return all_args[1:] return all_args @property @tracking.cached_per_instance def _call_accepts_kwargs(self): return tf_inspect.getfullargspec(self.call).varkw is not None @property @tracking.cached_per_instance def _should_compute_mask(self): return ('mask' in self._call_fn_args or getattr(self, 'compute_mask', None) is not None) @property def _object_identifier(self): """String stored in object identifier field in the SavedModel proto. Returns: A string with the object identifier, which is used at load time. """ return '_tf_keras_layer' @property def _eager_losses(self): # A list of loss values containing activity regularizers and losses # manually added through `add_loss` during eager execution. It is cleared # after every batch. # Because we plan on eventually allowing a same model instance to be trained # in eager mode or graph mode alternatively, we need to keep track of # eager losses and symbolic losses via separate attributes. if not hasattr(self._thread_local, '_eager_losses'): self._thread_local._eager_losses = [] return self._thread_local._eager_losses @_eager_losses.setter def _eager_losses(self, losses): self._thread_local._eager_losses = losses @property def _tracking_metadata(self): """String stored in metadata field in the SavedModel proto. Returns: A serialized JSON storing information necessary for recreating this layer. """ # TODO(kathywu): Add support for metrics serialization. # TODO(kathywu): Synchronize with the keras spec (go/keras-json-spec) once # the python config serialization has caught up. # Create a dictionary containing python layer state attributes. Any new # attribute that impacts the layer execution in some way should be added to # this dict. # Unlike a model's JSON configuration, which only # contains class_name and each layer's get_config() object, this stores more # information to accurately recreate the layer. # For backwards compatibility, any changes to this list should be additive. # Modifying or removing attributes may only be done with a sufficient # explanation. metadata = dict( class_name=type(self).__name__, name=self.name, trainable=self.trainable, expects_training_arg=self._expects_training_arg, dtype=self.dtype, batch_input_shape=getattr(self, '_batch_input_shape', None)) try: # Store the config dictionary, which is only used by the revived object # to return the original config when revived_obj.get_config() is called. # It is not important for recreating the revived object. metadata['config'] = self.get_config() except NotImplementedError: # in the case of a subclassed model, the get_config() method will throw # a NotImplementedError. pass if self.input_spec is not None: # Layer's input_spec has already been type-checked in the property setter. metadata['input_spec'] = nest.map_structure( lambda x: None if x is None else serialize_keras_object(x), self.input_spec) else: metadata['input_spec'] = None if (self.activity_regularizer is not None and hasattr(self.activity_regularizer, 'get_config')): metadata['activity_regularizer'] = serialize_keras_object( self.activity_regularizer) else: metadata['activity_regularizer'] = None return json.dumps(metadata, default=serialization.get_json_type) def _list_extra_dependencies_for_serialization(self, serialization_cache): """Lists extra dependencies to serialize to SavedModel. By overriding this method, extra dependencies can be attached to the serialized Layer. For example, this is used to save the list of `variables` and `trainable_variables`, which are python properties in a Layer object, but are represented as a static list in the SavedModel. Args: serialization_cache: A dictionary shared between all objects in the same object graph. This object is passed to both `_list_extra_dependencies_for_serialization` and `_list_functions_for_serialization`. Returns: A dictionary mapping attribute names to trackable objects. The entire list of attributes are listed in the `saved_model._LayerAttributes` class. """ return (saved_model.serialize_all_attributes(self, serialization_cache) .objects_to_serialize) def _list_functions_for_serialization(self, serialization_cache): """Lists the functions to include when serializing a Layer. Args: serialization_cache: Dictionary passed to all objects in the same object graph during serialization. Returns: A dictionary mapping attribute names to `Function` or `ConcreteFunction`. The entire list of attributes are listed in the `saved_model._LayerAttributes` class. """ # Create a dictionary containing the layer's call and loss functions. fns = (saved_model.serialize_all_attributes(self, serialization_cache) .functions_to_serialize) # The parent Autotrackable class saves all user-defined tf.functions, and # returns them in _list_functions_for_serialization(). Add these functions # to the dict. fns.update(super(Layer, self)._list_functions_for_serialization( serialization_cache)) return fns @property def _unique_trainable_weights(self): """Dedupe trainable weights while maintaining order as much as possible.""" trainable_weights = self.trainable_weights output, seen_weights = [], set() for w in trainable_weights: if w not in seen_weights: output.append(w) seen_weights.add(w) return output class TensorFlowOpLayer(Layer): """Wraps a TensorFlow Operation in a Layer. This class is used internally by the Functional API. When a user uses a raw TensorFlow Operation on symbolic tensors originating from an `Input` Layer, the resultant operation will be wrapped with this Layer object in order to make the operation compatible with the Keras API. This Layer will create a new, identical operation (except for inputs and outputs) every time it is called. If `run_eagerly` is `True`, the op creation and calculation will happen inside an Eager function. Instances of this Layer are created when `autolambda` is called, which is whenever a Layer's `__call__` encounters symbolic inputs that do not have Keras metadata, or when a Network's `__init__` encounters outputs that do not have Keras metadata. Attributes: node_def: String, the serialized NodeDef of the Op this layer will wrap. name: String, the name of the Layer. constants: Dict of NumPy arrays, the values of any Tensors needed for this Operation that do not originate from a Keras `Input` Layer. Since all placeholders must come from Keras `Input` Layers, these Tensors must be treated as constant in the Functional API. trainable: Bool, whether this Layer is trainable. Currently Variables are not supported, and so this parameter has no effect. dtype: The default dtype of this Layer. Inherited from `Layer` and has no effect on this class, however is used in `get_config`. """ def __init__(self, node_def, name, constants=None, trainable=True, dtype=None): super(TensorFlowOpLayer, self).__init__( name=_TF_OP_LAYER_NAME_PREFIX + name, trainable=trainable, dtype=dtype) if not isinstance(node_def, bytes): node_def = node_def.encode('utf-8') self.node_def = node_def_pb2.NodeDef.FromString(node_def) # JSON serialization stringifies keys which are integer input indices. self.constants = ({ int(index): constant for index, constant in constants.items() } if constants is not None else {}) # Layer uses original op unless it is called on new inputs. # This means `built` is not set in `__call__`. self.built = True def call(self, inputs): if context.executing_eagerly(): return self._defun_call(inputs) return self._make_op(inputs) def _make_node_def(self, graph): node_def = node_def_pb2.NodeDef() node_def.CopyFrom(self.node_def) node_def.name = graph.unique_name(node_def.name) return node_def def _make_op(self, inputs): inputs = nest.flatten(inputs) graph = inputs[0].graph node_def = self._make_node_def(graph) with graph.as_default(): for index, constant in self.constants.items(): # Recreate constant in graph to add distribution context. value = tensor_util.constant_value(constant) if value is not None: constant = constant_op.constant(value, name=node_def.input[index]) inputs.insert(index, constant) # Check for case where first input should be a list of Tensors. if 'N' in node_def.attr: num_tensors = node_def.attr['N'].i inputs = [inputs[:num_tensors]] + inputs[num_tensors:] c_op = ops._create_c_op(graph, node_def, inputs, control_inputs=[]) op = graph._create_op_from_tf_operation(c_op) op._control_flow_post_processing() # Record the gradient because custom-made ops don't go through the # code-gen'd eager call path op_type = compat.as_str(op.op_def.name) attr_names = [compat.as_str(attr.name) for attr in op.op_def.attr] attrs = [] for attr_name in attr_names: attrs.append(attr_name) attrs.append(op.get_attr(attr_name)) attrs = tuple(attrs) execute.record_gradient(op_type, op.inputs, attrs, op.outputs, op.name) if len(op.outputs) == 1: return op.outputs[0] return op.outputs @function.defun def _defun_call(self, inputs): """Wraps the op creation method in an Eager function for `run_eagerly`.""" return self._make_op(inputs) def get_config(self): config = super(TensorFlowOpLayer, self).get_config() config.update({ # `__init__` prefixes the name. Revert to the constructor argument. 'name': config['name'][len(_TF_OP_LAYER_NAME_PREFIX):], 'node_def': self.node_def.SerializeToString().decode('utf-8'), 'constants': { i: backend.get_value(c) for i, c in self.constants.items() } }) return config class AddLoss(Layer): """Adds its inputs as a loss. Attributes: unconditional: Whether or not the loss should be conditioned on the inputs. """ def __init__(self, unconditional, **kwargs): super(AddLoss, self).__init__(**kwargs) self.unconditional = unconditional def call(self, inputs): self.add_loss(inputs, inputs=(not self.unconditional)) return inputs def get_config(self): config = super(AddLoss, self).get_config() config.update({'unconditional': self.unconditional}) return config class AddMetric(Layer): """Adds its inputs as a metric. Attributes: aggregation: 'mean' or None. How the inputs should be aggregated. metric_name: The name to use for this metric. """ def __init__(self, aggregation=None, metric_name=None, **kwargs): super(AddMetric, self).__init__(**kwargs) self.aggregation = aggregation self.metric_name = metric_name def call(self, inputs): self.add_metric(inputs, self.aggregation, self.metric_name) return inputs def get_config(self): config = super(AddMetric, self).get_config() config.update({ 'aggregation': self.aggregation, 'metric_name': self.metric_name }) return config class KerasHistory( collections.namedtuple('KerasHistory', ['layer', 'node_index', 'tensor_index'])): """Tracks the Layer call that created a Tensor, for Keras Graph Networks. During construction of Keras Graph Networks, this metadata is added to each Tensor produced as the output of a Layer, starting with an `InputLayer`. This allows Keras to track how each Tensor was produced, and this information is later retraced by the `keras.engine.Network` class to reconstruct the Keras Graph Network. Attributes: layer: The Layer that produced the Tensor. node_index: The specific call to the Layer that produced this Tensor. Layers can be called multiple times in order to share weights. A new node is created every time a Tensor is called. tensor_index: The output index for this Tensor. Always zero if the Layer that produced this Tensor only has one output. Nested structures of Tensors are deterministically assigned an index via `nest.flatten`. """ # Added to maintain memory and performance characteristics of `namedtuple` # while subclassing. __slots__ = () # Avoid breaking users who directly import this symbol from this file. # TODO(fchollet): remove this. InputSpec = input_spec.InputSpec # pylint:disable=invalid-name
40.083529
111
0.679356
58224f09156547002a94ed10da4c14b307ab6c92
1,035
py
Python
codebase_dump/download_notes.py
Hipo/codebase-ultra
6dbb8424809350cced5926f491da0ee9fe0b32f4
[ "MIT" ]
null
null
null
codebase_dump/download_notes.py
Hipo/codebase-ultra
6dbb8424809350cced5926f491da0ee9fe0b32f4
[ "MIT" ]
2
2019-09-27T15:29:33.000Z
2020-06-05T23:10:16.000Z
codebase_dump/download_notes.py
Hipo/codebase-ultra
6dbb8424809350cced5926f491da0ee9fe0b32f4
[ "MIT" ]
null
null
null
import sys import os import time import requests from pathlib import Path USER = os.environ['CODEBASE_USER'] PASSWORD = os.environ['CODEBASE_PASSWORD'] session = requests.sessions.Session() session.auth = (USER, PASSWORD) session.headers['Accept'] = 'application/xml' project = sys.argv[1] project_path = Path(__file__).parent / Path(project) tickets_path = project_path / 'tickets' notes_path = project_path / 'notes' notes_path.mkdir(exist_ok=True, parents=True) note_ticket_ids = set(s.name.split('.')[0] for s in notes_path.glob('*.xml')) ticket_ids = [s.name.split('.')[0] for s in tickets_path.glob('*.xml')] ticket_ids = [ticket_id for ticket_id in ticket_ids if ticket_id not in note_ticket_ids] ticket_ids = sorted(ticket_ids, key=int, reverse=True) for ticket_id in ticket_ids: r = session.get(f'https://api3.codebasehq.com/{project}/tickets/{ticket_id}/notes') r.raise_for_status() print(ticket_id) with open(notes_path / f'{ticket_id}.xml', 'w') as f: f.write(r.text) time.sleep(0.2)
27.236842
88
0.724638
1c11c78c290ed54c3326cd3a1508c9417f3a7d43
10,061
py
Python
manimlib/mobject/svg/text_mobject.py
Ermaotie/manim
b25e446042571bf80b47198adfe230e0cb1b9637
[ "MIT" ]
1
2021-07-11T21:38:13.000Z
2021-07-11T21:38:13.000Z
manimlib/mobject/svg/text_mobject.py
Ermaotie/manim
b25e446042571bf80b47198adfe230e0cb1b9637
[ "MIT" ]
null
null
null
manimlib/mobject/svg/text_mobject.py
Ermaotie/manim
b25e446042571bf80b47198adfe230e0cb1b9637
[ "MIT" ]
null
null
null
import copy import hashlib import os import re import typing import warnings from contextlib import contextmanager from pathlib import Path import manimpango from manimlib.constants import * from manimlib.mobject.geometry import Dot from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.config_ops import digest_config from manimlib.utils.customization import get_customization from manimlib.utils.directories import get_downloads_dir, get_text_dir from manimpango import PangoUtils from manimpango import TextSetting TEXT_MOB_SCALE_FACTOR = 0.0076 DEFAULT_LINE_SPACING_SCALE = 0.3 class Text(SVGMobject): CONFIG = { # Mobject "color": WHITE, "height": None, "stroke_width": 0, # Text "font": '', "gradient": None, "lsh": -1, "size": None, "font_size": 48, "tab_width": 4, "slant": NORMAL, "weight": NORMAL, "t2c": {}, "t2f": {}, "t2g": {}, "t2s": {}, "t2w": {}, "disable_ligatures": True, } def __init__(self, text, **config): self.full2short(config) digest_config(self, config) if self.size: warnings.warn( "self.size has been deprecated and will " "be removed in future.", DeprecationWarning ) self.font_size = self.size if self.lsh == -1: self.lsh = self.font_size + self.font_size * DEFAULT_LINE_SPACING_SCALE else: self.lsh = self.font_size + self.font_size * self.lsh text_without_tabs = text if text.find('\t') != -1: text_without_tabs = text.replace('\t', ' ' * self.tab_width) self.text = text_without_tabs file_name = self.text2svg() PangoUtils.remove_last_M(file_name) self.remove_empty_path(file_name) SVGMobject.__init__(self, file_name, **config) self.text = text if self.disable_ligatures: self.apply_space_chars() if self.t2c: self.set_color_by_t2c() if self.gradient: self.set_color_by_gradient(*self.gradient) if self.t2g: self.set_color_by_t2g() # anti-aliasing if self.height is None: self.scale(TEXT_MOB_SCALE_FACTOR) # Just a temporary hack to get better triangulation # See pr #1552 for details for i in self.submobjects: i.insert_n_curves(len(i.get_points())) def remove_empty_path(self, file_name): with open(file_name, 'r') as fpr: content = fpr.read() content = re.sub(r'<path .*?d=""/>', '', content) with open(file_name, 'w') as fpw: fpw.write(content) def apply_space_chars(self): submobs = self.submobjects.copy() for char_index in range(len(self.text)): if self.text[char_index] in [" ", "\t", "\n"]: space = Dot(radius=0, fill_opacity=0, stroke_opacity=0) space.move_to(submobs[max(char_index - 1, 0)].get_center()) submobs.insert(char_index, space) self.set_submobjects(submobs) def find_indexes(self, word): m = re.match(r'\[([0-9\-]{0,}):([0-9\-]{0,})\]', word) if m: start = int(m.group(1)) if m.group(1) != '' else 0 end = int(m.group(2)) if m.group(2) != '' else len(self.text) start = len(self.text) + start if start < 0 else start end = len(self.text) + end if end < 0 else end return [(start, end)] indexes = [] index = self.text.find(word) while index != -1: indexes.append((index, index + len(word))) index = self.text.find(word, index + len(word)) return indexes def get_parts_by_text(self, word): return VGroup(*( self[i:j] for i, j in self.find_indexes(word) )) def get_part_by_text(self, word): parts = self.get_parts_by_text(word) if len(parts) > 0: return parts[0] else: return None def full2short(self, config): for kwargs in [config, self.CONFIG]: if kwargs.__contains__('line_spacing_height'): kwargs['lsh'] = kwargs.pop('line_spacing_height') if kwargs.__contains__('text2color'): kwargs['t2c'] = kwargs.pop('text2color') if kwargs.__contains__('text2font'): kwargs['t2f'] = kwargs.pop('text2font') if kwargs.__contains__('text2gradient'): kwargs['t2g'] = kwargs.pop('text2gradient') if kwargs.__contains__('text2slant'): kwargs['t2s'] = kwargs.pop('text2slant') if kwargs.__contains__('text2weight'): kwargs['t2w'] = kwargs.pop('text2weight') def set_color_by_t2c(self, t2c=None): t2c = t2c if t2c else self.t2c for word, color in list(t2c.items()): for start, end in self.find_indexes(word): self[start:end].set_color(color) def set_color_by_t2g(self, t2g=None): t2g = t2g if t2g else self.t2g for word, gradient in list(t2g.items()): for start, end in self.find_indexes(word): self[start:end].set_color_by_gradient(*gradient) def text2hash(self): settings = self.font + self.slant + self.weight settings += str(self.t2f) + str(self.t2s) + str(self.t2w) settings += str(self.lsh) + str(self.font_size) id_str = self.text + settings hasher = hashlib.sha256() hasher.update(id_str.encode()) return hasher.hexdigest()[:16] def text2settings(self): settings = [] t2x = [self.t2f, self.t2s, self.t2w] for i in range(len(t2x)): fsw = [self.font, self.slant, self.weight] if t2x[i]: for word, x in list(t2x[i].items()): for start, end in self.find_indexes(word): fsw[i] = x settings.append(TextSetting(start, end, *fsw)) # Set All text settings(default font slant weight) fsw = [self.font, self.slant, self.weight] settings.sort(key=lambda setting: setting.start) temp_settings = settings.copy() start = 0 for setting in settings: if setting.start != start: temp_settings.append(TextSetting(start, setting.start, *fsw)) start = setting.end if start != len(self.text): temp_settings.append(TextSetting(start, len(self.text), *fsw)) settings = sorted(temp_settings, key=lambda setting: setting.start) if re.search(r'\n', self.text): line_num = 0 for start, end in self.find_indexes('\n'): for setting in settings: if setting.line_num == -1: setting.line_num = line_num if start < setting.end: line_num += 1 new_setting = copy.copy(setting) setting.end = end new_setting.start = end new_setting.line_num = line_num settings.append(new_setting) settings.sort(key=lambda setting: setting.start) break for setting in settings: if setting.line_num == -1: setting.line_num = 0 return settings def text2svg(self): # anti-aliasing size = self.font_size lsh = self.lsh if self.font == '': self.font = get_customization()['style']['font'] dir_name = get_text_dir() hash_name = self.text2hash() file_name = os.path.join(dir_name, hash_name) + '.svg' if os.path.exists(file_name): return file_name settings = self.text2settings() width = DEFAULT_PIXEL_WIDTH height = DEFAULT_PIXEL_HEIGHT disable_liga = self.disable_ligatures return manimpango.text2svg( settings, size, lsh, disable_liga, file_name, START_X, START_Y, width, height, self.text, ) @contextmanager def register_font(font_file: typing.Union[str, Path]): """Temporarily add a font file to Pango's search path. This searches for the font_file at various places. The order it searches it described below. 1. Absolute path. 2. Downloads dir. Parameters ---------- font_file : The font file to add. Examples -------- Use ``with register_font(...)`` to add a font file to search path. .. code-block:: python with register_font("path/to/font_file.ttf"): a = Text("Hello", font="Custom Font Name") Raises ------ FileNotFoundError: If the font doesn't exists. AttributeError: If this method is used on macOS. Notes ----- This method of adding font files also works with :class:`CairoText`. .. important :: This method is available for macOS for ``ManimPango>=v0.2.3``. Using this method with previous releases will raise an :class:`AttributeError` on macOS. """ input_folder = Path(get_downloads_dir()).parent.resolve() possible_paths = [ Path(font_file), input_folder / font_file, ] for path in possible_paths: path = path.resolve() if path.exists(): file_path = path break else: error = f"Can't find {font_file}." f"Tried these : {possible_paths}" raise FileNotFoundError(error) try: assert manimpango.register_font(str(file_path)) yield finally: manimpango.unregister_font(str(file_path))
33.875421
96
0.567439
27ec7afefaa4a9d4bc9a17f25af223fb37eb65c2
252
py
Python
homeassistant/components/ambient_station/const.py
shanbs/home-assistant
818776d2b4f11e4f51992dc88bc0a6f9055833b2
[ "Apache-2.0" ]
4
2019-07-03T22:36:57.000Z
2019-08-10T15:33:25.000Z
homeassistant/components/ambient_station/const.py
shanbs/home-assistant
818776d2b4f11e4f51992dc88bc0a6f9055833b2
[ "Apache-2.0" ]
7
2019-08-23T05:26:02.000Z
2022-03-11T23:57:18.000Z
homeassistant/components/ambient_station/const.py
shanbs/home-assistant
818776d2b4f11e4f51992dc88bc0a6f9055833b2
[ "Apache-2.0" ]
3
2019-04-28T16:35:45.000Z
2020-05-28T15:21:59.000Z
"""Define constants for the Ambient PWS component.""" DOMAIN = 'ambient_station' ATTR_LAST_DATA = 'last_data' CONF_APP_KEY = 'app_key' DATA_CLIENT = 'data_client' TOPIC_UPDATE = 'update' TYPE_BINARY_SENSOR = 'binary_sensor' TYPE_SENSOR = 'sensor'
18
53
0.757937
c7fb75387aa31cab0cda67d020739f0ed48db823
610,380
py
Python
python/paddle/fluid/layers/nn.py
WeiLi233/Paddle
3d2ec707185c351943446f35a45db425e3be1b53
[ "Apache-2.0" ]
2
2022-01-04T10:51:58.000Z
2022-01-10T12:29:08.000Z
python/paddle/fluid/layers/nn.py
WeiLi233/Paddle
3d2ec707185c351943446f35a45db425e3be1b53
[ "Apache-2.0" ]
1
2020-09-08T01:45:28.000Z
2020-09-08T01:45:28.000Z
python/paddle/fluid/layers/nn.py
WeiLi233/Paddle
3d2ec707185c351943446f35a45db425e3be1b53
[ "Apache-2.0" ]
5
2021-12-10T11:20:06.000Z
2022-02-18T05:18:12.000Z
# Copyright (c) 2018 PaddlePaddle Authors. 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. """ All layers just related to the neural network. """ from __future__ import print_function import os import inspect import warnings import numpy as np import six import paddle from ..layer_helper import LayerHelper from ..initializer import Normal, Constant, NumpyArrayInitializer from ..framework import Variable, OpProtoHolder, in_dygraph_mode, dygraph_only, _dygraph_tracer, default_main_program, _varbase_creator, static_only, _global_flags from .. import dygraph_utils from ..param_attr import ParamAttr from .layer_function_generator import autodoc, templatedoc, _generate_doc_string_ from .tensor import concat, assign, fill_constant, zeros, tensor_array_to_tensor from . import utils from .. import unique_name from functools import reduce from .. import core from ...utils import deprecated from ..data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype import paddle from paddle.utils import deprecated from paddle import _C_ops __all__ = [ 'fc', 'embedding', 'linear_chain_crf', 'crf_decoding', 'cos_sim', 'chunk_eval', 'conv2d', 'conv3d', 'softmax', 'pool2d', 'pool3d', 'adaptive_pool2d', 'adaptive_pool3d', 'batch_norm', 'inplace_abn', 'instance_norm', 'data_norm', 'conv2d_transpose', 'conv3d_transpose', 'reduce_sum', 'reduce_mean', 'reduce_max', 'reduce_min', 'reduce_prod', 'reduce_all', 'reduce_any', 'dropout', 'split', 'ctc_greedy_decoder', 'l2_normalize', 'matmul', 'topk', 'transpose', 'im2sequence', 'row_conv', 'multiplex', 'layer_norm', 'group_norm', 'spectral_norm', 'smooth_l1', 'one_hot', 'autoincreased_step_counter', 'reshape', 'squeeze', 'unsqueeze', 'lod_reset', 'lod_append', 'lrn', 'pad', 'pad_constant_like', 'label_smooth', 'roi_pool', 'roi_align', 'dice_loss', 'image_resize', 'image_resize_short', 'resize_linear', 'resize_bilinear', 'resize_trilinear', 'resize_nearest', 'gather', 'gather_nd', 'scatter', 'scatter_nd_add', 'scatter_nd', 'random_crop', 'mean_iou', 'relu', 'selu', 'log', 'crop', 'crop_tensor', 'elu', 'relu6', 'pow', 'stanh', 'hard_sigmoid', 'swish', 'prelu', 'brelu', 'leaky_relu', 'soft_relu', 'flatten', 'stack', 'pad2d', 'unstack', 'unique', 'unique_with_counts', 'expand', 'expand_as', 'scale', 'elementwise_add', 'elementwise_div', 'elementwise_sub', 'elementwise_mul', 'elementwise_max', 'elementwise_min', 'elementwise_pow', 'elementwise_mod', 'elementwise_floordiv', 'uniform_random_batch_size_like', 'gaussian_random', 'sampling_id', 'gaussian_random_batch_size_like', 'sum', 'slice', 'strided_slice', 'shape', 'rank', 'size', 'logical_and', 'logical_or', 'logical_xor', 'logical_not', 'clip', 'clip_by_norm', 'mean', 'mul', 'maxout', 'space_to_depth', 'affine_grid', 'affine_channel', 'similarity_focus', 'hash', 'grid_sampler', 'log_loss', 'add_position_encoding', 'bilinear_tensor_product', 'merge_selected_rows', 'get_tensor_from_selected_rows', 'shuffle_channel', 'temporal_shift', 'py_func', 'psroi_pool', 'prroi_pool', 'pixel_shuffle', 'fsp_matrix', 'continuous_value_model', 'where', 'sign', 'deformable_conv', 'unfold', 'deformable_roi_pooling', 'filter_by_instag', 'shard_index', 'hard_swish', 'mish', 'gather_tree', 'uniform_random', 'unbind', ] @dygraph_only def _elementwise_op_in_dygraph(x, y, axis=-1, act=None, use_mkldnn=False, op_name=None): op = getattr(_C_ops, op_name) out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn) return dygraph_utils._append_activation_in_dygraph( out, act, use_mkldnn=use_mkldnn) def fc(input, size, num_flatten_dims=1, param_attr=None, bias_attr=None, act=None, name=None): r""" :api_attr: Static Graph **Fully Connected Layer** This operator creates a fully connected layer in the network. It can take a Tensor(or LoDTensor) or a list of Tensor(or LoDTensor) as its inputs(see Args in detail). It creates a variable called weight for each input Tensor, which represents a fully connected weight matrix from each input unit to each output unit. The fully connected layer multiplies each input Tensor with its corresponding weight to produce an output Tensor with shape :math:`[M, size]` , where M is batch size. If a list of Tensor is given, the results of multiple output Tensors with shape :math:`[M, size]` will be summed up. If :attr:`bias_attr` is not None, a bias variable will be created and added to the output. Finally, if :attr:`act` is not None, it will be applied to the output as well. When the input is a single Tensor(or LoDTensor): .. math:: Out = Act({XW + b}) When the input is a list of Tensor(or LoDTensor): .. math:: Out = Act({\sum_{i=0}^{N-1}X_iW_i + b}) In the above equation: * :math:`N`: Number of the input. N equals to len(input) if input is list of Variable. * :math:`X_i`: The i-th input tensor. * :math:`W_i`: The i-th weights matrix corresponding i-th input tensor. * :math:`b`: The bias parameter created by this layer (if needed). * :math:`Act`: The activation function. * :math:`Out`: The output Tensor. .. code-block:: text Case 1: Given a single Tensor data_1, and num_flatten_dims = 2: data_1.data = [[[0.1, 0.2], [0.3, 0.4]]] data_1.shape = (1, 2, 2) # 1 is batch_size out = fluid.layers.fc(input=data_1, size=1, num_flatten_dims=2) Then output is: out.data = [[0.83234344], [0.34936576]] out.shape = (1, 2, 1) Case 2: Given a list of Tensor: data_1.data = [[[0.1, 0.2], [0.3, 0.4]]] data_1.shape = (1, 2, 2) # 1 is batch_size data_2 = [[[0.1, 0.2, 0.3]]] data_2.shape = (1, 1, 3) out = fluid.layers.fc(input=[data_1, data_2], size=2) Then: out.data = [[0.18669507, 0.1893476]] out.shape = (1, 2) Args: input (Variable|list of Variable): A Tensor(or LoDTensor) with shape :math:`[N_1, N_2,..., N_k]` or a list of Tensor(or LoDTensor). The dimensions of the input Tensor is at least 2 and the data type should be float32 or float64. size(int): The number of output units in this layer, which also means the feature size of output Tensor(or LoDTensor). num_flatten_dims (int): The fc layer can accept an input Tensor with more than two dimensions. If this happens, the multidimensional tensor will first be flattened into a 2-D matrix. The parameter :attr:`num_flatten_dims` determines how the input Tensor is flattened: the first :attr:`num_flatten_dims` (inclusive, index starts from 1) dimensions will be flatten to form the first dimension of the final matrix (height of the matrix), and the rest :math:`rank(X) - num\_flatten\_dims` dimensions are flattened to form the second dimension of the final matrix (width of the matrix). For example, assuming that X is a 5-dimensional Tensor with a shape [2, 3, 4, 5, 6], and :attr:`num_flatten_dims` = 3. Then, the flattened matrix will have a shape [2 x 3 x 4, 5 x 6] = [24, 30]. Default: 1. param_attr (ParamAttr): To specify the weight parameter property. Default: None, which means the default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . bias_attr (ParamAttr): To specify the bias parameter property. Default: None, which means the default bias parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . act (str): Activation to be applied to the output of this layer, such as tanh, softmax, sigmoid, relu. For more information, please refer to :ref:`api_guide_activations_en` . Default: None. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Variable: Tensor or LoDTensor calculated by fc layer. The data type is same with input. Raises: ValueError: If dimensions of the input Tensor is less than 2. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() # when input is single tensor data = fluid.data(name="data", shape=[-1, 32], dtype="float32") fc = fluid.layers.fc(input=data, size=1000, act="tanh") # when input are multiple tensors data_1 = fluid.data(name="data_1", shape=[-1, 32], dtype="float32") data_2 = fluid.data(name="data_2", shape=[-1, 36], dtype="float32") fc = fluid.layers.fc(input=[data_1, data_2], size=1000, act="tanh") """ helper = LayerHelper("fc", **locals()) check_type(input, 'input', (list, tuple, Variable), 'fc') if isinstance(input, (list, tuple)): for i, input_x in enumerate(input): check_type(input_x, 'input[' + str(i) + ']', Variable, 'fc') dtype = helper.input_dtype() check_dtype(dtype, 'input', ['float16', 'uint16', 'float32', 'float64'], 'fc') mul_results = [] for input_var, param_attr in helper.iter_inputs_and_params(): input_shape = input_var.shape if num_flatten_dims == -1: num_flatten_dims = len(input_shape) - 1 param_shape = [ reduce(lambda a, b: a * b, input_shape[num_flatten_dims:], 1) ] + [size] w = helper.create_parameter( attr=param_attr, shape=param_shape, dtype=dtype, is_bias=False) tmp = helper.create_variable_for_type_inference(dtype) helper.append_op( type="mul", inputs={"X": input_var, "Y": w}, outputs={"Out": tmp}, attrs={"x_num_col_dims": num_flatten_dims, "y_num_col_dims": 1}) mul_results.append(tmp) if len(mul_results) == 1: pre_bias = mul_results[0] else: pre_bias = helper.create_variable_for_type_inference(dtype) helper.append_op( type="sum", inputs={"X": mul_results}, outputs={"Out": pre_bias}, attrs={"use_mkldnn": False}) # add bias pre_activation = helper.append_bias_op(pre_bias, dim_start=num_flatten_dims) # add activation return helper.append_activation(pre_activation) @deprecated(since="2.0.0", update_to="paddle.nn.functional.embedding") def embedding(input, size, is_sparse=False, is_distributed=False, padding_idx=None, param_attr=None, dtype='float32'): r""" :api_attr: Static Graph **WARING:** This OP will be deprecated in a future release. This OP requires the last dimension of Tensor shape must be equal to 1. It is recommended to use fluid. :ref:`api_fluid_embedding` . The operator is used to lookup embeddings vector of ids provided by :attr:`input` . It automatically constructs a 2D embedding matrix based on the input :attr:`size` (vocab_size, emb_size) and :attr:`dtype` . This OP requires the last dimension of Tensor shape must be equal to 1. The shape of output Tensor is generated by replacing the last dimension of the input Tensor shape with emb_size. **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` , otherwise the program will throw an exception and exit. .. code-block:: text Case 1: input is a Tensor. padding_idx = -1 input.data = [[[1], [3]], [[2], [4]], [[4], [127]]] input.shape = [3, 2, 1] Given size = [128, 16] output is a Tensor: out.shape = [3, 2, 16] out.data = [[[0.129435295, 0.244512452, ..., 0.436322452], [0.345421456, 0.524563927, ..., 0.144534654]], [[0.345249859, 0.124939536, ..., 0.194353745], [0.945345345, 0.435394634, ..., 0.435345365]], [[0.945345345, 0.435394634, ..., 0.435345365], [0.0, 0.0, ..., 0.0 ]]] # padding data The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127 It will pad all-zero data when ids is 127. Case 2: input is a LoDTensor with 1-level LoD. padding_idx = 0 input.lod = [[2, 3]] input.data = [[1], [3], [2], [4], [0]] input.shape = [5, 1] Given size = [128, 16] output is a LoDTensor: out.lod = [[2, 3]] out.shape = [5, 16] out.data = [[0.129435295, 0.244512452, ..., 0.436322452], [0.345421456, 0.524563927, ..., 0.144534654], [0.345249859, 0.124939536, ..., 0.194353745], [0.945345345, 0.435394634, ..., 0.435345365], [0.0, 0.0, ..., 0.0 ]] # padding data It will pad all-zero data when ids is 0. Args: input(Variable): A Tensor or LoDTensor with type int64, which contains the id information. The last dimension of Tensor shape must be equal to 1. The value of the input id should satisfy :math:`0<= id < size[0]` . size(tuple|list): The shape of lookup table parameter. It should have two elements which indicates the size of the dictionary of embeddings and the size of each embedding vector respectively. is_sparse(bool): The flag indicating whether to use sparse update. This parameter only affects the performance of the backwards gradient update. It is recommended to set True because sparse update is faster. But some optimizer does not support sparse update, such as :ref:`api_fluid_optimizer_AdadeltaOptimizer` , :ref:`api_fluid_optimizer_AdamaxOptimizer` , :ref:`api_fluid_optimizer_DecayedAdagradOptimizer` , :ref:`api_fluid_optimizer_FtrlOptimizer` , :ref:`api_fluid_optimizer_LambOptimizer` and :ref:`api_fluid_optimizer_LarsMomentumOptimizer` . In these case, is_sparse must be False. Default: False. is_distributed(bool): Whether to store the embedding matrix in a distributed manner. Only used in multi-machine distributed CPU training. Default: False. padding_idx(int|long|None): padding_idx needs to be in the interval [-vocab_size, vocab_size). If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever lookup encounters :math:`padding\_idx` in id. And the padding data will not be updated while training. If set None, it makes no effect to output. Default: None. param_attr(ParamAttr): To specify the weight parameter property. Default: None, which means the default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . In addition, user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter. The local word vector needs to be transformed into numpy format, and the shape of local word vector should be consistent with :attr:`size` . Then :ref:`api_fluid_initializer_NumpyArrayInitializer` is used to load custom or pre-trained word vectors. See code example 2 for details. dtype(str|core.VarDesc.VarType): It refers to the data type of output Tensor. It must be float32 or float64. Default: float32. Returns: Variable: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` . Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle paddle.enable_static() data = fluid.data(name='x', shape=[None, 1], dtype='int64') # example 1 emb_1 = fluid.embedding(input=data, size=[128, 64]) # example 2: load custom or pre-trained word vectors weight_data = np.random.random(size=(128, 100)) # word vectors with numpy format w_param_attrs = fluid.ParamAttr( name="emb_weight", learning_rate=0.5, initializer=fluid.initializer.NumpyArrayInitializer(weight_data), trainable=True) emb_2 = fluid.layers.embedding(input=data, size=(128, 100), param_attr=w_param_attrs, dtype='float32') """ helper = LayerHelper('embedding', **locals()) check_variable_and_dtype(input, 'input', ['int64'], 'fluid.layers.embedding') check_dtype(dtype, 'dtype', ['uint16', 'float16', 'float32', 'float64'], 'fluid.layers.embedding') if is_distributed: is_distributed = False warnings.warn( "is_distributed is go out of use, `fluid.contrib.layers.sparse_embedding` is your needed" ) remote_prefetch = True if is_sparse else False w = helper.create_parameter( attr=helper.param_attr, shape=size, dtype=dtype, is_bias=False) tmp = helper.create_variable_for_type_inference(dtype) padding_idx = -1 if padding_idx is None else padding_idx if padding_idx >= 0 else ( size[0] + padding_idx) helper.append_op( type='lookup_table', inputs={'Ids': input, 'W': w}, outputs={'Out': tmp}, attrs={ 'is_sparse': is_sparse, 'is_distributed': is_distributed, 'remote_prefetch': remote_prefetch, 'padding_idx': padding_idx }) return tmp def _pull_sparse(input, size, table_id, accessor_class, name="embedding", ctr_label_name="", padding_id=0, dtype='float32', scale_sparse_grad=True): r""" **Pull Fleet Sparse Layer** This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in Fleet lookup table. The result of this lookup is the embedding of each ID in the :attr:`input`. Args: input(Variable|list of Variable): Input is a Tensor<int64> Variable, which contains the IDs information. size(int): The embedding size parameter, which indicates the size of each embedding vector respectively. table_id(int): the fleet table id of this embedding. accessor_class(str): the pslib accessor of the table, default is DownpourCtrAccessor. ctr_label_name(str): the layer name of click. padding_id(int): the padding id during lookup, default is 0. dtype(str): The dtype refers to the data type of output tensor. Only supports float32 now. scale_sparse_grad(bool): whether to scale sparse gradient with batch size. default is True. Returns: Variable|list of Variable: The tensor variable storing the embeddings of the \ supplied inputs. Examples: .. code-block:: python import paddle.fluid as fluid data = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1) emb = fluid.layers.nn._pull_sparse( input=data, size=11, table_id=0, accessor_class="DownpourCtrAccessor") """ helper = LayerHelper(name, **locals()) inputs = helper.multiple_input() outs = [helper.create_variable_for_type_inference(dtype)] input_names = [i.name for i in inputs] attrs = { 'EmbeddingDim': size, 'TableId': table_id, 'AccessorClass': accessor_class, 'CtrLabelName': ctr_label_name, 'PaddingId': padding_id, 'ScaleSparseGrad': scale_sparse_grad, 'InputNames': input_names, # this is only for compatible with embedding op 'is_distributed': True } # this is only for compatible with embedding op w, _ = helper.create_or_get_global_variable( name=name, shape=[size], dtype=dtype, is_bias=False, persistable=True) helper.append_op( type='pull_sparse', inputs={'Ids': inputs, 'W': w}, outputs={'Out': outs}, attrs=attrs) if len(outs) == 1: return outs[0] return outs def _pull_sparse_v2(input, size, table_id, accessor_class, name="embedding", ctr_label_name="", padding_id=0, dtype='float32', scale_sparse_grad=True): r""" **Pull Fleet Sparse Layer** This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in Fleet lookup table. The result of this lookup is the embedding of each ID in the :attr:`input`. Args: input(Variable|list of Variable): Input is a Tensor<int64> Variable, which contains the IDs information. size(int): The embedding size parameter, which indicates the size of each embedding vector respectively. table_id(int): the pslib table id of this embedding. accessor_class(str): the fleet accessor of the table, default is DownpourCtrAccessor. ctr_label_name(str): the layer name of click. padding_id(int): the padding id during lookup, default is 0. dtype(str): The dtype refers to the data type of output tensor. Only supports float32 now. scale_sparse_grad(bool): whether to scale sparse gradient with batch size. default is True. Returns: Variable|list of Variable: The tensor variable storing the embeddings of the \ supplied inputs. Examples: .. code-block:: python import paddle.fluid as fluid data = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1) emb = fluid.layers.nn._pull_sparse_v2( input=data, size=11, table_id=0, accessor_class="DownpourCtrAccessor") """ helper = LayerHelper(name, **locals()) inputs = helper.multiple_input() outs = [helper.create_variable_for_type_inference(dtype)] input_names = [i.name for i in inputs] attrs = { 'EmbeddingDim': size, 'TableId': table_id, 'AccessorClass': accessor_class, 'CtrLabelName': ctr_label_name, 'PaddingId': padding_id, 'ScaleSparseGrad': scale_sparse_grad, 'InputNames': input_names, # this is only for compatible with embedding op 'is_distributed': True } # this is only for compatible with embedding op w, _ = helper.create_or_get_global_variable( name=name, shape=[size], dtype=dtype, is_bias=False, persistable=True) helper.append_op( type='pull_sparse_v2', inputs={'Ids': inputs, 'W': w}, outputs={'Out': outs}, attrs=attrs) if len(outs) == 1: return outs[0] return outs def _pull_box_sparse(input, size, dtype='float32', is_distributed=False, is_sparse=False): r""" **Pull Box Sparse Layer** This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in BoxPS lookup table. The result of this lookup is the embedding of each ID in the :attr:`input`. Args: input(Variable|list of Variable): Input is a Tensor<int64> Variable, which contains the IDs information. size(int): The embedding size parameter, which indicates the size of each embedding vector respectively. dtype(str): The dtype refers to the data type of output tensor. Only supports float32 now. Returns: Variable|list of Variable: The tensor variable storing the embeddings of the \ supplied inputs. Examples: .. code-block:: python import paddle.fluid as fluid data = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1) emb = fluid.layers.pull_box_sparse(input=data, size=[11]) """ helper = LayerHelper('pull_box_sparse', **locals()) if dtype != 'float32': raise ValueError( "BoxPS only support float type embedding now, and your type is: " + dtype) helper.input_dtype() inputs = helper.multiple_input() outs = [ helper.create_variable_for_type_inference(dtype) for i in range(len(inputs)) ] w = helper.create_parameter( attr=helper.param_attr, shape=[size], dtype=dtype, is_bias=False) helper.append_op( type='pull_box_sparse', inputs={'Ids': inputs, 'W': w}, outputs={'Out': outs}, attrs={ 'size': size, 'is_distributed': is_distributed, 'is_sparse': is_sparse }) if len(outs) == 1: return outs[0] return outs @templatedoc() def linear_chain_crf(input, label, param_attr=None, length=None): """ :api_attr: Static Graph Linear Chain CRF. ${comment} Args: input(${emission_type}): ${emission_comment} label(${label_type}): ${label_comment} Length(${length_type}): ${length_comment} param_attr(ParamAttr): The attribute of the learnable parameter for transition parameter. Returns: output(${emission_exps_type}): ${emission_exps_comment} \n output(${transition_exps_type}): ${transition_exps_comment} \n output(${log_likelihood_type}): ${log_likelihood_comment} \n Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle paddle.enable_static() #define net structure, using LodTensor train_program = fluid.Program() startup_program = fluid.Program() with fluid.program_guard(train_program, startup_program): input_data = fluid.data(name='input_data', shape=[-1,10], dtype='float32') label = fluid.data(name='label', shape=[-1,1], dtype='int') emission= fluid.layers.fc(input=input_data, size=10, act="tanh") crf_cost = fluid.layers.linear_chain_crf( input=emission, label=label, param_attr=fluid.ParamAttr( name='crfw', learning_rate=0.01)) use_cuda = False place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() exe = fluid.Executor(place) exe.run(startup_program) #define data, using LoDTensor a = fluid.create_lod_tensor(np.random.rand(12,10).astype('float32'), [[3,3,4,2]], place) b = fluid.create_lod_tensor(np.array([[1],[1],[2],[3],[1],[1],[1],[3],[1],[1],[1],[1]]),[[3,3,4,2]] , place) feed1 = {'input_data':a,'label':b} loss= exe.run(train_program,feed=feed1, fetch_list=[crf_cost]) print(loss) #define net structure, using padding train_program = fluid.Program() startup_program = fluid.Program() with fluid.program_guard(train_program, startup_program): input_data2 = fluid.data(name='input_data2', shape=[-1,10,10], dtype='float32') label2 = fluid.data(name='label2', shape=[-1,10,1], dtype='int') label_length = fluid.data(name='length', shape=[-1,1], dtype='int') emission2= fluid.layers.fc(input=input_data2, size=10, act="tanh", num_flatten_dims=2) crf_cost2 = fluid.layers.linear_chain_crf( input=emission2, label=label2, length=label_length, param_attr=fluid.ParamAttr( name='crfw', learning_rate=0.01)) use_cuda = False place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() exe = fluid.Executor(place) exe.run(startup_program) #define data, using padding cc=np.random.rand(4,10,10).astype('float32') dd=np.random.rand(4,10,1).astype('int64') ll=np.array([[3],[3],[4],[2]]) feed2 = {'input_data2':cc,'label2':dd,'length':ll} loss2= exe.run(train_program,feed=feed2, fetch_list=[crf_cost2]) print(loss2) #[array([[ 7.8902354], # [ 7.3602567], # [ 10.004011], # [ 5.86721 ]], dtype=float32)] #you can use find_var to get transition parameter. transition=np.array(fluid.global_scope().find_var('crfw').get_tensor()) print(transition) """ check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'linear_chain_crf') check_variable_and_dtype(label, 'label', ['int64'], 'linear_chain_crf') helper = LayerHelper('linear_chain_crf', **locals()) size = input.shape[2] if length else input.shape[1] transition = helper.create_parameter( attr=helper.param_attr, shape=[size + 2, size], dtype=helper.input_dtype()) alpha = helper.create_variable_for_type_inference( dtype=helper.input_dtype()) emission_exps = helper.create_variable_for_type_inference( dtype=helper.input_dtype()) transition_exps = helper.create_variable_for_type_inference( dtype=helper.input_dtype()) log_likelihood = helper.create_variable_for_type_inference( dtype=helper.input_dtype()) this_inputs = { "Emission": [input], "Transition": transition, "Label": [label] } if length: this_inputs['Length'] = [length] helper.append_op( type='linear_chain_crf', inputs=this_inputs, outputs={ "Alpha": [alpha], "EmissionExps": [emission_exps], "TransitionExps": transition_exps, "LogLikelihood": log_likelihood }) return log_likelihood @templatedoc() def crf_decoding(input, param_attr, label=None, length=None): """ :api_attr: Static Graph ${comment} Args: input(Tensor): ${emission_comment} param_attr (ParamAttr|None): To specify the weight parameter attribute. Default: None, which means the default weight parameter property is used. See usage for details in :ref:`api_paddle_fluid_param_attr_ParamAttr` . label(${label_type}, optional): ${label_comment} length(${length_type}, optional): ${length_comment} Returns: Tensor: ${viterbi_path_comment} Examples: .. code-block:: python import paddle paddle.enable_static() # LoDTensor-based example num_labels = 10 feature = paddle.static.data(name='word_emb', shape=[-1, 784], dtype='float32', lod_level=1) label = paddle.static.data(name='label', shape=[-1, 1], dtype='int64', lod_level=1) emission = paddle.static.nn.fc(feature, size=num_labels) crf_cost = paddle.fluid.layers.linear_chain_crf(input=emission, label=label, param_attr=paddle.ParamAttr(name="crfw")) crf_decode = paddle.static.nn.crf_decoding(input=emission, param_attr=paddle.ParamAttr(name="crfw")) # Common tensor example num_labels, max_len = 10, 20 feature = paddle.static.data(name='word_emb_pad', shape=[-1, max_len, 784], dtype='float32') label = paddle.static.data(name='label_pad', shape=[-1, max_len, 1], dtype='int64') length = paddle.static.data(name='length', shape=[-1, 1], dtype='int64') emission = paddle.static.nn.fc(feature, size=num_labels, num_flatten_dims=2) crf_cost = paddle.fluid.layers.linear_chain_crf(input=emission, label=label, length=length, param_attr=paddle.ParamAttr(name="crfw_pad")) crf_decode = paddle.static.nn.crf_decoding(input=emission, length=length, param_attr=paddle.ParamAttr(name="crfw_pad")) """ check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'crf_decoding') helper = LayerHelper('crf_decoding', **locals()) transition = helper.get_parameter(param_attr.name) viterbi_path = helper.create_variable_for_type_inference( dtype=core.VarDesc.VarType.INT64) inputs = {"Emission": [input], "Transition": transition, "Label": label} if length: inputs['Length'] = length helper.append_op( type='crf_decoding', inputs=inputs, outputs={"ViterbiPath": [viterbi_path]}) return viterbi_path @templatedoc() def cos_sim(X, Y): """ ${comment} Args: X (Tensor): ${x_comment}. Y (Tensor): ${y_comment}. Returns: A Tensor representing the output of cosine(X, Y). Examples: .. code-block:: python import paddle x = paddle.rand(shape=[3, 7], dtype='float32') y = paddle.rand(shape=[1, 7], dtype='float32') out = paddle.fluid.layers.cos_sim(x, y) print(out) """ check_variable_and_dtype(X, 'X', ['float32'], 'cos_sim') check_variable_and_dtype(Y, 'Y', ['float32'], 'cos_sim') helper = LayerHelper('cos_sim', **locals()) out = helper.create_variable_for_type_inference(dtype=X.dtype) xnorm = helper.create_variable_for_type_inference(dtype=X.dtype) ynorm = helper.create_variable_for_type_inference(dtype=X.dtype) helper.append_op( type='cos_sim', inputs={'X': [X], 'Y': [Y]}, outputs={'Out': [out], 'XNorm': [xnorm], 'YNorm': [ynorm]}) return out @deprecated(since="2.0.0", update_to="paddle.nn.functional.dropout") def dropout(x, dropout_prob, is_test=None, seed=None, name=None, dropout_implementation="downgrade_in_infer"): """ Computes dropout. Drop or keep each element of `x` independently. Dropout is a regularization technique for reducing overfitting by preventing neuron co-adaption during training. The dropout operator randomly sets (according to the given dropout probability) the outputs of some units to zero, while others are remain unchanged. dropout op can be removed from the program to make the program more efficient. Args: x (Variable): The input tensor variable. The data type is float16 or float32 or float64. dropout_prob (float): Probability of setting units to zero. is_test (bool): A flag indicating whether it is in test phrase or not. Default None, in dynamic graph, it use global tracer mode; in static graph, it means False. seed (int): A Python integer used to create random seeds. If this parameter is set to None, a random seed is used. NOTE: If an integer seed is given, always the same output units will be dropped. DO NOT use a fixed seed in training.Default: None. name (str|None): A name for this layer(optional). If set None, the layer will be named automatically. dropout_implementation(string): ['downgrade_in_infer'(default)|'upscale_in_train'] 1. downgrade_in_infer(default), downgrade the outcome at inference - train: out = input * mask - inference: out = input * (1.0 - dropout_prob) (mask is a tensor same shape with input, value is 0 or 1 ratio of 0 is dropout_prob) 2. upscale_in_train, upscale the outcome at training time - train: out = input * mask / ( 1.0 - dropout_prob ) - inference: out = input (mask is a tensor same shape with input, value is 0 or 1 ratio of 0 is dropout_prob) Returns: A Variable holding Tensor representing the dropout, has same shape and data type with `x`. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() x = fluid.data(name="data", shape=[None, 32, 32], dtype="float32") dropped = fluid.layers.dropout(x, dropout_prob=0.5) """ # fast return for p == 0 if dropout_prob == 0: return x if in_dygraph_mode(): if (seed is None or seed == 0) and default_main_program().random_seed != 0: seed = default_main_program().random_seed if is_test is None: is_test = not _dygraph_tracer()._train_mode out, mask = _C_ops.dropout( x, 'dropout_prob', dropout_prob, 'is_test', is_test, 'fix_seed', seed is not None, 'seed', seed if seed is not None else 0, 'dropout_implementation', dropout_implementation) return out def get_attrs(prog, dropout_prob, is_test, seed): if (seed is None or seed == 0) and prog.random_seed != 0: seed = prog.random_seed attrs = { 'dropout_prob': dropout_prob, 'is_test': is_test, 'fix_seed': seed is not None, 'seed': seed if seed is not None else 0, 'dropout_implementation': dropout_implementation, } return attrs helper = LayerHelper('dropout', **locals()) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'dropout') out = helper.create_variable_for_type_inference(dtype=x.dtype) mask = helper.create_variable_for_type_inference( dtype=core.VarDesc.VarType.UINT8, stop_gradient=True) attrs = get_attrs(helper.main_program, dropout_prob, is_test, seed) helper.append_op( type='dropout', inputs={'X': [x]}, outputs={'Out': [out], 'Mask': [mask]}, attrs=attrs) return out @templatedoc() def chunk_eval(input, label, chunk_scheme, num_chunk_types, excluded_chunk_types=None, seq_length=None): r""" This operator computes the precision, recall and F1-score for chunk detection. It is often used in sequence tagging tasks, such as Named Entity Recognition(NER). For some basics of chunking, please refer to `Chunking with Support Vector Machines <https://aclanthology.info/pdf/N/N01/N01-1025.pdf>`_ . This operator supports IOB, IOE, IOBES and IO (also known as plain) tagging schemes. Here is a NER example for the usage of these tagging schemes: .. code-block:: python ====== ====== ====== ===== == ============ ===== ===== ===== == ========= Li Ming works at Agricultural Bank of China in Beijing. ====== ====== ====== ===== == ============ ===== ===== ===== == ========= IO I-PER I-PER O O I-ORG I-ORG I-ORG I-ORG O I-LOC IOB B-PER I-PER O O B-ORG I-ORG I-ORG I-ORG O B-LOC IOE I-PER E-PER O O I-ORG I-ORG I-ORG E-ORG O E-LOC IOBES B-PER E-PER O O I-ORG I-ORG I-ORG E-ORG O S-LOC ====== ====== ====== ===== == ============ ===== ===== ===== == ========= There are three chunk types(named entity types) including PER(person), ORG(organization) and LOC(location), and we can see that the labels have the form `<tag type>-<chunk type>` . Since the implementation of this operator actually uses label ids rather than label strings, to make it work, there should be a way to map label ids to tag types and chunk types. This operator uses the following way to do mapping: .. code-block:: python tag_type = label % num_tag_type chunk_type = label / num_tag_type where `num_tag_type` is the num of tag types in the tagging scheme, `num_chunk_type` is the num of chunk types, and `tag_type` get its value from the following table. .. code-block:: python Scheme Begin Inside End Single plain 0 - - - IOB 0 1 - - IOE - 0 1 - IOBES 0 1 2 3 Accordingly, in the above NER example, if the tagging scheme is IOB and chunk types are ORG, PER and LOC, then the label ids would be as follows: .. code-block:: python B-ORG 0 I-ORG 1 B-PER 2 I-PER 3 B-LOC 4 I-LOC 5 O 6 With which we can map each label id to the corresponding tag type and chunk type correctly. Args: input (Tensor): A Tensor representing the predicted labels from the network. Its shape would be `[N, M, 1]`, where `N` stands for batch size, `M` for sequence length. The data type should be int64. label (Tensor): A Tensor representing the ground-truth labels. It should have the same shape, lod and data type as ``input`` . chunk_scheme (str): Indicate the tagging schemes used here. The value must be IOB, IOE, IOBES or plain. num_chunk_types (int): The number of chunk types. excluded_chunk_types (list, optional): Indicate the chunk types shouldn't be taken into account. It should be a list of chunk type ids(integer). Default None. seq_length(Tensor, optional): A 1D Tensor containing the length of each sequence when ``input`` and ``label`` are Tensor. Default None. Returns: tuple: A tuple including precision, recall, F1-score, chunk number detected, \ chunk number in ground-truth, chunk number correctly detected. Each \ is a Tensor with shape `[1]`. The data type of precision, recall and \ F1-score all is float32, and the others' data type all is int64. Examples: .. code-block:: python import paddle.fluid as fluid dict_size = 10000 label_dict_len = 7 sequence = fluid.data( name='id', shape=[None, 1], lod_level=1, dtype='int64') embedding = fluid.embedding( input=sequence, size=[dict_size, 512]) hidden = fluid.layers.fc(input=embedding, size=512) label = fluid.data( name='label', shape=[None, 1], lod_level=1, dtype='int64') crf = fluid.layers.linear_chain_crf( input=hidden, label=label, param_attr=fluid.ParamAttr(name="crfw")) crf_decode = fluid.layers.crf_decoding( input=hidden, param_attr=fluid.ParamAttr(name="crfw")) fluid.layers.chunk_eval( input=crf_decode, label=label, chunk_scheme="IOB", num_chunk_types=int((label_dict_len - 1) / 2)) """ helper = LayerHelper("chunk_eval", **locals()) check_variable_and_dtype(input, 'input', ['int64'], 'chunk_eval') check_variable_and_dtype(label, 'label', ['int64'], 'chunk_eval') # prepare output precision = helper.create_variable_for_type_inference(dtype="float32") recall = helper.create_variable_for_type_inference(dtype="float32") f1_score = helper.create_variable_for_type_inference(dtype="float32") num_infer_chunks = helper.create_variable_for_type_inference(dtype="int64") num_label_chunks = helper.create_variable_for_type_inference(dtype="int64") num_correct_chunks = helper.create_variable_for_type_inference( dtype="int64") this_input = {"Inference": [input], "Label": [label]} if seq_length is not None: this_input["SeqLength"] = [seq_length] helper.append_op( type="chunk_eval", inputs=this_input, outputs={ "Precision": [precision], "Recall": [recall], "F1-Score": [f1_score], "NumInferChunks": [num_infer_chunks], "NumLabelChunks": [num_label_chunks], "NumCorrectChunks": [num_correct_chunks] }, attrs={ "num_chunk_types": num_chunk_types, "chunk_scheme": chunk_scheme, "excluded_chunk_types": excluded_chunk_types or [] }) return (precision, recall, f1_score, num_infer_chunks, num_label_chunks, num_correct_chunks) @deprecated(since="2.0.0", update_to="paddle.nn.functional.softmax") def softmax(input, use_cudnn=True, name=None, axis=-1): r""" This operator implements the softmax layer. The calculation process is as follows: 1. The dimension :attr:`axis` of the ``input`` will be permuted to the last. 2. Then the input tensor will be logically flattened to a 2-D matrix. The matrix's second dimension(row length) is the same as the dimension :attr:`axis` of the input tensor, and the first dimension(column length) is the product of all other dimensions of the input tensor. For each row of the matrix, the softmax operator squashes the K-dimensional(K is the width of the matrix, which is also the size of the input tensor's dimension :attr:`axis`) vector of arbitrary real values to a K-dimensional vector of real values in the range [0, 1] that add up to 1. 3. After the softmax operation is completed, the inverse operations of steps 1 and 2 are performed to restore the two-dimensional matrix to the same dimension as the ``input``. It computes the exponential of the given dimension and the sum of exponential values of all the other dimensions in the K-dimensional vector input. Then the ratio of the exponential of the given dimension and the sum of exponential values of all the other dimensions is the output of the softmax operator. For each row :math:`i` and each column :math:`j` in the matrix, we have: .. math:: Out[i, j] = \\frac{\\exp(X[i, j])}{\\sum_j(exp(X[i, j])} Example: .. code-block:: text Case 1: Input: X.shape = [2, 3, 4] X.data = [[[2.0, 3.0, 4.0, 5.0], [3.0, 4.0, 5.0, 6.0], [7.0, 8.0, 8.0, 9.0]], [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [6.0, 7.0, 8.0, 9.0]]] Attrs: axis = -1 Output: Out.shape = [2, 3, 4] Out.data = [[[0.0320586 , 0.08714432, 0.23688282, 0.64391426], [0.0320586 , 0.08714432, 0.23688282, 0.64391426], [0.07232949, 0.19661193, 0.19661193, 0.53444665]], [[0.0320586 , 0.08714432, 0.23688282, 0.64391426], [0.0320586 , 0.08714432, 0.23688282, 0.64391426], [0.0320586 , 0.08714432, 0.23688282, 0.64391426]]] Case 2: Input: X.shape = [2, 3, 4] X.data = [[[2.0, 3.0, 4.0, 5.0], [3.0, 4.0, 5.0, 6.0], [7.0, 8.0, 8.0, 9.0]], [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [6.0, 7.0, 8.0, 9.0]]] Attrs: axis = 1 Output: Out.shape = [2, 3, 4] Out.data = [[[0.00657326, 0.00657326, 0.01714783, 0.01714783], [0.01786798, 0.01786798, 0.04661262, 0.04661262], [0.97555875, 0.97555875, 0.93623955, 0.93623955]], [[0.00490169, 0.00490169, 0.00490169, 0.00490169], [0.26762315, 0.26762315, 0.26762315, 0.26762315], [0.72747516, 0.72747516, 0.72747516, 0.72747516]]] Args: input (Tensor): The input tensor. A multi-dimension ``Tensor`` with type float32 or float64. use_cudnn (bool, optional): Use cudnn kernel or not, it is valid only when the cudnn \ library is installed. To improve performance, set use_cudnn to True by default. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Default: None. will be named automatically. Default: None. axis (int, optional): The index of dimension to perform softmax calculations, it should be in range :math:`[-1, rank - 1]`, while :math:`rank` is the rank of input tensor. Default: -1. -1 means the last dimension. Returns: Tensor: ``Tensor`` indicates the output of softmax. The data type and shape are the same as ``input`` . Examples: .. code-block:: python import paddle import paddle.nn.functional as F x = paddle.to_tensor([[[2.0, 3.0, 4.0, 5.0], [3.0, 4.0, 5.0, 6.0], [7.0, 8.0, 8.0, 9.0]], [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [6.0, 7.0, 8.0, 9.0]]], dtype='float32') y = F.softmax(x, axis=1) print(y) # [[[0.00657326, 0.00657326, 0.01714783, 0.01714783], # [0.01786798, 0.01786798, 0.04661262, 0.04661262], # [0.97555870, 0.97555870, 0.93623954, 0.93623954]], # [[0.00490169, 0.00490169, 0.00490169, 0.00490169], # [0.26762316, 0.26762316, 0.26762316, 0.26762316], # [0.72747517, 0.72747517, 0.72747517, 0.72747517]]] """ if in_dygraph_mode(): return _C_ops.softmax(input, 'axis', axis, 'use_cudnn', use_cudnn) inputs = {"X": [input]} attrs = {"axis": axis, "use_cudnn": use_cudnn} helper = LayerHelper('softmax', **locals()) check_variable_and_dtype(input, 'input/x', ['float16', 'float32', 'float64'], 'softmax') dtype = helper.input_dtype() softmax_out = helper.create_variable_for_type_inference(dtype) helper.append_op( type="softmax", inputs={"X": input}, outputs={"Out": softmax_out}, attrs=attrs) return softmax_out def conv2d(input, num_filters, filter_size, stride=1, padding=0, dilation=1, groups=None, param_attr=None, bias_attr=None, use_cudnn=True, act=None, name=None, data_format="NCHW"): r""" :api_attr: Static Graph The convolution2D layer calculates the output based on the input, filter and strides, paddings, dilations, groups parameters. Input and Output are in NCHW or NHWC format, where N is batch size, C is the number of channels, H is the height of the feature, and W is the width of the feature. Filter is in MCHW format, where M is the number of output image channels, C is the number of input image channels, H is the height of the filter, and W is the width of the filter. If the groups is greater than 1, C will equal the number of input image channels divided by the groups. Please refer to UFLDL's `convolution <http://ufldl.stanford.edu/tutorial/supervised/FeatureExtractionUsingConvolution/>`_ for more details. If bias attribution and activation type are provided, bias is added to the output of the convolution, and the corresponding activation function is applied to the final result. For each input :math:`X`, the equation is: .. math:: Out = \sigma (W \\ast X + b) Where: * :math:`X`: Input value, a tensor with NCHW or NHWC format. * :math:`W`: Filter value, a tensor with MCHW format. * :math:`\\ast`: Convolution operation. * :math:`b`: Bias value, a 2-D tensor with shape [M, 1]. * :math:`\\sigma`: Activation function. * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. Example: - Input: Input shape: :math:`(N, C_{in}, H_{in}, W_{in})` Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)` - Output: Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` Where .. math:: H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\ W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1 Args: input (Tensor): The input is 4-D Tensor with shape [N, C, H, W], the data type of input is float16 or float32 or float64. num_filters(int): The number of filter. It is as same as the output image channel. filter_size (int|tuple): The filter size. If filter_size is a tuple, it must contain two integers, (filter_size_height, filter_size_width). Otherwise, filter_size_height = filter_size_width =\ filter_size. stride (int|tuple): The stride size. It means the stride in convolution. If stride is a tuple, it must contain two integers, (stride_height, stride_width). Otherwise, stride_height = stride_width = stride. Default: stride = 1. padding (string|int|list|tuple): The padding size. It means the number of zero-paddings on both sides for each dimension.If `padding` is a string, either 'VALID' or 'SAME' which is the padding algorithm. If padding size is a tuple or list, it could be in three forms: `[pad_height, pad_width]` or `[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when `data_format` is `"NCHW"`, `padding` can be in the form `[[0,0], [0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. when `data_format` is `"NHWC"`, `pool_padding` can be in the form `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. Default: padding = 0. dilation (int|tuple): The dilation size. It means the spacing between the kernel points. If dilation is a tuple, it must contain two integers, (dilation_height, dilation_width). Otherwise, dilation_height = dilation_width = dilation. Default: dilation = 1. groups (int): The groups number of the Conv2d Layer. According to grouped convolution in Alex Krizhevsky's Deep CNN paper: when group=2, the first half of the filters is only connected to the first half of the input channels, while the second half of the filters is only connected to the second half of the input channels. Default: groups=1. param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights of conv2d. If it is set to None or one attribute of ParamAttr, conv2d will create ParamAttr as param_attr. If the Initializer of the param_attr is not set, the parameter is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None. bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of conv2d. If it is set to False, no bias will be added to the output units. If it is set to None or one attribute of ParamAttr, conv2d will create ParamAttr as bias_attr. If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. use_cudnn (bool): Use cudnn kernel or not, it is valid only when the cudnn library is installed. Default: True act (str): Activation type, if it is set to None, activation is not appended. Default: None name(str|None): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. Returns: A Tensor representing the conv2d, whose data type is the same with input. If act is None, the tensor storing the convolution result, and if act is not None, the tensor storing convolution and non-linearity activation result. Raises: ValueError: If the type of `use_cudnn` is not bool. ValueError: If `data_format` is not "NCHW" or "NHWC". ValueError: If the channel dimmention of the input is less than or equal to zero. ValueError: If `padding` is a string, but not "SAME" or "VALID". ValueError: If `padding` is a tuple, but the element corresponding to the input's batch size is not 0 or the element corresponding to the input's channel is not 0. ShapeError: If the input is not 4-D Tensor. ShapeError: If the input's dimension size and filter's dimension size not equal. ShapeError: If the dimension size of input minus the size of `stride` is not 2. ShapeError: If the number of input channels is not equal to filter's channels * groups. ShapeError: If the number of output channels is not be divided by groups. Examples: .. code-block:: python import paddle paddle.enable_static() data = paddle.static.data(name='data', shape=[None, 3, 32, 32], dtype='float32') conv2d = paddle.static.nn.conv2d(input=data, num_filters=2, filter_size=3, act="relu") print(conv2d.shape) # [-1, 2, 30, 30] """ check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'], 'conv2d') if len(input.shape) != 4: raise ValueError("Input size should be 4, " "but received {}".format(len(input.shape))) num_channels = input.shape[1] if not isinstance(use_cudnn, bool): raise ValueError("Attr(use_cudnn) should be True or False. Received " "Attr(use_cudnn): %s. " % str(use_cudnn)) if data_format not in ["NCHW", "NHWC"]: raise ValueError( "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " "Attr(data_format): %s." % str(data_format)) channel_last = (data_format == "NHWC") num_channels = input.shape[3] if channel_last else input.shape[1] if num_channels < 0: raise ValueError( "The channel dimmention of the input(%s) should be defined. " "Received: %s." % (str(input.shape), str(num_channels))) assert param_attr is not False, "param_attr should not be False here." if groups is None: num_filter_channels = num_channels elif groups <= 0: raise ValueError("the groups of input must be greater than 0, " "but received the groups of input is {}".format( groups)) else: if num_channels % groups != 0: raise ValueError( "the channel of input must be divisible by groups," "received: the channel of input is {}, the shape of input is {}" ", the groups is {}".format(num_channels, input.shape, groups)) num_filter_channels = num_channels // groups l_type = 'conv2d' if (num_channels == groups and num_filters % num_channels == 0 and not use_cudnn): l_type = 'depthwise_conv2d' if (num_channels == groups and num_filters % num_channels == 0 and core.is_compiled_with_rocm()): l_type = 'depthwise_conv2d' # NPU only supports depthwise_conv2d when "input_channel = output_channel = groups" if core.is_compiled_with_npu(): if (num_channels == groups and num_channels == num_filters): l_type = 'depthwise_conv2d' else: l_type = 'conv2d' helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype() filter_size = utils.convert_to_list(filter_size, 2, 'filter_size') stride = utils.convert_to_list(stride, 2, 'stride') dilation = utils.convert_to_list(dilation, 2, 'dilation') # padding def _update_padding(padding, data_format): def is_list_or_tuple(ele): if isinstance(ele, list) or isinstance(ele, tuple): return True return False if is_list_or_tuple(padding) and len(padding) == 4: if is_list_or_tuple(padding[0]) and (data_format == "NCHW"): if not (padding[0] == [0, 0] and padding[1] == [0, 0]): raise ValueError( "Non-zero padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[2:4] padding = [ele for a_list in padding for ele in a_list] elif is_list_or_tuple(padding[0]) and (data_format == "NHWC"): if not (padding[0] == [0, 0] and padding[3] == [0, 0]): raise ValueError( "Non-zero padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[1:3] padding = [ele for a_list in padding for ele in a_list] padding = utils.convert_to_list(padding, 4, 'padding') if utils._is_symmetric_padding(padding, 2): padding = [padding[0], padding[2]] else: padding = utils.convert_to_list(padding, 2, 'padding') return padding padding_algorithm = "EXPLICIT" if isinstance(padding, str): padding = padding.upper() if padding not in ["SAME", "VALID"]: raise ValueError( "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'." % str(padding)) if padding == "VALID": padding_algorithm = "VALID" padding = [0, 0] elif padding == "SAME": padding_algorithm = "SAME" padding = [0, 0] padding = _update_padding(padding, data_format) filter_shape = [num_filters, int(num_filter_channels)] + filter_size def _get_default_param_initializer(): filter_elem_num = filter_size[0] * filter_size[1] * num_channels if filter_elem_num <= 0: raise ValueError( "Invalid filter number, excepted number is larger than 0, but" " received {}, please check the input shape and " "filter size.".format(filter_elem_num)) std = (2.0 / filter_elem_num)**0.5 return Normal(0.0, std, 0) filter_param = helper.create_parameter( attr=helper.param_attr, shape=filter_shape, dtype=dtype, default_initializer=_get_default_param_initializer()) pre_bias = helper.create_variable_for_type_inference(dtype) if (core.is_compiled_with_cuda() and paddle.fluid.get_flags( "FLAGS_conv2d_disable_cudnn")["FLAGS_conv2d_disable_cudnn"]): use_cudnn = False helper.append_op( type=l_type, inputs={ 'Input': input, 'Filter': filter_param, }, outputs={"Output": pre_bias}, attrs={ 'strides': stride, 'paddings': padding, 'dilations': dilation, 'groups': groups, 'use_cudnn': use_cudnn, 'use_mkldnn': False, 'fuse_relu_before_depthwise_conv': False, "padding_algorithm": padding_algorithm, "data_format": data_format, }) if data_format == 'NCHW': pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2) else: pre_act = helper.append_bias_op(pre_bias, dim_start=3, dim_end=4) return helper.append_activation(pre_act) def conv3d(input, num_filters, filter_size, stride=1, padding=0, dilation=1, groups=None, param_attr=None, bias_attr=None, use_cudnn=True, act=None, name=None, data_format="NCDHW"): r""" :api_attr: Static Graph The convolution3D layer calculates the output based on the input, filter and strides, paddings, dilations, groups parameters. Input(Input) and Output(Output) are in NCDHW or NDHWC format. Where N is batch size C is the number of channels, D is the depth of the feature, H is the height of the feature, and W is the width of the feature. Convlution3D is similar with Convlution2D but adds one dimension(depth). If bias attribution and activation type are provided, bias is added to the output of the convolution, and the corresponding activation function is applied to the final result. For each input :math:`X`, the equation is: .. math:: Out = \sigma (W \\ast X + b) In the above equation: * :math:`X`: Input value, a tensor with NCDHW or NDHWC format. * :math:`W`: Filter value, a tensor with MCDHW format. * :math:`\\ast`: Convolution operation. * :math:`b`: Bias value, a 2-D tensor with shape [M, 1]. * :math:`\\sigma`: Activation function. * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. Example: - Input: Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` Filter shape: :math:`(C_{out}, C_{in}, D_f, H_f, W_f)` - Output: Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` Where .. math:: D_{out}&= \\frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (D_f - 1) + 1))}{strides[0]} + 1 \\\\ H_{out}&= \\frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (H_f - 1) + 1))}{strides[1]} + 1 \\\\ W_{out}&= \\frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (W_f - 1) + 1))}{strides[2]} + 1 Args: input (Tensor): The input is 5-D Tensor with shape [N, C, D, H, W], the data type of input is float16 or float32 or float64. num_filters(int): The number of filter. It is as same as the output image channel. filter_size (int|tuple): The filter size. If filter_size is a tuple, it must contain three integers, (filter_size_depth, filter_size_height, filter_size_width). Otherwise, filter_size_depth = filter_size_height = \ filter_size_width = filter_size. stride (int|tuple): The stride size. It means the stride in convolution. If stride is a tuple, it must contain three integers, (stride_depth, stride_height, stride_width). Otherwise, stride_depth = stride_height = stride_width = stride. Default: stride = 1. padding (string|int|list|tuple): The padding size. It means the number of zero-paddings on both sides for each dimension. If `padding` is a string, either 'VALID' or 'SAME' which is the padding algorithm. If padding size is a tuple or list, it could be in three forms: `[pad_depth, pad_height, pad_width]` or `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when `data_format` is `"NCDHW"`, `pool_padding` can be in the form `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. when `data_format` is `"NDHWC"`, `pool_padding` can be in the form `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. Default: padding = 0. dilation (int|tuple): The dilation size. It means the spacing between the kernel points. If dilation is a tuple, it must contain three integers, (dilation_depth, dilation_height, dilation_width). Otherwise, dilation_depth = dilation_height = dilation_width = dilation. Default: dilation = 1. groups (int): The groups number of the Conv3d Layer. According to grouped convolution in Alex Krizhevsky's Deep CNN paper: when group=2, the first half of the filters is only connected to the first half of the input channels, while the second half of the filters is only connected to the second half of the input channels. Default: groups=1 param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights of conv3d. If it is set to None or one attribute of ParamAttr, conv3d will create ParamAttr as param_attr. If it is set to None, the parameter is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None. bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of conv3d. If it is set to False, no bias will be added to the output units. If it is set to None or one attribute of ParamAttr, conv3d will create ParamAttr as bias_attr. If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. use_cudnn (bool): Use cudnn kernel or not, it is valid only when the cudnn library is installed. Default: True act (str): Activation type, if it is set to None, activation is not appended. Default: None. name(str|None): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. Returns: A Variable holding Tensor representing the conv3d, whose data type is the same with input. If act is None, the tensor variable storing the convolution result, and if act is not None, the tensor variable storing convolution and non-linearity activation result. Raises: ValueError: If the type of `use_cudnn` is not bool. ValueError: If `data_format` is not "NCDHW" or "NDHWC". ValueError: If the channel dimmention of the input is less than or equal to zero. ValueError: If `padding` is a string, but not "SAME" or "VALID". ValueError: If `padding` is a tuple, but the element corresponding to the input's batch size is not 0 or the element corresponding to the input's channel is not 0. ShapeError: If the input is not 5-D Tensor. ShapeError: If the input's dimension size and filter's dimension size not equal. ShapeError: If the dimension size of input minus the size of `stride` is not 2. ShapeError: If the number of input channels is not equal to filter's channels * groups. ShapeError: If the number of output channels is not be divided by groups. Examples: .. code-block:: python import paddle import numpy as np paddle.enable_static() data = paddle.static.data(name='data', shape=[None, 3, 12, 32, 32], dtype='float32') param_attr = paddle.framework.ParamAttr(name='conv3d.weight', initializer=paddle.nn.initializer.XavierNormal(), learning_rate=0.001) res = paddle.static.nn.conv3d(input=data, num_filters=2, filter_size=3, act="relu", param_attr=param_attr) place = paddle.CPUPlace() exe = paddle.static.Executor(place) exe.run(paddle.static.default_startup_program()) x = np.random.rand(1, 3, 12, 32, 32).astype("float32") output = exe.run(feed={"data": x}, fetch_list=[res]) print(output) """ l_type = 'conv3d' assert param_attr is not False, "param_attr should not be False here." helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype() if not isinstance(use_cudnn, bool): raise ValueError("Attr(use_cudnn) should be True or False. Received " "Attr(use_cudnn): %s. " % str(use_cudnn)) if data_format not in ["NCDHW", "NDHWC"]: raise ValueError( "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " "Attr(data_format): %s." % str(data_format)) channel_last = (data_format == "NDHWC") if len(input.shape) != 5: raise ValueError( "Input should be 5D tensor, but received input with the shape of {}". format(input.shape)) num_channels = input.shape[4] if channel_last else input.shape[1] if num_channels < 0: raise ValueError( "The channel dimmention of the input(%s) should be defined. " "Received: %s." % (str(input.shape), str(num_channels))) if groups is None: num_filter_channels = num_channels elif groups <= 0: raise ValueError( "the groups of conv3d should be greater than 0. Received groups: {}". format(groups)) else: if num_channels % groups != 0: raise ValueError( "The number of input channels must be divisible by Attr(groups). " "Received: number of channels(%s), groups(%s)." % (str(num_channels), str(groups))) num_filter_channels = num_channels // groups filter_size = utils.convert_to_list(filter_size, 3, 'filter_size') stride = utils.convert_to_list(stride, 3, 'stride') dilation = utils.convert_to_list(dilation, 3, 'dilation') def _update_padding(padding, data_format): def is_list_or_tuple(ele): if isinstance(ele, list) or isinstance(ele, tuple): return True return False if is_list_or_tuple(padding) and len(padding) == 5: if is_list_or_tuple(padding[0]) and (data_format == "NCDHW"): if not (padding[0] == [0, 0] and padding[1] == [0, 0]): raise ValueError( "Non-zero padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[2:5] padding = [ele for a_list in padding for ele in a_list] elif is_list_or_tuple(padding[0]) and (data_format == "NDHWC"): if not (padding[0] == [0, 0] and padding[4] == [0, 0]): raise ValueError( "Non-zero padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[1:4] padding = [ele for a_list in padding for ele in a_list] padding = utils.convert_to_list(padding, 6, 'padding') if utils._is_symmetric_padding(padding, 3): padding = [padding[0], padding[2], padding[4]] elif is_list_or_tuple(padding) and len(padding) == 6: padding = utils.convert_to_list(padding, 6, 'padding') if utils._is_symmetric_padding(padding, 3): padding = [padding[0], padding[2], padding[4]] else: padding = utils.convert_to_list(padding, 3, 'padding') return padding padding_algorithm = "EXPLICIT" if isinstance(padding, str): padding = padding.upper() if padding not in ["SAME", "VALID"]: raise ValueError( "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'." % str(padding)) if padding == "VALID": padding_algorithm = "VALID" padding = [0, 0, 0] elif padding == "SAME": padding_algorithm = "SAME" padding = [0, 0, 0] padding = _update_padding(padding, data_format) input_shape = input.shape filter_shape = [num_filters, num_filter_channels] + filter_size def _get_default_param_initializer(): filter_elem_num = filter_size[0] * filter_size[1] * filter_size[ 2] * num_channels if filter_elem_num <= 0: raise ValueError( "Invalid filter number, excepted number is larger than 0, but" " received {}, please check the input shape and " "filter size.".format(filter_elem_num)) std = (2.0 / filter_elem_num)**0.5 return Normal(0.0, std, 0) filter_param = helper.create_parameter( attr=helper.param_attr, shape=filter_shape, dtype=dtype, default_initializer=_get_default_param_initializer()) pre_bias = helper.create_variable_for_type_inference(dtype) helper.append_op( type=l_type, inputs={ 'Input': input, 'Filter': filter_param, }, outputs={"Output": pre_bias}, attrs={ 'strides': stride, 'paddings': padding, 'dilations': dilation, 'groups': groups, 'use_cudnn': use_cudnn, 'use_mkldnn': False, "padding_algorithm": padding_algorithm, "data_format": data_format, }) if data_format == 'NCDHW': pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2) else: pre_act = helper.append_bias_op(pre_bias, dim_start=4, dim_end=5) return helper.append_activation(pre_act) @templatedoc() def pool2d(input, pool_size=-1, pool_type="max", pool_stride=1, pool_padding=0, global_pooling=False, use_cudnn=True, ceil_mode=False, name=None, exclusive=True, data_format="NCHW"): """ ${comment} Args: input (Variable): The input tensor of pooling operator which is a 4-D tensor with shape [N, C, H, W]. The format of input tensor is `"NCHW"` or `"NHWC"`, where `N` is batch size, `C` is the number of channels, `H` is the height of the feature, and `W` is the width of the feature. The data type if float32 or float64. pool_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain two integers, (pool_size_Height, pool_size_Width). Otherwise, the pool kernel size will be a square of an int. pool_type: ${pooling_type_comment} pool_stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, it must contain two integers, (pool_stride_Height, pool_stride_Width). Otherwise, the pool stride size will be a square of an int. pool_padding (string|int|list|tuple): The pool padding. If `pool_padding` is a string, either 'VALID' or 'SAME' which is the padding algorithm. If pool padding size is a tuple or list, it could be in three forms: `[pad_height, pad_width]` or `[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when `data_format` is `"NCHW"`, `pool_padding` can be in the form `[[0,0], [0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. when `data_format` is `"NHWC"`, `pool_padding` can be in the form `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. Otherwise, the pool padding size will be a square of an int. global_pooling (bool): ${global_pooling_comment} use_cudnn (bool): ${use_cudnn_comment} ceil_mode (bool): ${ceil_mode_comment} name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. exclusive (bool): Whether to exclude padding points in average pooling mode, default is `true`. data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. Returns: Variable: The output tensor of pooling result. The data type is same as input tensor. Raises: ValueError: If `pool_type` is not "max" nor "avg". ValueError: If `global_pooling` is False and `pool_size` is -1. TypeError: If `use_cudnn` is not a bool value. ValueError: If `data_format` is not "NCHW" or "NHWC". ValueError: If `pool_padding` is a string, but not "SAME" or "VALID". ValueError: If `pool_padding` is "VALID", but `ceil_mode` is True. ValueError: If `pool_padding` is a list or tuple, but the elements in the batch or channel dimensions are non-zero. ShapeError: If the input is not a 4-D or 5-D Tensor. ShapeError: If the dimension of input minus the size of `pool_stride` is not 2. ShapeError: If the size of `pool_size` and `pool_stride` is not equal. ShapeError: If the output's shape calculated is not greater than 0. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() data = fluid.data(name='data', shape=[None, 3, 32, 32], dtype='float32') # max pool2d pool2d = fluid.layers.pool2d( input = data, pool_size = 2, pool_type = "max", pool_stride = 1, global_pooling=False) # average pool2d pool2d = fluid.layers.pool2d( input = data, pool_size = 2, pool_type = "avg", pool_stride = 1, global_pooling=False) # global average pool2d pool2d = fluid.layers.pool2d( input = data, pool_size = 2, pool_type = "avg", pool_stride = 1, global_pooling=True) # Attr(pool_padding) is a list with 4 elements, Attr(data_format) is "NCHW". out_1 = fluid.layers.pool2d( input = data, pool_size = 3, pool_type = "avg", pool_stride = 1, pool_padding = [1, 2, 1, 0], data_format = "NCHW") # Attr(pool_padding) is a string, Attr(data_format) is "NCHW". out_2 = fluid.layers.pool2d( input = data, pool_size = 3, pool_type = "avg", pool_stride = 1, pool_padding = "VALID", data_format = "NCHW") """ if pool_type not in ["max", "avg"]: raise ValueError( "Unknown Attr(pool_type): '%s'. It can only be 'max' or 'avg'.", str(pool_type)) if global_pooling is False and pool_size == -1: raise ValueError( "When Attr(global_pooling) is False, Attr(pool_size) must be passed " "and be a valid value. Received pool_size: %s." % str(pool_size)) if not isinstance(use_cudnn, bool): raise TypeError("Attr(use_cudnn) should be True or False. Received " "Attr(use_cudnn): %s." % str(use_cudnn)) if data_format not in ["NCHW", "NHWC"]: raise ValueError( "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " "Attr(data_format): %s." % str(data_format)) pool_size = utils.convert_to_list(pool_size, 2, 'pool_size') pool_stride = utils.convert_to_list(pool_stride, 2, 'pool_stride') def update_padding(padding, data_format): def is_list_or_tuple(ele): if isinstance(ele, list) or isinstance(ele, tuple): return True return False if is_list_or_tuple(padding) and len(padding) == 4: if is_list_or_tuple(padding[0]) and (data_format == "NCHW"): if not (padding[0] == [0, 0] and padding[1] == [0, 0]): raise ValueError( "Non-zero pool_padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[2:4] padding = [ele for a_list in padding for ele in a_list] elif is_list_or_tuple(padding[0]) and (data_format == "NHWC"): if not (padding[0] == [0, 0] and padding[3] == [0, 0]): raise ValueError( "Non-zero pool_padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[1:3] padding = [ele for a_list in padding for ele in a_list] padding = utils.convert_to_list(padding, 4, 'padding') if utils._is_symmetric_padding(padding, 2): padding = [padding[0], padding[2]] else: padding = utils.convert_to_list(padding, 2, 'padding') return padding padding_algorithm = "EXPLICIT" if isinstance(pool_padding, str): pool_padding = pool_padding.upper() if pool_padding not in ["SAME", "VALID"]: raise ValueError( "Unknown Attr(pool_padding): '%s'. It can only be 'SAME' or 'VALID'." % str(pool_padding)) if pool_padding == "VALID": padding_algorithm = "VALID" pool_padding = [0, 0] if ceil_mode != False: raise ValueError( "When Attr(pool_padding) is \"VALID\", Attr(ceil_mode) must be False. " "Received ceil_mode: True.") elif pool_padding == "SAME": padding_algorithm = "SAME" pool_padding = [0, 0] pool_padding = update_padding(pool_padding, data_format) op_type = 'pool2d' helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype() pool_out = helper.create_variable_for_type_inference(dtype) helper.append_op( type=op_type, inputs={"X": input}, outputs={"Out": pool_out}, attrs={ "pooling_type": pool_type, "ksize": pool_size, "global_pooling": global_pooling, "strides": pool_stride, "paddings": pool_padding, "padding_algorithm": padding_algorithm, "use_cudnn": use_cudnn, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": exclusive, "data_format": data_format, }) return pool_out @templatedoc() def pool3d(input, pool_size=-1, pool_type="max", pool_stride=1, pool_padding=0, global_pooling=False, use_cudnn=True, ceil_mode=False, name=None, exclusive=True, data_format="NCDHW"): """ ${comment} Args: input (Variable): The input tensor of pooling operator, which is a 5-D tensor with shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` or `"NDHWC"`, where `N` is batch size, `C` is the number of channels, `D` is the depth of the feature, `H` is the height of the feature, and `W` is the width of the feature. pool_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain three integers, (pool_size_Depth, pool_size_Height, pool_size_Width). Otherwise, the pool kernel size will be the cube of an int. pool_type (string): ${pooling_type_comment} pool_stride (string|int|list|tuple)): The pool padding. If `pool_padding` is a string, either 'VALID' or 'SAME' which is the padding algorithm. If pool stride size is a tuple or list, it must contain three integers, `[stride_Depth, stride_Height, stride_Width]`. Otherwise, the pool stride size will be a cube of an int. pool_padding (int|list|tuple): The pool padding size. If pool padding size is a tuple or list, it could be in three forms: `[pad_depth, pad_height, pad_width]` or `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when `data_format` is `"NCDHW"`, `pool_padding` can be in the form `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. when `data_format` is `"NDHWC"`, `pool_padding` can be in the form `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. global_pooling (bool): ${global_pooling_comment} use_cudnn (bool): ${use_cudnn_comment} ceil_mode (bool): ${ceil_mode_comment} name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. exclusive (bool): Whether to exclude padding points in average pooling mode, default is true. data_format (string): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. Returns: Variable: The output tensor of pooling result. The data type is same as input tensor. Raises: ValueError: If `pool_type` is not "max" nor "avg". ValueError: If `global_pooling` is False and `pool_size` is -1. TypeError: If `use_cudnn` is not a bool value. ValueError: If `data_format` is not "NCDHW" or "NDHWC". ValueError: If `pool_padding` is a string, but not "SAME" or "VALID". ValueError: If `pool_padding` is "VALID", but `ceil_mode` is True. ValueError: If `pool_padding` is a list or tuple, but the elements in the batch or channel dimensions are non-zero. ShapeError: If the input is not a 4-D or 5-D Tensor. ShapeError: If the dimension of input minus the size of `pool_stride` is not 2. ShapeError: If the size of `pool_size` and `pool_stride` is not equal. ShapeError: If the output's shape calculated is not greater than 0. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() data = fluid.data(name='data', shape=[None, 3, 32, 32, 32], dtype='float32') # max pool3d pool3d = fluid.layers.pool3d( input = data, pool_size = 2, pool_type = "max", pool_stride = 1, global_pooling=False) # average pool3d pool3d = fluid.layers.pool3d( input = data, pool_size = 2, pool_type = "avg", pool_stride = 1, global_pooling=False) # global average pool3d pool3d = fluid.layers.pool3d( input = data, pool_size = 2, pool_type = "avg", pool_stride = 1, global_pooling=True) # example 1: # Attr(pool_padding) is a list with 6 elements, Attr(data_format) is "NCDHW". out_1 = fluid.layers.pool3d( input = data, pool_size = 2, pool_type = "avg", pool_stride = 1, pool_padding = [1, 2, 1, 0, 1, 2], global_pooling = False, data_format = "NCDHW") # example 2: # Attr(pool_padding) is a string, Attr(data_format) is "NCDHW". out_2 = fluid.layers.pool3d( input = data, pool_size = 3, pool_type = "avg", pool_stride = 1, pool_padding = "VALID", global_pooling = False, data_format = "NCDHW") """ if pool_type not in ["max", "avg"]: raise ValueError( "Unknown Attr(pool_type): '%s'. It can only be 'max' or 'avg'.", str(pool_type)) if global_pooling is False and pool_size == -1: raise ValueError( "When Attr(global_pooling) is False, Attr(pool_size) must be passed " "and be a valid value. Received Attr(pool_size): %s." % str(pool_size)) if not isinstance(use_cudnn, bool): raise TypeError("Attr(use_cudnn) should be True or False. Received " "Attr(use_cudnn): %s. " % str(use_cudnn)) if data_format not in ["NCDHW", "NDHWC"]: raise ValueError( "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " "Attr(data_format): %s" % str(data_format)) pool_size = utils.convert_to_list(pool_size, 3, 'pool_size') pool_stride = utils.convert_to_list(pool_stride, 3, 'pool_stride') def update_padding(padding, data_format): def is_list_or_tuple(ele): if isinstance(ele, (list, tuple)): return True return False if is_list_or_tuple(padding) and len(padding) == 5: if is_list_or_tuple(padding[0]) and (data_format == "NCDHW"): if not (padding[0] == [0, 0] and padding[1] == [0, 0]): raise ValueError( "Non-zero pool_padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[2:5] padding = [ele for a_list in padding for ele in a_list] elif is_list_or_tuple(padding[0]) and (data_format == "NDHWC"): if not (padding[0] == [0, 0] and padding[4] == [0, 0]): raise ValueError( "Non-zero pool_padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[1:4] padding = [ele for a_list in padding for ele in a_list] padding = utils.convert_to_list(padding, 6, 'padding') if utils._is_symmetric_padding(padding, 3): padding = [padding[0], padding[2], padding[4]] elif is_list_or_tuple(padding) and len(padding) == 6: padding = utils.convert_to_list(padding, 6, 'padding') if utils._is_symmetric_padding(padding, 3): padding = [padding[0], padding[2], padding[4]] else: padding = utils.convert_to_list(padding, 3, 'padding') return padding padding_algorithm = "EXPLICIT" if isinstance(pool_padding, str): pool_padding = pool_padding.upper() if pool_padding not in ["SAME", "VALID"]: raise ValueError( "Unknown Attr(pool_padding): '%s'. It can only be 'SAME' or 'VALID'." % str(pool_padding)) if pool_padding == "VALID": padding_algorithm = "VALID" pool_padding = [0, 0, 0] if ceil_mode != False: raise ValueError( "When Attr(pool_padding) is \"VALID\", ceil_mode must be False. " "Received ceil_mode: True.") elif pool_padding == "SAME": padding_algorithm = "SAME" pool_padding = [0, 0, 0] pool_padding = update_padding(pool_padding, data_format) op_type = "pool3d" helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype() pool_out = helper.create_variable_for_type_inference(dtype) helper.append_op( type=op_type, inputs={"X": input}, outputs={"Out": pool_out}, attrs={ "pooling_type": pool_type, "ksize": pool_size, "global_pooling": global_pooling, "strides": pool_stride, "paddings": pool_padding, "padding_algorithm": padding_algorithm, "use_cudnn": use_cudnn, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": exclusive, "data_format": data_format, }) return pool_out @deprecated(since="2.0.0") @templatedoc(op_type="pool2d") def adaptive_pool2d(input, pool_size, pool_type="max", require_index=False, name=None): r""" This operation calculates the output based on the input, pool_size, pool_type parameters. Input(X) and output(Out) are in NCHW format, where N is batch size, C is the number of channels, H is the height of the feature, and W is the width of the feature. Parameters(pool_size) should contain two elements which represent height and width, respectively. Also the H and W dimensions of output(Out) is same as Parameter(pool_size). The output tensor shape will be [N, C, pool_size[0], pool_size[1]] For average adaptive pool2d: .. math:: hstart &= floor(i * H_{in} / H_{out}) hend &= ceil((i + 1) * H_{in} / H_{out}) wstart &= floor(j * W_{in} / W_{out}) wend &= ceil((j + 1) * W_{in} / W_{out}) Output(i ,j) &= \\frac{sum(Input[hstart:hend, wstart:wend])}{(hend - hstart) * (wend - wstart)} Args: input (Tensor): The input tensor of pooling operator, which is a 4-D tensor with shape [N, C, H, W]. The format of input tensor is NCHW, where N is batch size, C is the number of channels, H is the height of the feature, and W is the width of the feature. The data type is float32 or float64. pool_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain two integers, (pool_size_Height, pool_size_Width). pool_type: ${pooling_type_comment} require_index (bool): If true, the index of max pooling point will be returned along with outputs. It cannot be set in average pooling type. Default False. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of adaptive pooling result. The data type is same as input tensor. Raises: ValueError: 'pool_type' is not 'max' nor 'avg'. ValueError: invalid setting 'require_index' true when 'pool_type' is 'avg'. ValueError: 'pool_size' should be a list or tuple with length as 2. Examples: .. code-block:: python # average adaptive pool2d # suppose input data in shape of [N, C, H, W], `pool_size` is [m, n], # output shape is [N, C, m, n], adaptive pool divide H and W dimensions # of input data into m * n grids averagely and performs poolings in each # grid to get output. # adaptive average pool performs calculations as follow: # # for i in range(m): # for j in range(n): # hstart = floor(i * H / m) # hend = ceil((i + 1) * H / m) # wstart = floor(i * W / n) # wend = ceil((i + 1) * W / n) # output[:, :, i, j] = avg(input[:, :, hstart: hend, wstart: wend]) # import paddle paddle.enable_static() data = paddle.rand(shape=[1,3,32,32]) pool_out = paddle.fluid.layers.adaptive_pool2d( input=data, pool_size=[3, 3], pool_type='avg') # max adaptive pool2d # suppose input data in shape of [N, C, H, W], `pool_size` is [m, n], # output shape is [N, C, m, n], adaptive pool divide H and W dimensions # of input data into m * n grids averagely and performs poolings in each # grid to get output. # adaptive average pool performs calculations as follow: # # for i in range(m): # for j in range(n): # hstart = floor(i * H / m) # hend = ceil((i + 1) * H / m) # wstart = floor(i * W / n) # wend = ceil((i + 1) * W / n) # output[:, :, i, j] = max(input[:, :, hstart: hend, wstart: wend]) # import paddle data = paddle.rand(shape=[1,3,32,32]) pool_out = paddle.fluid.layers.adaptive_pool2d( input=data, pool_size=[3, 3], pool_type='max') """ check_variable_and_dtype( input, 'input', ['float16', 'float32', 'float64', 'int32', 'int64'], 'adaptive_pool2d') check_type(pool_type, 'pool_type', str, 'adaptive_pool2d') check_type(pool_size, 'pool_size', (int, list, tuple), 'adaptive_pool2d') check_type(require_index, 'require_index', bool, 'adaptive_pool2d') if pool_type not in ["max", "avg"]: raise ValueError( "Unknown pool_type: '%s'. It can only be 'max' or 'avg'.", str(pool_type)) if pool_type == "avg" and require_index: raise ValueError( "invalid setting 'require_index' true when 'pool_type' is 'avg'.") pool_size = utils.convert_to_list(pool_size, 2, 'pool_size') if pool_type == "max": l_type = 'max_pool2d_with_index' else: l_type = "pool2d" helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype() pool_out = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out} if pool_type == "max": mask = helper.create_variable_for_type_inference(dtype) outputs["Mask"] = mask helper.append_op( type=l_type, inputs={"X": input}, outputs=outputs, attrs={ "pooling_type": pool_type, "ksize": pool_size, "adaptive": True, }) return (pool_out, mask) if require_index else pool_out @deprecated(since="2.0.0") @templatedoc(op_type="pool3d") def adaptive_pool3d(input, pool_size, pool_type="max", require_index=False, name=None): r""" This operation calculates the output based on the input, pool_size, pool_type parameters. Input(X) and output(Out) are in NCDHW format, where N is batch size, C is the number of channels, D is the depth of the feature, H is the height of the feature, and W is the width of the feature. Parameters(pool_size) should contain three elements which represent height and width, respectively. Also the D, H and W dimensions of output(Out) is same as Parameter(pool_size). The output tensor shape will be [N, C, pool_size[0], pool_size[1], pool_size[2]] For average adaptive pool3d: .. math:: dstart &= floor(i * D_{in} / D_{out}) dend &= ceil((i + 1) * D_{in} / D_{out}) hstart &= floor(j * H_{in} / H_{out}) hend &= ceil((j + 1) * H_{in} / H_{out}) wstart &= floor(k * W_{in} / W_{out}) wend &= ceil((k + 1) * W_{in} / W_{out}) Output(i ,j, k) &= \\frac{sum(Input[dstart:dend, hstart:hend, wstart:wend])}{(dend - dstart) * (hend - hstart) * (wend - wstart)} Args: input (Tensor): The input tensor of pooling operator, which is a 5-D tensor with shape [N, C, D, H, W]. The format of input tensor is NCDHW, where N is batch size, C is the number of channels, D is the depth of the feature, H is the height of the feature, and W is the width of the feature. The data type is float32 or float64. pool_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain three integers, (Depth, Height, Width). pool_type: ${pooling_type_comment} require_index (bool): If true, the index of max pooling point will be returned along with outputs. It cannot be set in average pooling type. Default False. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of adaptive pooling result. The data type is same as input tensor. Raises: ValueError: 'pool_type' is not 'max' nor 'avg'. ValueError: invalid setting 'require_index' true when 'pool_type' is 'avg'. ValueError: 'pool_size' should be a list or tuple with length as 2. Examples: .. code-block:: python # average adaptive pool3d # suppose input data in shape of [N, C, D, H, W], `pool_size` is [l, m, n], # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions # of input data into l * m * n grids averagely and performs poolings in each # grid to get output. # adaptive average pool performs calculations as follow: # # for i in range(l): # for j in range(m): # for k in range(n): # dstart = floor(i * D / l) # dend = ceil((i + 1) * D / l) # hstart = floor(j * H / m) # hend = ceil((j + 1) * H / m) # wstart = floor(k * W / n) # wend = ceil((k + 1) * W / n) # output[:, :, i, j, k] = # avg(input[:, :, dstart:dend, hstart: hend, wstart: wend]) # import paddle paddle.enable_static() data = paddle.rand(shape=[1,3,32,32,32]) pool_out = paddle.fluid.layers.adaptive_pool3d( input=data, pool_size=[3, 3, 3], pool_type='avg') # max adaptive pool3d # suppose input data in shape of [N, C, D, H, W], `pool_size` is [l, m, n], # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions # of input data into l * m * n grids averagely and performs poolings in each # grid to get output. # adaptive average pool performs calculations as follow: # # for i in range(l): # for j in range(m): # for k in range(n): # dstart = floor(i * D / l) # dend = ceil((i + 1) * D / l) # hstart = floor(j * H / m) # hend = ceil((j + 1) * H / m) # wstart = floor(k * W / n) # wend = ceil((k + 1) * W / n) # output[:, :, i, j, k] = # avg(input[:, :, dstart:dend, hstart: hend, wstart: wend]) # import paddle data = paddle.rand(shape=[1,3,32,32,32]) pool_out = paddle.fluid.layers.adaptive_pool3d( input=data, pool_size=[3, 3, 3], pool_type='max') """ check_variable_and_dtype( input, 'input', ['float16', 'float32', 'float64', 'int32', 'int64'], 'adaptive_pool3d') check_type(pool_type, 'pool_type', str, 'adaptive_pool3d') check_type(pool_size, 'pool_size', (int, list, tuple), 'adaptive_pool3d') check_type(require_index, 'require_index', bool, 'adaptive_pool3d') if pool_type not in ["max", "avg"]: raise ValueError( "Unknown pool_type: '%s'. It can only be 'max' or 'avg'.", str(pool_type)) if pool_type == "avg" and require_index: raise ValueError( "invalid setting 'require_index' true when 'pool_type' is 'avg'.") pool_size = utils.convert_to_list(pool_size, 3, 'pool_size') if pool_type == "max": l_type = 'max_pool3d_with_index' else: l_type = "pool3d" helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype() pool_out = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out} if pool_type == "max": mask = helper.create_variable_for_type_inference(dtype) outputs["Mask"] = mask helper.append_op( type=l_type, inputs={"X": input}, outputs=outputs, attrs={ "pooling_type": pool_type, "ksize": pool_size, "adaptive": True, }) return (pool_out, mask) if require_index else pool_out def batch_norm(input, act=None, is_test=False, momentum=0.9, epsilon=1e-05, param_attr=None, bias_attr=None, data_layout='NCHW', in_place=False, name=None, moving_mean_name=None, moving_variance_name=None, do_model_average_for_mean_and_var=True, use_global_stats=False): r""" :api_attr: Static Graph **Batch Normalization Layer** Can be used as a normalizer function for convolution or fully_connected operations. The required data format for this layer is one of the following: 1. NHWC `[batch, in_height, in_width, in_channels]` 2. NCHW `[batch, in_channels, in_height, in_width]` Refer to `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift <https://arxiv.org/pdf/1502.03167.pdf>`_ for more details. :math:`input` is the input features over a mini-batch. .. math:: \\mu_{\\beta} &\\gets \\frac{1}{m} \\sum_{i=1}^{m} x_i \\qquad &//\\ \ mini-batch\ mean \\\\ \\sigma_{\\beta}^{2} &\\gets \\frac{1}{m} \\sum_{i=1}^{m}(x_i - \\ \\mu_{\\beta})^2 \\qquad &//\ mini-batch\ variance \\\\ \\hat{x_i} &\\gets \\frac{x_i - \\mu_\\beta} {\\sqrt{\\ \\sigma_{\\beta}^{2} + \\epsilon}} \\qquad &//\ normalize \\\\ y_i &\\gets \\gamma \\hat{x_i} + \\beta \\qquad &//\ scale\ and\ shift moving\_mean = moving\_mean * momentum + mini-batch\_mean * (1. - momentum) \\\\ moving\_var = moving\_var * momentum + mini-batch\_var * (1. - momentum) moving_mean is global mean and moving_var is global variance. When use_global_stats = True, the :math:`\\mu_{\\beta}` and :math:`\\sigma_{\\beta}^{2}` are not the statistics of one mini-batch. They are global (or running) statistics. (It usually got from the pre-trained model.) The training and testing (or inference) have the same behavior: .. math:: \\hat{x_i} &\\gets \\frac{x_i - \\mu_\\beta} {\\sqrt{\\ \\sigma_{\\beta}^{2} + \\epsilon}} \\\\ y_i &\\gets \\gamma \\hat{x_i} + \\beta Note: if build_strategy.sync_batch_norm=True, the batch_norm in network will use sync_batch_norm automatically. `is_test = True` can only be used in test program and inference program, `is_test` CANNOT be set to True in train program, if you want to use global status from pre_train model in train program, please set `use_global_stats = True`. Args: input(Tensor): The rank of input Tensor can be 2, 3, 4, 5. The data type is float16 or float32 or float64. act(string, Default None): Activation type, linear|relu|prelu|... is_test (bool, Default False): A flag indicating whether it is in test phrase or not. momentum(float|Tensor, Default 0.9): The value used for the moving_mean and moving_var computation. This should be a float number or a Tensor with shape [1] and data type as float32. The updated formula is: :math:`moving\_mean = moving\_mean * momentum + new\_mean * (1. - momentum)` :math:`moving\_var = moving\_var * momentum + new\_var * (1. - momentum)` Default is 0.9. epsilon(float, Default 1e-05): A value added to the denominator for numerical stability. Default is 1e-5. param_attr(ParamAttr|None): The parameter attribute for Parameter `scale` of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm will create ParamAttr as param_attr, the name of scale can be set in ParamAttr. If the Initializer of the param_attr is not set, the parameter is initialized with Xavier. Default: None. bias_attr(ParamAttr|None): The parameter attribute for the bias of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. data_layout (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. in_place(bool, Default False): Make the input and output of batch norm reuse memory. name(str|None): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. moving_mean_name(str, Default None): The name of moving_mean which store the global Mean. If it is set to None, batch_norm will save global mean with a random name, otherwise, batch_norm will save global mean with the string. moving_variance_name(str, Default None): The name of the moving_variance which store the global Variance. If it is set to None, batch_norm will save global variance with a random name, otherwise, batch_norm will save global variance with the string. do_model_average_for_mean_and_var(bool, Default True): Whether parameter mean and variance should do model average when model average is enabled. use_global_stats(bool, Default False): Whether to use global mean and variance. In inference or test mode, set use_global_stats to true or is_test to true, and the behavior is equivalent. In train mode, when setting use_global_stats True, the global mean and variance are also used during train period. Returns: A Tensor which is the result after applying batch normalization on the input, has same shape and data type with input. Examples: .. code-block:: python import paddle paddle.enable_static() x = paddle.static.data(name='x', shape=[3, 7, 3, 7], dtype='float32') hidden1 = paddle.static.nn.fc(x=x, size=200) print(hidden1.shape) # [3, 200] hidden2 = paddle.static.nn.batch_norm(input=hidden1) print(hidden2.shape) # [3, 200] """ assert bias_attr is not False, "bias_attr should not be False in batch_norm." helper = LayerHelper('batch_norm', **locals()) check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'], 'batch_norm') dtype = helper.input_dtype() # use fp32 for bn parameter if dtype == core.VarDesc.VarType.FP16: dtype = core.VarDesc.VarType.FP32 input_shape = input.shape if data_layout == 'NCHW': channel_num = input_shape[1] else: if data_layout == 'NHWC': channel_num = input_shape[-1] else: raise ValueError("unsupported data layout:" + data_layout) param_shape = [channel_num] # create parameter scale = helper.create_parameter( attr=helper.param_attr, shape=param_shape, dtype=dtype, default_initializer=Constant(1.0)) bias = helper.create_parameter( attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True) mean = helper.create_parameter( attr=ParamAttr( name=moving_mean_name, initializer=Constant(0.0), trainable=False, do_model_average=do_model_average_for_mean_and_var), shape=param_shape, dtype=dtype) mean.stop_gradient = True variance = helper.create_parameter( attr=ParamAttr( name=moving_variance_name, initializer=Constant(1.0), trainable=False, do_model_average=do_model_average_for_mean_and_var), shape=param_shape, dtype=dtype) variance.stop_gradient = True # create output # mean and mean_out share the same memory mean_out = mean # variance and variance_out share the same memory variance_out = variance saved_mean = helper.create_variable_for_type_inference( dtype=dtype, stop_gradient=True) saved_variance = helper.create_variable_for_type_inference( dtype=dtype, stop_gradient=True) reserve_space = None if not is_test: reserve_space = helper.create_variable_for_type_inference( dtype=helper.input_dtype(), stop_gradient=True) batch_norm_out = input if in_place else \ helper.create_variable_for_type_inference(dtype) inputs = { "X": input, "Scale": scale, "Bias": bias, "Mean": mean, "Variance": variance } attrs = { "epsilon": epsilon, "is_test": is_test, "data_layout": data_layout, "use_mkldnn": False, "fuse_with_relu": False, "use_global_stats": use_global_stats } if isinstance(momentum, Variable): inputs['MomemtumTensor'] = momentum else: attrs['momentum'] = momentum outputs = { "Y": batch_norm_out, "MeanOut": mean_out, "VarianceOut": variance_out, "SavedMean": saved_mean, "SavedVariance": saved_variance } if reserve_space is not None: outputs["ReserveSpace"] = reserve_space helper.append_op( type="batch_norm", inputs=inputs, outputs=outputs, attrs=attrs) return helper.append_activation(batch_norm_out) def inplace_abn(input, act=None, is_test=False, momentum=0.9, epsilon=1e-05, param_attr=None, bias_attr=None, data_layout='NCHW', name=None, moving_mean_name=None, moving_variance_name=None, do_model_average_for_mean_and_var=True, use_global_stats=False, act_alpha=1.0): r""" **In-place Activation Batch Normalization Layer** This layer calculates batch normalization and activation with in-place memory. For batch normalization calculations, see `fluid.layers.batch_norm`. For in-place activation batch normalization, see `In-Place Activated BatchNorm for Memory-Optimized Training of DNNs <https://arxiv.org/abs/1712.02616>`_ `inplace_abn` only support activation type as `None`, `identity`, `leaky_relu`, `elu` currently. `inplace_abn` only support data type as `float32`, `float64` currently. Note: if build_strategy.sync_batch_norm=True, the batch_norm in network will use sync_batch_norm automatically. `is_test = True` can only be used in test program and inference program, `is_test` CANNOT be set to True in train program, if you want to use global status from pre_train model in train program, please set `use_global_stats = True`. Args: input(Variable): The rank of input variable can be 2, 3, 4, 5. The data type is float16 or float32 or float64. act(string, Default None): Activation type, linear|relu|prelu|... is_test (bool, Default False): A flag indicating whether it is in test phrase or not. momentum(float|Variable, Default 0.9): The value used for the moving_mean and moving_var computation. This should be a float number or a Variable with shape [1] and data type as float32. The updated formula is: :math:`moving\_mean = moving\_mean * momentum + new\_mean * (1. - momentum)` :math:`moving\_var = moving\_var * momentum + new\_var * (1. - momentum)` Default is 0.9. epsilon(float, Default 1e-05): A value added to the denominator for numerical stability. Default is 1e-5. param_attr(ParamAttr|None): The parameter attribute for Parameter `scale` of inplace_abn. If it is set to None or one attribute of ParamAttr, inplace_abn will create ParamAttr as param_attr, the name of scale can be set in ParamAttr. If the Initializer of the param_attr is not set, the parameter is initialized with Xavier. Default: None. bias_attr(ParamAttr|None): The parameter attribute for the bias of inplace_abn. If it is set to None or one attribute of ParamAttr, inplace_abn will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. data_layout (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. name(str|None): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. moving_mean_name(str, Default None): The name of moving_mean which store the global Mean. If it is set to None, inplace_abn will save global mean with a random name, otherwise, inplace_abn will save global mean with the string. moving_variance_name(str, Default None): The name of the moving_variance which store the global Variance. If it is set to None, inplace_abn, will save global variance with a random name, otherwise, inplace_abn will save global variance with the string. do_model_average_for_mean_and_var(bool, Default True): Whether parameter mean and variance should do model average when model average is enabled. use_global_stats(bool, Default False): Whether to use global mean and variance. In inference or test mode, set use_global_stats to true or is_test to true, and the behavior is equivalent. In train mode, when setting use_global_stats True, the global mean and variance are also used during train period. act_alpha(float, Default 1.0): when activation is in ['elu', 'identity', 'leaky_relu'], inplace activative batch normalization will be used, and alpha parameter for activation can be given by this parameter. Returns: A Variable holding Tensor which is the result after applying batch normalization and activation on the input, has same shape and data type with input. Examples: .. code-block:: python import paddle.fluid as fluid x = fluid.data(name='x', shape=[3, 7, 3, 7], dtype='float32') hidden1 = fluid.layers.fc(input=x, size=200, param_attr='fc1.w') hidden2 = fluid.layers.inplace_abn(input=hidden1) hidden3 = fluid.layers.inplace_abn(input=hidden2, act='leaky_relu', act_alpha=0.2) """ assert act in [None, 'identity', 'leaky_relu', 'elu'], \ "inplace_abn only support act as None, 'identity', " \ "'leaky_relu', 'elu' currently" assert bias_attr is not False, "bias_attr should not be False in inplace_abn." helper = LayerHelper('inplace_abn', **locals()) check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'inplace_abn') dtype = helper.input_dtype() input_shape = input.shape if data_layout == 'NCHW': channel_num = input_shape[1] else: if data_layout == 'NHWC': channel_num = input_shape[-1] else: raise ValueError("unsupported data layout:" + data_layout) param_shape = [channel_num] # create parameter scale = helper.create_parameter( attr=helper.param_attr, shape=param_shape, dtype=dtype, default_initializer=Constant(1.0)) bias = helper.create_parameter( attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True) mean = helper.create_parameter( attr=ParamAttr( name=moving_mean_name, initializer=Constant(0.0), trainable=False, do_model_average=do_model_average_for_mean_and_var), shape=param_shape, dtype=dtype) mean.stop_gradient = True variance = helper.create_parameter( attr=ParamAttr( name=moving_variance_name, initializer=Constant(1.0), trainable=False, do_model_average=do_model_average_for_mean_and_var), shape=param_shape, dtype=dtype) variance.stop_gradient = True # create output # mean and mean_out share the same memory mean_out = mean # variance and variance out share the same memory variance_out = variance saved_mean = helper.create_variable_for_type_inference( dtype=dtype, stop_gradient=True) saved_variance = helper.create_variable_for_type_inference( dtype=dtype, stop_gradient=True) reserve_space = helper.create_variable_for_type_inference( dtype=dtype, stop_gradient=True) batch_norm_out = input inputs = { "X": input, "Scale": scale, "Bias": bias, "Mean": mean, "Variance": variance } attrs = { "epsilon": epsilon, "is_test": is_test, "data_layout": data_layout, "use_mkldnn": False, "fuse_with_relu": False, "use_global_stats": use_global_stats, "activation": act, "alpha": act_alpha, } if isinstance(momentum, Variable): inputs['MomemtumTensor'] = momentum else: attrs['momentum'] = momentum outputs = { "Y": batch_norm_out, "MeanOut": mean_out, "VarianceOut": variance_out, "SavedMean": saved_mean, "SavedVariance": saved_variance } if reserve_space is not None: outputs["ReserveSpace"] = reserve_space helper.append_op( type="inplace_abn", inputs=inputs, outputs=outputs, attrs=attrs) return batch_norm_out def instance_norm(input, epsilon=1e-05, param_attr=None, bias_attr=None, name=None): r""" :api_attr: Static Graph **Instance Normalization Layer** Can be used as a normalizer function for convolution or fully_connected operations. The required data format for this layer is one of the following: DataLayout: NCHW `[batch, in_channels, in_height, in_width]` Refer to `Instance Normalization: The Missing Ingredient for Fast Stylization <https://arxiv.org/pdf/1607.08022.pdf>`_ for more details. :math:`input` is the input features over a mini-batch. .. math:: \\mu_{\\beta} &\\gets \\frac{1}{HW} \\sum_{i=1}^{HW} x_i \\qquad &//\\ \\ mean\ of\ one\ feature\ map\ in\ mini-batch \\\\ \\sigma_{\\beta}^{2} &\\gets \\frac{1}{HW} \\sum_{i=1}^{HW}(x_i - \\ \\mu_{\\beta})^2 \\qquad &//\ variance\ of\ one\ feature\ map\ in\ mini-batch \\\\ \\hat{x_i} &\\gets \\frac{x_i - \\mu_\\beta} {\\sqrt{\\ \\sigma_{\\beta}^{2} + \\epsilon}} \\qquad &//\ normalize \\\\ y_i &\\gets \\gamma \\hat{x_i} + \\beta \\qquad &//\ scale\ and\ shift Note: `H` means height of feature map, `W` means width of feature map. Args: input(Tensor): The rank of input tensor can be 2, 3, 4, 5. The data type is float32 or float64. epsilon(float, Default 1e-05): A value added to the denominator for numerical stability. Default is 1e-5. param_attr(ParamAttr|None|bool, optional): The parameter attribute for Parameter `scale` of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm will create ParamAttr as param_attr, the name of scale can be set in ParamAttr. If the Initializer of the param_attr is not set, the parameter is initialized with Xavier. If the param_attr is set to False, instance_norm will not create param_attr. Default: None. bias_attr(ParamAttr|None|bool, optional): The parameter attribute for the bias of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. If the Initializer of the bias_attr is not set, the bias is initialized zero. If the bias_attr is set to False, instance_norm will not create bias_attr. Default: None. name(string, Default None): A name for this layer(optional). If set None, the layer will be named automatically. Returns: A Tensor which is the result after applying instance normalization on the input, has same shape and data type with input. Examples: .. code-block:: python import paddle paddle.enable_static() x = paddle.static.data(name='x', shape=[3, 7, 3, 7], dtype='float32') hidden1 = paddle.static.nn.fc(x, size=200) hidden2 = paddle.static.nn.instance_norm(hidden1) """ check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'instance_norm') if param_attr is False: assert bias_attr is False, "param_attr and bias_attr must be set to Fasle at the same time in instance_norm" helper = LayerHelper('instance_norm', **locals()) dtype = helper.input_dtype() # use fp32 for in parameter if dtype == core.VarDesc.VarType.FP16: dtype = core.VarDesc.VarType.FP32 input_shape = input.shape if len(input.shape) < 2 or len(input.shape) > 5: raise ValueError( 'expected 2D or 3D or 4D or 5D input (got {}D input, input shape is: {})'. format(len(input.shape), input_shape)) channel_num = input_shape[1] param_shape = [channel_num] if param_attr != False and bias_attr != False: # create parameter scale = helper.create_parameter( attr=helper.param_attr, shape=param_shape, dtype=dtype, default_initializer=Constant(1.0)) bias = helper.create_parameter( attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True, default_initializer=Constant(0.0)) # create output saved_mean = helper.create_variable_for_type_inference( dtype=dtype, stop_gradient=True) saved_variance = helper.create_variable_for_type_inference( dtype=dtype, stop_gradient=True) instance_norm_out = helper.create_variable_for_type_inference(dtype) inputs = {"X": input} if param_attr != False and bias_attr != False: inputs["Scale"] = scale inputs["Bias"] = bias helper.append_op( type="instance_norm", inputs=inputs, outputs={ "Y": instance_norm_out, "SavedMean": saved_mean, "SavedVariance": saved_variance }, attrs={"epsilon": epsilon, }) return instance_norm_out @static_only def data_norm(input, act=None, epsilon=1e-05, param_attr=None, data_layout='NCHW', in_place=False, name=None, moving_mean_name=None, moving_variance_name=None, do_model_average_for_mean_and_var=True, slot_dim=-1, sync_stats=False, summary_decay_rate=0.9999999, enable_scale_and_shift=False): r""" :api_attr: Static Graph **Data Normalization Layer** This op can be used as a normalizer function for conv2d and fully_connected operations. The required data format for this layer is one of the following: 1. NHWC `[batch, in_height, in_width, in_channels]` 2. NCHW `[batch, in_channels, in_height, in_width]` :math:`input` is the input features over a mini-batch. .. math:: \\mu_{\\beta} &\\gets \\frac{1}{m} \\sum_{i=1}^{m} x_i \\qquad &//\\ \ mini-batch\ mean \\\\ \\sigma_{\\beta}^{2} &\\gets \\frac{1}{m} \\sum_{i=1}^{m}(x_i - \\ \\mu_{\\beta})^2 \\qquad &//\ mini-batch\ variance \\\\ \\hat{x_i} &\\gets \\frac{x_i - \\mu_\\beta} {\\sqrt{\\ \\sigma_{\\beta}^{2} + \\epsilon}} \\qquad &//\ normalize \\\\ y_i &\\gets \\gamma \\hat{x_i} + \\beta \\qquad &//\ scale\ and\ shift Args: input(Tensor): The input Tensor. act(string, Default None): Activation type, linear|relu|prelu|... epsilon(float, Default 1e-05): param_attr(ParamAttr): The parameter attribute for Parameter `scale`. data_layout (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. in_place(bool, Default False): Make the input and output of batch norm reuse memory. name(string, Default None): A name for this layer(optional). If set None, the layer will be named automatically. moving_mean_name(string, Default None): The name of moving_mean which store the global Mean. moving_variance_name(string, Default None): The name of the moving_variance which store the global Variance. do_model_average_for_mean_and_var(bool, Default True): Whether parameter mean and variance should do model average when model average is enabled. slot_dim(int): The embedding dimension of one slot. Slot is a set of one specific feature. In pslib mode, we distinguish feature ids by slot and pull their embeddings from parameter server (pslib). The first place of the embedding is the historical show number (occurence time of this feature id with a label 0). If the input of this op is concated by slot-wise embeddings, and the show number is zero when this slot is new or empty, the normalization result may be impractical. To avoid this, we add slot_dim to locate the show number and judge if the show number is zero. If so, we choose to skip normalization on this embedding. sync_stats(bool, Default False): When running with multiple GPU cards, using allreduce to sync the summary messages. summary_decay_rate(float, Default 0.9999999): The decay rate when updating summary. enable_scale_and_shift(bool, Default False): do scale&shift after normalization. Returns: Tensor: A tensor which is the result after applying data normalization on the input. Examples: .. code-block:: python import paddle paddle.enable_static() x = paddle.randn(shape=[32,100]) hidden2 = paddle.static.nn.data_norm(input=x) """ helper = LayerHelper('data_norm', **locals()) dtype = helper.input_dtype() input_shape = input.shape if data_layout == 'NCHW': channel_num = input_shape[1] else: if data_layout == 'NHWC': channel_num = input_shape[-1] else: raise ValueError("unsupported data layout:" + data_layout) param_shape = [channel_num] batch_size_default = 1e4 batch_sum_default = 0.0 batch_square_sum_default = 1e4 scale_w_default = 1.0 bias_default = 0.0 if param_attr and isinstance(param_attr, dict): batch_size_default = param_attr.get("batch_size", 1e4) batch_sum_default = param_attr.get("batch_sum", 0.0) batch_square_sum_default = param_attr.get("batch_square", 1e4) if enable_scale_and_shift: scale_w_default = param_attr.get("scale_w", 1.0) bias_default = param_attr.get("bias", 0.0) # create scale and shift(bias) when enable_scale_and_shift is True if name == None: name = "dn" if enable_scale_and_shift: scale_w = helper.create_parameter( attr=ParamAttr( name=name + '.scale_w', initializer=Constant(value=float(scale_w_default)), trainable=True), shape=param_shape, dtype=input.dtype) bias = helper.create_parameter( attr=ParamAttr( name=name + '.bias', initializer=Constant(value=float(bias_default)), trainable=True), shape=param_shape, dtype=input.dtype) # create parameter batch_size = helper.create_parameter( attr=ParamAttr( name=name + '.batch_size', initializer=Constant(value=float(batch_size_default)), trainable=True), shape=param_shape, dtype=input.dtype) batch_sum = helper.create_parameter( attr=ParamAttr( name=name + '.batch_sum', initializer=Constant(value=float(batch_sum_default)), trainable=True), shape=param_shape, dtype=input.dtype) batch_square_sum = helper.create_parameter( attr=ParamAttr( name=name + '.batch_square_sum', initializer=Constant(value=float(batch_square_sum_default)), trainable=True), shape=param_shape, dtype=input.dtype) means = helper.create_variable(dtype=dtype, stop_gradient=True) scales = helper.create_variable(dtype=dtype, stop_gradient=True) data_norm_out = input if in_place else helper.create_variable(dtype=dtype) inputs = { "X": input, "BatchSize": batch_size, "BatchSum": batch_sum, "BatchSquareSum": batch_square_sum } attrs = { "epsilon": epsilon, "data_layout": data_layout, "sync_stats": sync_stats, "summary_decay_rate": summary_decay_rate, } if slot_dim > 0: attrs["slot_dim"] = slot_dim if enable_scale_and_shift: attrs["enable_scale_and_shift"] = enable_scale_and_shift if enable_scale_and_shift: inputs["scale_w"] = scale_w inputs["bias"] = bias helper.append_op( type="data_norm", inputs=inputs, outputs={ "Y": data_norm_out, "Means": means, "Scales": scales, "BatchSize": batch_size, "BatchSum": batch_sum, "BatchSquareSum": batch_square_sum }, attrs=attrs) return helper.append_activation(data_norm_out) @templatedoc() def layer_norm(input, scale=True, shift=True, begin_norm_axis=1, epsilon=1e-05, param_attr=None, bias_attr=None, act=None, name=None): r""" :api_attr: Static Graph **Layer Normalization Layer** The API implements the function of the Layer Normalization Layer and can be applied to mini-batch input data. Refer to `Layer Normalization <https://arxiv.org/pdf/1607.06450v1.pdf>`_ The formula is as follows: .. math:: \\mu & = \\frac{1}{H}\\sum_{i=1}^{H} x_i \\sigma & = \\sqrt{\\frac{1}{H}\sum_{i=1}^{H}{(x_i - \\mu)^2} + \\epsilon} y & = f(\\frac{g}{\\sigma}(x - \\mu) + b) - :math:`x`: the vector representation of the summed inputs to the neurons in that layer. - :math:`H`: the number of hidden units in a layers - :math:`\\epsilon`: the small value added to the variance to prevent division by zero. - :math:`g`: the trainable scale parameter. - :math:`b`: the trainable bias parameter. Args: input(Tensor): A multi-dimension ``Tensor`` , and the data type is float32 or float64. scale(bool, optional): Whether to learn the adaptive gain :math:`g` after normalization. Default: True. shift(bool, optional): Whether to learn the adaptive bias :math:`b` after normalization. Default: True. begin_norm_axis(int, optional): The normalization will be performed along dimensions from :attr:`begin_norm_axis` to :attr:`rank(input)`. Default: 1. epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-05. param_attr(ParamAttr, optional): The parameter attribute for the learnable gain :math:`g`. If :attr:`scale` is False, :attr:`param_attr` is omitted. If :attr:`scale` is True and :attr:`param_attr` is None, a default :code:`ParamAttr` would be added as scale. The :attr:`param_attr` is initialized as 1 if it is added. Default: None. bias_attr(ParamAttr, optional): The parameter attribute for the learnable bias :math:`b`. If :attr:`shift` is False, :attr:`bias_attr` is omitted. If :attr:`shift` is True and :attr:`param_attr` is None, a default :code:`ParamAttr` would be added as bias. The :attr:`bias_attr` is initialized as 0 if it is added. Default: None. act(str, optional): Activation to be applied to the output of layer normalization. Default: None. name(str): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Tensor: ``Tensor`` indicating the normalized result, the data type is the same as ``input`` , and the return dimension is the same as ``input`` . Examples: .. code-block:: python import paddle paddle.enable_static() x = paddle.static.data(name='x', shape=[8, 32, 32], dtype='float32') output = paddle.static.nn.layer_norm(input=x, begin_norm_axis=1) print(output.shape) # [8, 32, 32] """ assert in_dygraph_mode( ) is not True, "please use LayerNorm instead of layer_norm in dygraph mode!" helper = LayerHelper('layer_norm', **locals()) check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'layer_norm') dtype = helper.input_dtype() # create intput and parameters inputs = {'X': input} input_shape = input.shape param_shape = [reduce(lambda x, y: x * y, input_shape[begin_norm_axis:])] if scale: assert param_attr is not False, "param_attr should not be False when using scale." scale = helper.create_parameter( attr=helper.param_attr, shape=param_shape, dtype=dtype, default_initializer=Constant(1.0)) inputs['Scale'] = scale else: if param_attr: warnings.warn("param_attr is only available with scale is True.") if shift: assert bias_attr is not False, "bias_attr should not be False when using shift." bias = helper.create_parameter( attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True) inputs['Bias'] = bias else: if bias_attr: warnings.warn("bias_attr is only available with shift is True.") # create output mean_out = helper.create_variable_for_type_inference( dtype=dtype, stop_gradient=True) variance_out = helper.create_variable_for_type_inference( dtype=dtype, stop_gradient=True) layer_norm_out = helper.create_variable_for_type_inference(dtype) helper.append_op( type="layer_norm", inputs=inputs, outputs={ "Y": layer_norm_out, "Mean": mean_out, "Variance": variance_out, }, attrs={"epsilon": epsilon, "begin_norm_axis": begin_norm_axis}) return helper.append_activation(layer_norm_out) @templatedoc() def group_norm(input, groups, epsilon=1e-05, param_attr=None, bias_attr=None, act=None, data_layout='NCHW', name=None): """ :api_attr: Static Graph **Group Normalization Layer** Refer to `Group Normalization <https://arxiv.org/abs/1803.08494>`_ . Parameters: input(Tensor): Tensor with dimension greater than 1, the data type is float32 or float64. groups(int): The number of groups that divided from channels, the data type is int32. epsilon(float, optional): The small value added to the variance to prevent division by zero, the data type is float32. Default: 1e-05. param_attr(ParamAttr|bool, optional): ParamAttr object that specifies weight parameter attribute. If a bool type, only False is supported, which means there is no weight parameter. Default: None, the default weight parameter attribute is used. For more information, please refer to :ref:`api_guide_ParamAttr` . bias_attr(ParamAttr|bool, optional): ParamAttr object that specifies bias parameter attribute. If a bool type, only False is supported, which means there is no bias parameter. Default: None, the default bias parameter attribute is used. For more information, please refer to :ref:`api_guide_ParamAttr` . act(str, optional): Activation to be applied to the output of group normalization. data_layout(str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, *]`. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Tensor: A Tensor has same data type and data format with `input`. Examples: .. code-block:: python import paddle paddle.enable_static() data = paddle.static.data(name='data', shape=[2, 8, 32, 32], dtype='float32') x = paddle.static.nn.group_norm(input=data, groups=4) print(x.shape) # [2, 8, 32, 32] """ helper = LayerHelper('group_norm', **locals()) dtype = helper.input_dtype() check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'group_norm') # create intput and parameters inputs = {'X': input} input_shape = input.shape if len(input_shape) < 2: raise ValueError( f"The dimensions of Op(fluid.layers.group_norm)'s input should be more than 1. But received {len(input_shape)}" ) if data_layout != 'NCHW' and data_layout != 'NHWC': raise ValueError( "Param(data_layout) of Op(fluid.layers.group_norm) got wrong value: received " + data_layout + " but only NCHW or NHWC supported.") channel_num = input_shape[1] if data_layout == 'NCHW' else input_shape[-1] param_shape = [channel_num] if param_attr: scale = helper.create_parameter( attr=helper.param_attr, shape=param_shape, dtype=dtype, default_initializer=Constant(1.0)) inputs['Scale'] = scale if bias_attr: bias = helper.create_parameter( attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True) inputs['Bias'] = bias # create output mean_out = helper.create_variable(dtype=dtype, stop_gradient=True) variance_out = helper.create_variable(dtype=dtype, stop_gradient=True) group_norm_out = helper.create_variable(dtype=dtype) helper.append_op( type="group_norm", inputs=inputs, outputs={ "Y": group_norm_out, "Mean": mean_out, "Variance": variance_out, }, attrs={ "epsilon": epsilon, "groups": groups, "data_layout": data_layout }) return helper.append_activation(group_norm_out) @templatedoc() def spectral_norm(weight, dim=0, power_iters=1, eps=1e-12, name=None): r""" :api_attr: Static Graph **Spectral Normalization Layer** This operation calculates the spectral normalization value of weight parameters of fc, conv1d, conv2d, conv3d layers which should be 2-D, 3-D, 4-D, 5-D Parameters. Output tensor will be in same shape with input tensor. Calculations are showed as follows. Step 1: Generate vector U in shape of [H], and V in shape of [W]. While H is the :attr:`dim` th dimension of the input weights, and W is the product result of remaining dimensions. Step 2: :attr:`power_iters` should be a positive integer, do following calculations with U and V for :attr:`power_iters` rounds. Calculations as follows: .. math:: \mathbf{v} := \\frac{\mathbf{W}^{T} \mathbf{u}}{\|\mathbf{W}^{T} \mathbf{u}\|_2} \mathbf{u} := \\frac{\mathbf{W}^{T} \mathbf{v}}{\|\mathbf{W}^{T} \mathbf{v}\|_2} Step 3: Calculate :math:`\sigma(\mathbf{W})` and normalize weight values. .. math:: \sigma(\mathbf{W}) = \mathbf{u}^{T} \mathbf{W} \mathbf{v} \mathbf{W} = \\frac{\mathbf{W}}{\sigma(\mathbf{W})} Refer to `Spectral Normalization <https://arxiv.org/abs/1802.05957>`_ . Args: weight(Tensor): ${weight_comment} dim(int): ${dim_comment} power_iters(int): ${power_iters_comment} eps(float): ${eps_comment} name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: A tensor of weight parameters after spectral normalization. The data type and shape is same as input tensor. Examples: .. code-block:: python import paddle paddle.enable_static() weight = paddle.static.data(name='weight', shape=[2, 8, 32, 32], dtype='float32') x = paddle.static.nn.spectral_norm(weight=weight, dim=1, power_iters=2) print(x.shape) # [2, 8, 32, 32] """ helper = LayerHelper('spectral_norm', **locals()) check_variable_and_dtype(weight, 'weight', ['float32', 'float64'], 'spectral_norm') check_type(dim, 'dim', int, 'spectral_norm') check_type(power_iters, 'power_iters', int, 'spectral_norm') check_type(eps, 'eps', float, 'spectral_norm') dtype = weight.dtype # create intput and parameters inputs = {'Weight': weight} input_shape = weight.shape assert weight.numel() > 0, "Any dimension of input cannot be equal to 0." assert dim < len(input_shape), ("The input `dim` should be less than the " "rank of `weight`, but received dim=" "{}".format(dim)) h = input_shape[dim] w = np.prod(input_shape) // h u = helper.create_parameter( attr=ParamAttr(), shape=[h], dtype=dtype, default_initializer=Normal(0., 1.)) u.stop_gradient = True inputs['U'] = u v = helper.create_parameter( attr=ParamAttr(), shape=[w], dtype=dtype, default_initializer=Normal(0., 1.)) inputs['V'] = v v.stop_gradient = True # create output out = helper.create_variable(dtype=dtype) helper.append_op( type="spectral_norm", inputs=inputs, outputs={"Out": out, }, attrs={ "dim": dim, "power_iters": power_iters, "eps": eps, }) return out def conv2d_transpose(input, num_filters, output_size=None, filter_size=None, padding=0, stride=1, dilation=1, groups=None, param_attr=None, bias_attr=None, use_cudnn=True, act=None, name=None, data_format='NCHW'): r""" :api_attr: Static Graph The convolution2D transpose layer calculates the output based on the input, filter, and dilations, strides, paddings. Input(Input) and output(Output) are in NCHW or NHWC format. Where N is batch size, C is the number of channels, H is the height of the feature, and W is the width of the feature. Parameters(dilations, strides, paddings) are two elements. These two elements represent height and width, respectively. The details of convolution transpose layer, please refer to the following explanation and references `therein <https://arxiv.org/pdf/1603.07285.pdf>`_. If bias attribution and activation type are provided, bias is added to the output of the convolution, and the corresponding activation function is applied to the final result. For each input :math:`X`, the equation is: .. math:: Out = \sigma (W \\ast X + b) Where: * :math:`X`: Input value, a 4-D Tensor with NCHW or NHWC format. * :math:`W`: Filter value, a 4-D Tensor with MCHW format. * :math:`\\ast`: Convolution operation. * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1]. * :math:`\\sigma`: Activation function. * :math:`Out`: Output value, a 4-D Tensor with data format 'NCHW' or 'NHWC', the shape of :math:`Out` and :math:`X` may be different. Example: - Input: Input shape: :math:`(N, C_{in}, H_{in}, W_{in})` Filter shape: :math:`(C_{in}, C_{out}, H_f, W_f)` - Output: Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` Where .. math:: H^\prime_{out} &= (H_{in} - 1) * strides[0] - pad_height_top - pad_height_bottom + dilations[0] * (H_f - 1) + 1 \\\\ W^\prime_{out} &= (W_{in} - 1) * strides[1] - pad_width_left - pad_width_right + dilations[1] * (W_f - 1) + 1 \\\\ H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[0] ] \\\\ W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[1] ] Note: The conv2d_transpose can be seen as the backward of the conv2d. For conv2d, when stride > 1, conv2d maps multiple input shape to the same output shape, so for conv2d_transpose, when stride > 1, input shape maps multiple output shape. If output_size is None, :math:`H_{out} = H^\prime_{out}, W_{out} = W^\prime_{out}`; else, the :math:`H_{out}` of the output size must between :math:`H^\prime_{out}` and :math:`H^\prime_{out} + strides[0]`, and the :math:`W_{out}` of the output size must between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[1]`, conv2d_transpose can compute the kernel size automatically. Args: input(Tensor): 4-D Tensor with [N, C, H, W] or [N, H, W, C] format, its data type is float32 or float64. num_filters(int): The number of the filter. It is as same as the output image channel. output_size(int|tuple, optional): The output image size. If output size is a tuple, it must contain two integers, (image_height, image_width). None if use filter_size, padding, and stride to calculate output_size. If output_size and filter_size are specified at the same time, They should follow the formula above. Default: None. output_size and filter_size should not be None at the same time. filter_size(int|tuple, optional): The filter size. If filter_size is a tuple, it must contain two integers, (filter_size_height, filter_size_width). Otherwise, filter_size_height = filter_size_width = filter_size. None if use output size to calculate filter_size. Default: None. filter_size and output_size should not be None at the same time. stride(int|tuple, optional): The stride size. It means the stride in transposed convolution. If stride is a tuple, it must contain two integers, (stride_height, stride_width). Otherwise, stride_height = stride_width = stride. Default: stride = 1. padding(str|int|list|tuple, optional): The padding size. It means the number of zero-paddings on both sides for each dimension. If `padding` is a string, either 'VALID' or 'SAME' which is the padding algorithm. If `padding` is a tuple or list, it could be in three forms: `[pad_height, pad_width]` or `[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when `data_format` is `"NCHW"`, `padding` can be in the form `[[0,0], [0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. when `data_format` is `"NHWC"`, `padding` can be in the form `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. Default: padding = 0. dilation(int|tuple, optional): The dilation size. It means the spacing between the kernel points. If dilation is a tuple, it must contain two integers, (dilation_height, dilation_width). Otherwise, dilation_height = dilation_width = dilation. Default: dilation = 1. filter_size(int|tuple, optional): The filter size. If filter_size is a tuple, it must contain two integers, (filter_size_height, filter_size_width). Otherwise, filter_size_height = filter_size_width = filter_size. None if use output size to calculate filter_size. Default: None. groups(int, optional): The groups number of the Conv2d transpose layer. Inspired by grouped convolution in Alex Krizhevsky's Deep CNN paper, in which when group=2, the first half of the filters is only connected to the first half of the input channels, while the second half of the filters is only connected to the second half of the input channels. Default: groups = 1. param_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights of conv2d_transpose. If it is set to None or one attribute of ParamAttr, conv2d_transpose will create ParamAttr as param_attr. If the Initializer of the param_attr is not set, the parameter is initialized with Xavier. Default: None. bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv2d_transpose. If it is set to False, no bias will be added to the output units. If it is set to None or one attribute of ParamAttr, conv2d_transpose will create ParamAttr as bias_attr. If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn library is installed. Default: True. act (str, optional): Activation type, if it is set to None, activation is not appended. Default: None. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. Returns: A Tensor representing the conv2d_transpose, whose data type is the same with input and shape is (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels). If act is None, the tensor storing the transposed convolution result, and if act is not None, the tensor storing transposed convolution and non-linearity activation result. Raises: ValueError: If the type of `use_cudnn` is not bool. ValueError: If `data_format` is not "NCHW" or "NHWC". ValueError: If `padding` is a string, but not "SAME" or "VALID". ValueError: If `padding` is a tuple, but the element corresponding to the input's batch size is not 0 or the element corresponding to the input's channel is not 0. ValueError: If `output_size` and filter_size are None at the same time. ShapeError: If the input is not 4-D Tensor. ShapeError: If the input's dimension size and filter's dimension size not equal. ShapeError: If the dimension size of input minus the size of `stride` is not 2. ShapeError: If the number of input channels is not equal to filter's channels. ShapeError: If the size of `output_size` is not equal to that of `stride`. Examples: .. code-block:: python import paddle paddle.enable_static() data = paddle.static.data(name='data', shape=[None, 3, 32, 32], dtype='float32') conv2d_transpose = paddle.static.nn.conv2d_transpose(input=data, num_filters=2, filter_size=3) print(conv2d_transpose.shape) # [-1, 2, 34, 34] """ assert param_attr is not False, "param_attr should not be False in conv2d_transpose." if len(input.shape) != 4: raise ValueError("Input size should be 4, " "but received {}".format(len(input.shape))) if data_format not in ['NCHW', 'NHWC']: raise ValueError( "Attr(data_format) of Op(fluid.layers.conv2d_transpose) got wrong value: received " + data_format + " but only NCHW or NHWC supported.") input_channel = input.shape[1] if data_format == 'NCHW' else input.shape[-1] op_type = 'conv2d_transpose' if (input_channel == groups and num_filters == input_channel and not use_cudnn): op_type = 'depthwise_conv2d_transpose' helper = LayerHelper(op_type, **locals()) if not isinstance(input, Variable): raise TypeError("Input of conv2d_transpose must be Variable") stride = utils.convert_to_list(stride, 2, 'stride') dilation = utils.convert_to_list(dilation, 2, 'dilation') if not isinstance(use_cudnn, bool): raise ValueError("use_cudnn should be True or False") def _update_padding(padding, data_format): def is_list_or_tuple(ele): if isinstance(ele, list) or isinstance(ele, tuple): return True return False if is_list_or_tuple(padding) and len(padding) == 4: if is_list_or_tuple(padding[0]) and (data_format == "NCHW"): if not (padding[0] == [0, 0] and padding[1] == [0, 0]): raise ValueError( "Non-zero padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[2:4] padding = [ele for a_list in padding for ele in a_list] elif is_list_or_tuple(padding[0]) and (data_format == "NHWC"): if not (padding[0] == [0, 0] and padding[3] == [0, 0]): raise ValueError( "Non-zero padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[1:3] padding = [ele for a_list in padding for ele in a_list] padding = utils.convert_to_list(padding, 4, 'padding') else: padding = utils.convert_to_list(padding, 2, 'padding') padding = [padding[0], padding[0], padding[1], padding[1]] return padding padding_algorithm = "EXPLICIT" if isinstance(padding, str): padding = padding.upper() if padding not in ["SAME", "VALID"]: raise ValueError( "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'." % str(padding)) if padding == "VALID": padding_algorithm = "VALID" padding = [0, 0, 0, 0] elif padding == "SAME": padding_algorithm = "SAME" padding = [0, 0, 0, 0] padding = _update_padding(padding, data_format) if filter_size is None: if output_size is None: raise ValueError("output_size must be set when filter_size is None") if isinstance(output_size, int): output_size = [output_size, output_size] h_in = input.shape[2] if data_format == 'NCHW' else input.shape[1] w_in = input.shape[3] if data_format == 'NCHW' else input.shape[2] filter_size_h = (output_size[0] - (h_in - 1) * stride[0] + padding[0] + padding[1] - 1) // dilation[0] + 1 filter_size_w = (output_size[1] - (w_in - 1) * stride[1] + padding[2] + padding[3] - 1) // dilation[1] + 1 filter_size = [filter_size_h, filter_size_w] else: filter_size = utils.convert_to_list(filter_size, 2, 'conv2d_transpose.filter_size') if len(padding) == 4 and utils._is_symmetric_padding(padding, 2): padding = [padding[0], padding[2]] if output_size is None: output_size = [] elif isinstance(output_size, (list, tuple, int)): output_size = utils.convert_to_list(output_size, 2, 'output_size') else: raise ValueError("output_size should be int, list[int] or tuple[int]") if groups is None: groups = 1 elif groups <= 0: raise ValueError("the groups of input must be greater than 0, " "but received the groups of input is {}".format( groups)) filter_shape = [input_channel, num_filters // groups] + filter_size img_filter = helper.create_parameter( dtype=input.dtype, shape=filter_shape, attr=helper.param_attr) pre_bias = helper.create_variable_for_type_inference(dtype=input.dtype) helper.append_op( type=op_type, inputs={'Input': [input], 'Filter': [img_filter]}, outputs={'Output': pre_bias}, attrs={ 'output_size': output_size, 'strides': stride, 'paddings': padding, 'padding_algorithm': padding_algorithm, 'dilations': dilation, 'groups': groups, 'use_cudnn': use_cudnn, 'data_format': data_format }) if data_format == 'NCHW': pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2) else: pre_act = helper.append_bias_op(pre_bias, dim_start=3, dim_end=4) out = helper.append_activation(pre_act) return out def conv3d_transpose(input, num_filters, output_size=None, filter_size=None, padding=0, stride=1, dilation=1, groups=None, param_attr=None, bias_attr=None, use_cudnn=True, act=None, name=None, data_format='NCDHW'): r""" :api_attr: Static Graph The convolution3D transpose layer calculates the output based on the input, filter, and dilations, strides, paddings. Input(Input) and output(Output) are in NCDHW or NDHWC format. Where N is batch size, C is the number of channels, D is the depth of the feature, H is the height of the feature, and W is the width of the feature. Parameters(dilations, strides, paddings) are two elements. These two elements represent height and width, respectively. The details of convolution transpose layer, please refer to the following explanation and references `therein <https://arxiv.org/pdf/1603.07285.pdf>`_. If bias attribution and activation type are provided, bias is added to the output of the convolution, and the corresponding activation function is applied to the final result. For each input :math:`X`, the equation is: .. math:: Out = \sigma (W \ast X + b) In the above equation: * :math:`X`: Input value, a Tensor with NCDHW or NDHWC format. * :math:`W`: Filter value, a Tensor with MCDHW format. * :math:`\ast`: Convolution operation. * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1]. * :math:`\sigma`: Activation function. * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. Example: - Input: Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` Filter shape: :math:`(C_{in}, C_{out}, D_f, H_f, W_f)` - Output: Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` Where .. math:: D^\prime_{out} &= (D_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (D_f - 1) + 1 \\\\ H^\prime_{out} &= (H_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (H_f - 1) + 1 \\\\ W^\prime_{out} &= (W_{in} - 1) * strides[2] - 2 * paddings[2] + dilations[2] * (W_f - 1) + 1 \\\\ D_{out} &\in [ D^\prime_{out}, D^\prime_{out} + strides[0] ] \\\\ H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[1] ] \\\\ W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[2] ] Note: The conv3d_transpose can be seen as the backward of the conv3d. For conv3d, when stride > 1, conv3d maps multiple input shape to the same output shape, so for conv3d_transpose, when stride > 1, input shape maps multiple output shape. If output_size is None, :math:`H_{out} = H^\prime_{out}, :math:`H_{out} = \ H^\prime_{out}, W_{out} = W^\prime_{out}`; else, the :math:`D_{out}` of the output size must between :math:`D^\prime_{out}` and :math:`D^\prime_{out} + strides[0]`, the :math:`H_{out}` of the output size must between :math:`H^\prime_{out}` and :math:`H^\prime_{out} + strides[1]`, and the :math:`W_{out}` of the output size must between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[2]`, conv3d_transpose can compute the kernel size automatically. Args: input(Tensor): The input is 5-D Tensor with shape [N, C, D, H, W] or [N, D, H, W, C], the data type of input is float32 or float64. num_filters(int): The number of the filter. It is as same as the output image channel. output_size(int|tuple, optional): The output image size. If output size is a tuple, it must contain three integers, (image_depth, image_height, image_width). This parameter only works when filter_size is None. If output_size and filter_size are specified at the same time, They should follow the formula above. Default: None. Output_size and filter_size should not be None at the same time. filter_size(int|tuple, optional): The filter size. If filter_size is a tuple, it must contain three integers, (filter_size_depth, filter_size_height, filter_size_width). Otherwise, filter_size_depth = filter_size_height = \ filter_size_width = filter_size. None if use output size to calculate filter_size. Default: None. filter_size and output_size should not be None at the same time. padding(int|list|str|tuple, optional): The padding size. The padding argument effectively adds `dilation * (kernel - 1)` amount of zero-padding on both sides of input. If `padding` is a string, either 'VALID' or 'SAME' supported, which is the padding algorithm. If `padding` is a tuple or list, it could be in three forms: `[pad_depth, pad_height, pad_width]` or `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when `data_format` is `'NCDHW'`, `padding` can be in the form `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. when `data_format` is `'NDHWC'`, `padding` can be in the form `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. Default: padding = 0. stride(int|tuple, optional): The stride size. It means the stride in transposed convolution. If stride is a tuple, it must contain three integers, (stride_depth, stride_height, stride_width). Otherwise, stride_depth = stride_height = stride_width = stride. Default: stride = 1. dilation(int|tuple, optional): The dilation size. It means the spacing between the kernel points. If dilation is a tuple, it must contain three integers, (dilation_depth, dilation_height, dilation_width). Otherwise, dilation_depth = dilation_height = dilation_width = dilation. Default: dilation = 1. groups(int, optional): The groups number of the Conv3d transpose layer. Inspired by grouped convolution in Alex Krizhevsky's Deep CNN paper, in which when group=2, the first half of the filters is only connected to the first half of the input channels, while the second half of the filters is only connected to the second half of the input channels. Default: groups=1 param_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights of conv3d_transpose. If it is set to None or one attribute of ParamAttr, conv3d_transpose will create ParamAttr as param_attr. If the Initializer of the param_attr is not set, the parameter is initialized with Xavier. Default: None. bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv3d_transpose. If it is set to False, no bias will be added to the output units. If it is set to None or one attribute of ParamAttr, conv3d_transpose will create ParamAttr as bias_attr. If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn library is installed. Default: True act (str, optional): Activation type, if it is set to None, activation is not appended. Default: None. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. Returns: A Variable holding Tensor representing the conv3d_transpose, whose data type is the same with input and shape is (num_batches, channels, out_d, out_h, out_w) or (num_batches, out_d, out_h, out_w, channels). If act is None, the tensor variable storing the transposed convolution result, and if act is not None, the tensor variable storing transposed convolution and non-linearity activation result. Raises: ValueError: If the type of `use_cudnn` is not bool. ValueError: If `data_format` is not "NCDHW" or "NDHWC". ValueError: If `padding` is a string, but not "SAME" or "VALID". ValueError: If `padding` is a tuple, but the element corresponding to the input's batch size is not 0 or the element corresponding to the input's channel is not 0. ValueError: If `output_size` and filter_size are None at the same time. ShapeError: If the input is not 5-D Tensor. ShapeError: If the input's dimension size and filter's dimension size not equal. ShapeError: If the dimension size of input minus the size of `stride` is not 2. ShapeError: If the number of input channels is not equal to filter's channels. ShapeError: If the size of `output_size` is not equal to that of `stride`. Examples: .. code-block:: python import paddle import numpy as np paddle.enable_static() data = paddle.static.data(name='data', shape=[None, 3, 12, 32, 32], dtype='float32') param_attr = paddle.framework.ParamAttr(name='conv3d.weight', initializer=paddle.nn.initializer.XavierNormal(), learning_rate=0.001) res = paddle.static.nn.conv3d_transpose(input=data, num_filters=2, filter_size=3, act="relu", param_attr=param_attr) place = paddle.CPUPlace() exe = paddle.static.Executor(place) exe.run(paddle.static.default_startup_program()) x = np.random.rand(1, 3, 12, 32, 32).astype("float32") output = exe.run(feed={"data": x}, fetch_list=[res]) print(output) """ assert param_attr is not False, "param_attr should not be False in conv3d_transpose." if data_format not in ['NCDHW', 'NDHWC']: raise ValueError( "Param(data_format) of Op(fluid.layers.conv3d_transpose) got wrong value: received " + data_format + " but only NCDHW or NDHWC supported.") l_type = "conv3d_transpose" helper = LayerHelper(l_type, **locals()) if not isinstance(input, Variable): raise TypeError("Input of conv3d_transpose must be Variable") if len(input.shape) != 5: raise ValueError( "Input should be 5D tensor, but received input with the shape of {}". format(input.shape)) input_channel = input.shape[1] if data_format == 'NCDHW' else input.shape[ -1] stride = utils.convert_to_list(stride, 3, 'stride') dilation = utils.convert_to_list(dilation, 3, 'dilation') if not isinstance(use_cudnn, bool): raise ValueError("use_cudnn should be True or False") def _update_padding(padding, data_format): def is_list_or_tuple(ele): if isinstance(ele, list) or isinstance(ele, tuple): return True return False if is_list_or_tuple(padding) and len(padding) == 5: if is_list_or_tuple(padding[0]) and (data_format == "NCDHW"): if not (padding[0] == [0, 0] and padding[1] == [0, 0]): raise ValueError( "Non-zero padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[2:5] padding = [ele for a_list in padding for ele in a_list] elif is_list_or_tuple(padding[0]) and (data_format == "NDHWC"): if not (padding[0] == [0, 0] and padding[4] == [0, 0]): raise ValueError( "Non-zero padding(%s) in the batch or channel dimensions " "is not supported." % str(padding)) padding = padding[1:4] padding = [ele for a_list in padding for ele in a_list] padding = utils.convert_to_list(padding, 6, 'padding') elif is_list_or_tuple(padding) and len(padding) == 6: padding = utils.convert_to_list(padding, 6, 'padding') else: padding = utils.convert_to_list(padding, 3, 'padding') padding = [ padding[0], padding[0], padding[1], padding[1], padding[2], padding[2] ] return padding padding_algorithm = "EXPLICIT" if isinstance(padding, str): padding = padding.upper() if padding not in ["SAME", "VALID"]: raise ValueError( "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'." % str(padding)) if padding == "VALID": padding_algorithm = "VALID" padding = [0, 0, 0, 0, 0, 0] elif padding == "SAME": padding_algorithm = "SAME" padding = [0, 0, 0, 0, 0, 0] padding = _update_padding(padding, data_format) if filter_size is None: if output_size is None: raise ValueError("output_size must be set when filter_size is None") if isinstance(output_size, int): output_size = [output_size, output_size, output_size] d_in = input.shape[2] if data_format == 'NCDHW' else input.shape[1] h_in = input.shape[3] if data_format == 'NCDHW' else input.shape[2] w_in = input.shape[4] if data_format == 'NCDHW' else input.shape[3] filter_size_d = (output_size[0] - (d_in - 1) * stride[0] + padding[0] + padding[1] - 1) // dilation[0] + 1 filter_size_h = (output_size[1] - (h_in - 1) * stride[1] + padding[2] + padding[3] - 1) // dilation[1] + 1 filter_size_w = (output_size[2] - (w_in - 1) * stride[2] + padding[4] + padding[5] - 1) // dilation[2] + 1 filter_size = [filter_size_d, filter_size_h, filter_size_w] else: filter_size = utils.convert_to_list(filter_size, 3, 'conv3d_transpose.filter_size') if len(padding) == 6 and utils._is_symmetric_padding(padding, 3): padding = [padding[0], padding[2], padding[4]] if output_size is None: output_size = [] elif isinstance(output_size, (list, tuple, int)): output_size = utils.convert_to_list(output_size, 3, 'output_size') else: raise ValueError("output_size should be int, list[int] or tuple[int]") groups = 1 if groups is None else groups if groups <= 0: raise ValueError( "the groups of conv3d_transpose should be greater than 0. Received groups: {}". format(groups)) if num_filters % groups != 0: raise ValueError("Attr(num_filters) must be divisible by groups," "Received: Attr(num_filters) is {}, the groups is {}". format(num_filters, groups)) filter_shape = [input_channel, num_filters // groups] + filter_size img_filter = helper.create_parameter( dtype=input.dtype, shape=filter_shape, attr=helper.param_attr) if data_format == 'NCDHW': data_format = 'NCHW' if data_format == 'NDHWC': data_format = 'NHWC' pre_bias = helper.create_variable_for_type_inference(dtype=input.dtype) helper.append_op( type=l_type, inputs={'Input': [input], 'Filter': [img_filter]}, outputs={'Output': pre_bias}, attrs={ 'output_size': output_size, 'strides': stride, 'paddings': padding, 'padding_algorithm': padding_algorithm, 'dilations': dilation, 'groups': groups, 'use_cudnn': use_cudnn, 'data_format': data_format }) if data_format == 'NCHW': pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2) else: pre_act = helper.append_bias_op(pre_bias, dim_start=4, dim_end=5) out = helper.append_activation(pre_act) return out def reduce_sum(input, dim=None, keep_dim=False, name=None): """ Computes the sum of tensor elements over the given dimension. Args: input (Variable): The input variable which is a Tensor, the data type is float32, float64, int32, int64. dim (list|int, optional): The dimensions along which the sum is performed. If :attr:`None`, sum all elements of :attr:`input` and return a Tensor variable with a single element, otherwise must be in the range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`. keep_dim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the :attr:`input` unless :attr:`keep_dim` is true, default value is False. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Variable: Tensor, results of summation operation on the specified dim of input tensor, it's data type is the same as input's Tensor. Raises: TypeError, if out data type is different with the input data type. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() # x is a Tensor variable with following elements: # [[0.2, 0.3, 0.5, 0.9] # [0.1, 0.2, 0.6, 0.7]] # Each example is followed by the corresponding output tensor. x = fluid.data(name='x', shape=[2, 4], dtype='float32') fluid.layers.reduce_sum(x) # [3.5] fluid.layers.reduce_sum(x, dim=0) # [0.3, 0.5, 1.1, 1.6] fluid.layers.reduce_sum(x, dim=-1) # [1.9, 1.6] fluid.layers.reduce_sum(x, dim=1, keep_dim=True) # [[1.9], [1.6]] # y is a Tensor variable with shape [2, 2, 2] and elements as below: # [[[1, 2], [3, 4]], # [[5, 6], [7, 8]]] # Each example is followed by the corresponding output tensor. y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') fluid.layers.reduce_sum(y, dim=[1, 2]) # [10, 26] fluid.layers.reduce_sum(y, dim=[0, 1]) # [16, 20] """ if dim is not None and not isinstance(dim, list): dim = [dim] if in_dygraph_mode(): reduce_all = True if dim == None or dim == [] or len(dim) == len( input.shape) else False dim = dim if dim != None and dim != [] else [0] return _C_ops.reduce_sum(input, 'dim', dim, 'keep_dim', keep_dim, 'reduce_all', reduce_all) attrs = { 'dim': dim if dim != None and dim != [] else [0], 'keep_dim': keep_dim, 'reduce_all': True if dim == None or dim == [] or len(dim) == len(input.shape) else False } check_variable_and_dtype( input, 'input', ['float16', 'float32', 'float64', 'int32', 'int64'], 'reduce_sum') helper = LayerHelper('reduce_sum', **locals()) out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) helper.append_op( type='reduce_sum', inputs={'X': input}, outputs={'Out': out}, attrs=attrs) return out @deprecated(since="2.0.0", update_to="paddle.mean") def reduce_mean(input, dim=None, keep_dim=False, name=None): """ Computes the mean of the input tensor's elements along the given dimension. Args: input (Variable): The input variable which is a Tensor, the data type is float32, float64, int32, int64. dim (list|int, optional): The dimension along which the mean is computed. If `None`, compute the mean over all elements of :attr:`input` and return a variable with a single element, otherwise it must be in the range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank(input) + dim[i]`. keep_dim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the :attr:`input` unless :attr:`keep_dim` is true, default value is False. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Variable: Tensor, results of average on the specified dim of input tensor, it's data type is the same as input's Tensor. Raises: TypeError, if out data type is different with the input data type. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() # x is a Tensor variable with following elements: # [[0.2, 0.3, 0.5, 0.9] # [0.1, 0.2, 0.6, 0.7]] # Each example is followed by the corresponding output tensor. x = fluid.data(name='x', shape=[2, 4], dtype='float32') fluid.layers.reduce_mean(x) # [0.4375] fluid.layers.reduce_mean(x, dim=0) # [0.15, 0.25, 0.55, 0.8] fluid.layers.reduce_mean(x, dim=-1) # [0.475, 0.4] fluid.layers.reduce_mean(x, dim=1, keep_dim=True) # [[0.475], [0.4]] # y is a Tensor variable with shape [2, 2, 2] and elements as below: # [[[1.0, 2.0], [3.0, 4.0]], # [[5.0, 6.0], [7.0, 8.0]]] # Each example is followed by the corresponding output tensor. y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') fluid.layers.reduce_mean(y, dim=[1, 2]) # [2.5, 6.5] fluid.layers.reduce_mean(y, dim=[0, 1]) # [4.0, 5.0] """ return paddle.mean(x=input, axis=dim, keepdim=keep_dim, name=name) def reduce_max(input, dim=None, keep_dim=False, name=None): """ Computes the maximum of tensor elements over the given dimension. Args: input (Variable): The input variable which is a Tensor, the data type is float32, float64, int32, int64. dim (list|int, optional): The dimension along which the maximum is computed. If :attr:`None`, compute the maximum over all elements of :attr:`input` and return a Tensor variable with a single element, otherwise must be in the range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`. keep_dim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the :attr:`input` unless :attr:`keep_dim` is true, default value is False. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Variable: Tensor, results of maximum on the specified dim of input tensor, it's data type is the same as input's Tensor. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() # x is a Tensor variable with following elements: # [[0.2, 0.3, 0.5, 0.9] # [0.1, 0.2, 0.6, 0.7]] # Each example is followed by the corresponding output tensor. x = fluid.data(name='x', shape=[2, 4], dtype='float32') fluid.layers.reduce_max(x) # [0.9] fluid.layers.reduce_max(x, dim=0) # [0.2, 0.3, 0.6, 0.9] fluid.layers.reduce_max(x, dim=-1) # [0.9, 0.7] fluid.layers.reduce_max(x, dim=1, keep_dim=True) # [[0.9], [0.7]] # y is a Tensor variable with shape [2, 2, 2] and elements as below: # [[[1.0, 2.0], [3.0, 4.0]], # [[5.0, 6.0], [7.0, 8.0]]] # Each example is followed by the corresponding output tensor. y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') fluid.layers.reduce_max(y, dim=[1, 2]) # [4.0, 8.0] fluid.layers.reduce_max(y, dim=[0, 1]) # [7.0, 8.0] """ helper = LayerHelper('reduce_max', **locals()) out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) if dim is not None and not isinstance(dim, list): dim = [dim] helper.append_op( type='reduce_max', inputs={'X': input}, outputs={'Out': out}, attrs={ 'dim': dim if dim != None and dim != [] else [0], 'keep_dim': keep_dim, 'reduce_all': True if dim == None or dim == [] or len(dim) == len(input.shape) else False }) return out def reduce_min(input, dim=None, keep_dim=False, name=None): """ Computes the minimum of tensor elements over the given dimension. Args: input (Variable): The input variable which is a Tensor, the data type is float32, float64, int32, int64. dim (list|int, optional): The dimensions along which the minimum is computed. If :attr:`None`, compute the minimum over all elements of :attr:`input` and return a Tensor variable with a single element, otherwise must be in the range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`. keep_dim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the :attr:`input` unless :attr:`keep_dim` is true, default value is False. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Variable: Tensor, result of minimum on the specified dim of input tensor, it's data type is the same as input's Tensor. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() # x is a Tensor variable with following elements: # [[0.2, 0.3, 0.5, 0.9] # [0.1, 0.2, 0.6, 0.7]] # Each example is followed by the corresponding output tensor. x = fluid.data(name='x', shape=[2, 4], dtype='float32') fluid.layers.reduce_min(x) # [0.1] fluid.layers.reduce_min(x, dim=0) # [0.1, 0.2, 0.5, 0.7] fluid.layers.reduce_min(x, dim=-1) # [0.2, 0.1] fluid.layers.reduce_min(x, dim=1, keep_dim=True) # [[0.2], [0.1]] # y is a Tensor variable with shape [2, 2, 2] and elements as below: # [[[1.0, 2.0], [3.0, 4.0]], # [[5.0, 6.0], [7.0, 8.0]]] # Each example is followed by the corresponding output tensor. y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') fluid.layers.reduce_min(y, dim=[1, 2]) # [1.0, 5.0] fluid.layers.reduce_min(y, dim=[0, 1]) # [1.0, 2.0] """ helper = LayerHelper('reduce_min', **locals()) out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) if dim is not None and not isinstance(dim, list): dim = [dim] helper.append_op( type='reduce_min', inputs={'X': input}, outputs={'Out': out}, attrs={ 'dim': dim if dim != None and dim != [] else [0], 'keep_dim': keep_dim, 'reduce_all': True if dim == None or dim == [] or len(dim) == len(input.shape) else False }) return out def reduce_prod(input, dim=None, keep_dim=False, name=None): """ Computes the product of tensor elements over the given dimension. Args: input (Variable): The input variable which is a Tensor, the data type is float32, float64, int32, int64. dim (int|list|tuple, optional): The dimensions along which the product is performed. If :attr:`None`, multiply all elements of :attr:`input` and return a Tensor variable with a single element, otherwise must be in the range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`. keep_dim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the :attr:`input` unless :attr:`keep_dim` is true, default value is False. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Variable: Tensor, result of product on the specified dim of input tensor, it's data type is the same as input's Tensor. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() # x is a Tensor variable with following elements: # [[0.2, 0.3, 0.5, 0.9] # [0.1, 0.2, 0.6, 0.7]] # Each example is followed by the corresponding output tensor. x = fluid.data(name='x', shape=[2, 4], dtype='float32') fluid.layers.reduce_prod(x) # [0.0002268] fluid.layers.reduce_prod(x, dim=0) # [0.02, 0.06, 0.3, 0.63] fluid.layers.reduce_prod(x, dim=-1) # [0.027, 0.0084] fluid.layers.reduce_prod(x, dim=1, keep_dim=True) # [[0.027], [0.0084]] # y is a Tensor variable with shape [2, 2, 2] and elements as below: # [[[1.0, 2.0], [3.0, 4.0]], # [[5.0, 6.0], [7.0, 8.0]]] # Each example is followed by the corresponding output tensor. y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') fluid.layers.reduce_prod(y, dim=[1, 2]) # [24.0, 1680.0] fluid.layers.reduce_prod(y, dim=[0, 1]) # [105.0, 384.0] """ helper = LayerHelper('reduce_prod', **locals()) if dim is not None and not isinstance(dim, list): if isinstance(dim, tuple): dim = list(dim) elif isinstance(dim, int): dim = [dim] else: raise TypeError( "The type of axis must be int, list or tuple, but received {}". format(type(dim))) check_variable_and_dtype( input, 'input', ['float32', 'float64', 'int32', 'int64'], 'reduce_prod') out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) helper.append_op( type='reduce_prod', inputs={'X': input}, outputs={'Out': out}, attrs={ 'dim': dim if dim != None and dim != [] else [0], 'keep_dim': keep_dim, 'reduce_all': True if dim == None or dim == [] or len(dim) == len(input.shape) else False }) return out def reduce_all(input, dim=None, keep_dim=False, name=None): """ This OP computes the ``logical and`` of tensor elements over the given dimension, and output the result. Args: input (Tensor): the input tensor, it's data type should be `bool`. dim (list|int|optional): The dimension along which the logical and is computed. If :attr:`None`, compute the logical and over all elements of :attr:`input` and return a Tensor variable with a single element, otherwise must be in the range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`. The default value is None. keep_dim (bool): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the :attr:`input` unless :attr:`keep_dim` is true. The default value is False. name(str|None): A name for this layer(optional). If set None, the layer will be named automatically. The default value is None. Returns: Tensor, the output data type is bool. : The reduced tensor variable with ``logical and`` in given dims. Examples: .. code-block:: python import paddle import paddle.fluid as fluid import paddle.fluid.layers as layers import numpy as np # x is a bool Tensor variable with following elements: # [[True, False] # [True, True]] x = fluid.layers.assign(np.array([[1, 0], [1, 1]], dtype='int32')) x = fluid.layers.cast(x, 'bool') out = fluid.layers.reduce_all(x) # False out = fluid.layers.reduce_all(x, dim=0) # [True, False] out = fluid.layers.reduce_all(x, dim=-1) # [False, True] # keep_dim=False, x.shape=(2,2), out.shape=(2,) out = fluid.layers.reduce_all(x, dim=1, keep_dim=True) # [[False], [True]] # keep_dim=True, x.shape=(2,2), out.shape=(2,1) """ check_variable_and_dtype(input, 'input', ('bool'), 'reduce_all') helper = LayerHelper('reduce_all', **locals()) out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) if dim is not None and not isinstance(dim, list): dim = [dim] helper.append_op( type='reduce_all', inputs={'X': input}, outputs={'Out': out}, attrs={ 'dim': dim if dim != None and dim != [] else [0], 'keep_dim': keep_dim, 'reduce_all': True if dim == None or dim == [] or len(dim) == len(input.shape) else False }) return out def reduce_any(input, dim=None, keep_dim=False, name=None): """ This OP computes the ``logical or`` of tensor elements over the given dimension, and output the result. Args: input (Tensor): the input tensor, it's data type should be `bool`. dim (list|int|optional): The dimension along which the logical and is computed. If :attr:`None`, compute the logical and over all elements of :attr:`input` and return a Tensor variable with a single element, otherwise must be in the range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`. The default value is None. keep_dim (bool): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the :attr:`input` unless :attr:`keep_dim` is true. The default value is False. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor, the output data type is bool. : The reduced tensor variable with ``logical or`` in given dims. Examples: .. code-block:: python import paddle import paddle.fluid as fluid import paddle.fluid.layers as layers import numpy as np # x is a bool Tensor variable with following elements: # [[True, False] # [False, False]] x = fluid.layers.assign(np.array([[1, 0], [0, 0]], dtype='int32')) x = fluid.layers.cast(x, 'bool') out = fluid.layers.reduce_any(x) # True out = fluid.layers.reduce_any(x, dim=0) # [True, False] out = fluid.layers.reduce_any(x, dim=-1) # [True, False] # keep_dim=False, x.shape=(2,2), out.shape=(2,) out = fluid.layers.reduce_any(x, dim=1, keep_dim=True) # [[True], [False]] # keep_dim=True, x.shape=(2,2), out.shape=(2,1) """ check_variable_and_dtype(input, 'input', ('bool'), 'reduce_any') helper = LayerHelper('reduce_any', **locals()) out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) if dim is not None and not isinstance(dim, list): dim = [dim] helper.append_op( type='reduce_any', inputs={'X': input}, outputs={'Out': out}, attrs={ 'dim': dim if dim != None and dim != [] else [0], 'keep_dim': keep_dim, 'reduce_all': True if dim == None or dim == [] or len(dim) == len(input.shape) else False }) return out def split(input, num_or_sections, dim=-1, name=None): """ Split the input tensor into multiple sub-Tensors. Args: input (Tensor): A N-D Tensor. The data type is bool, float16, float32, float64, int32 or int64. num_or_sections (int|list|tuple): If ``num_or_sections`` is int, then the ``num_or_sections`` indicates the number of equal sized sub-Tensors that the ``input`` will be divided into. If ``num_or_sections`` is a list or tuple, the length of it indicates the number of sub-Tensors and the elements in it indicate the sizes of sub-Tensors' dimension orderly. The length of the list mustn't be larger than the ``input`` 's size of specified dim. dim (int|Tensor, optional): The dimension along which to split, it can be a scalar with type ``int`` or a ``Tensor`` with shape [1] and data type ``int32`` or ``int64``. If :math:`dim < 0`, the dimension to split along is :math:`rank(input) + dim`. Default is -1. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: list(Tensor): The list of segmented Tensors. Example: .. code-block:: python import paddle.fluid as fluid # input is a Tensor which shape is [3, 9, 5] input = fluid.data( name="input", shape=[3, 9, 5], dtype="float32") out0, out1, out2 = fluid.layers.split(input, num_or_sections=3, dim=1) # out0.shape [3, 3, 5] # out1.shape [3, 3, 5] # out2.shape [3, 3, 5] out0, out1, out2 = fluid.layers.split(input, num_or_sections=[2, 3, 4], dim=1) # out0.shape [3, 2, 5] # out1.shape [3, 3, 5] # out2.shape [3, 4, 5] out0, out1, out2 = fluid.layers.split(input, num_or_sections=[2, 3, -1], dim=1) # out0.shape [3, 2, 5] # out1.shape [3, 3, 5] # out2.shape [3, 4, 5] # dim is negative, the real dim is (rank(input) + axis) which real # value is 1. out0, out1, out2 = fluid.layers.split(input, num_or_sections=3, dim=-2) # out0.shape [3, 3, 5] # out1.shape [3, 3, 5] # out2.shape [3, 3, 5] """ if in_dygraph_mode(): num = None attrs = () if isinstance(dim, Variable): dim = dim.numpy() dim = dim.item(0) assert len(input.shape) + dim >= 0, "(rank(x) + axis) must >= 0" dim = (len(input.shape) + dim) if dim < 0 else dim attrs += ('axis', dim) if isinstance(num_or_sections, int): num = num_or_sections attrs += ('num', num_or_sections) elif isinstance(num_or_sections, (list, tuple)): num = len(num_or_sections) if utils._contain_var(num_or_sections): for index, item in enumerate(num_or_sections): if isinstance(item, Variable): num_or_sections[index] = num_or_sections[index].numpy()[ 0] attrs += ('sections', list(num_or_sections)) else: attrs += ('sections', list(num_or_sections)) else: raise TypeError( "The type of 'num_or_sections' in split must be int, list or tuple in imperative mode, but " "received %s." % (type(num_or_sections))) return _C_ops.split(input, num, *attrs) check_variable_and_dtype( input, 'input', ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], 'split') check_type(num_or_sections, 'num_or_sections', (list, int, tuple), 'split') check_type(dim, 'dim', (int, Variable), 'split') if isinstance(dim, Variable): check_dtype(dim.dtype, 'dim', ['int32', 'int64'], 'split') helper = LayerHelper('split', **locals()) input_shape = input.shape inputs = {'X': input} attrs = {'num': num_or_sections if isinstance(num_or_sections, int) else 0} def _get_SectionsTensorList(one_list): tensor_list = [] unk_dim_idx = -1 for idx, dim_size in enumerate(one_list): if isinstance(dim_size, Variable): dim_size.stop_gradient = True tensor_list.append(dim_size) else: assert (isinstance(dim_size, int)) if dim_size == -1: assert unk_dim_idx == -1, ( "Only one value of 'num_or_section' in split can " "be -1. But received num_or_section[%d] is also -1." % idx) unk_dim_idx = idx temp_out = helper.create_variable_for_type_inference('int32') fill_constant( [1], 'int32', dim_size, force_cpu=True, out=temp_out) tensor_list.append(temp_out) return tensor_list if isinstance(dim, Variable): dim.stop_gradient = True inputs['AxisTensor'] = dim else: assert len(input.shape) + dim >= 0, "(rank(x) + axis) must >= 0" dim = (len(input_shape) + dim) if dim < 0 else dim attrs['axis'] = dim if isinstance(num_or_sections, int): assert num_or_sections > 1, 'num_or_sections must be more than 1.' if isinstance(dim, int) and input_shape[dim] > 0: assert input_shape[dim] % num_or_sections ==0, \ "The input's size along the split dimension " \ "must be evenly divisible by Attr(num_or_sections). " \ "But %d is not evenly divisible by %d. " % (num_or_sections,input_shape[dim]) num = num_or_sections else: if isinstance(dim, int) and input_shape[dim] > 0: assert len(num_or_sections) <= input_shape[ dim], 'len(num_or_sections) must not be more than input.shape[dim].' num = len(num_or_sections) attrs['sections'] = list( map(lambda ele: -1 if isinstance(ele, Variable) else ele, num_or_sections)) if utils._contain_var(num_or_sections): inputs['SectionsTensorList'] = _get_SectionsTensorList( num_or_sections) outs = [ helper.create_variable_for_type_inference(dtype=helper.input_dtype()) for i in range(num) ] helper.append_op( type='split', inputs=inputs, outputs={'Out': outs}, attrs=attrs) return outs def l2_normalize(x, axis, epsilon=1e-12, name=None): r""" This op normalizes `x` along dimension `axis` using an L2 norm. For a 1-D tensor (`dim` is fixed to 0), this layer computes .. math:: y = \\frac{x}{ \sqrt{\sum {x^2} + epsion }} For `x` with more dimensions, this layer independently normalizes each 1-D slice along dimension `axis`. Args: x(Variable|list): The input tensor could be N-D tensor, and the input data type could be float16, float32 or float64. axis(int): The axis on which to apply normalization. If `axis < 0`, \ the dimension to normalization is rank(X) + axis. -1 is the last dimension. epsilon(float): The epsilon value is used to avoid division by zero, \ the default value is 1e-12. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Variable: The output has the same shape and data type with `x`. Examples: .. code-block:: python :name: code-example1 import paddle X = paddle.randn(shape=[3, 5], dtype='float64') out = paddle.fluid.layers.l2_normalize(X, axis=-1) print(out) # [[ 0.21558504 0.56360189 0.47466096 0.46269539 -0.44326736] # [-0.70602414 -0.52745777 0.37771788 -0.2804768 -0.04449922] # [-0.33972208 -0.43014923 0.31772556 0.76617881 -0.10761525]] """ if len(x.shape) == 1: axis = 0 if in_dygraph_mode(): _, out = _C_ops.norm(x, 'axis', 1 if axis is None else axis, 'epsilon', epsilon) return out check_variable_and_dtype(x, "X", ("float16", "float32", "float64"), "norm") helper = LayerHelper("l2_normalize", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) norm = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type="norm", inputs={"X": x}, outputs={"Out": out, "Norm": norm}, attrs={ "axis": 1 if axis is None else axis, "epsilon": epsilon, }) return out @deprecated(since="2.0.0", update_to="paddle.matmul") def matmul(x, y, transpose_x=False, transpose_y=False, alpha=1.0, name=None): """ Applies matrix multiplication to two tensors. Currently, the input tensors' rank can be any, but when the rank of any inputs is bigger than 3, this two inputs' rank should be equal. The actual behavior depends on the shapes of :math:`x`, :math:`y` and the flag values of :attr:`transpose_x`, :attr:`transpose_y`. Specifically: - If a transpose flag is specified, the last two dimensions of the tensor are transposed. If the tensor is rank-1 of shape :math:`[D]`, then for :math:`x` it is treated as :math:`[1, D]` in nontransposed form and as :math:`[D, 1]` in transposed form, whereas for :math:`y` it is the opposite: It is treated as :math:`[D, 1]` in nontransposed form and as :math:`[1, D]` in transposed form. - After transpose, the two tensors are 2-D or n-D and matrix multiplication performs in the following way. - If both are 2-D, they are multiplied like conventional matrices. - If either is n-D, it is treated as a stack of matrices residing in the last two dimensions and a batched matrix multiply supporting broadcast applies on the two tensors. Also note that if the raw tensor :math:`x` or :math:`y` is rank-1 and nontransposed, the prepended or appended dimension :math:`1` will be removed after matrix multiplication. Args: x (Variable): The input variable which is a Tensor or LoDTensor. y (Variable): The input variable which is a Tensor or LoDTensor. transpose_x (bool): Whether to transpose :math:`x` before multiplication. transpose_y (bool): Whether to transpose :math:`y` before multiplication. alpha (float): The scale of output. Default 1.0. name(str|None): A name for this layer(optional). If set None, the layer will be named automatically. Returns: Variable: The product Tensor (or LoDTensor) variable. Examples: .. code-block:: python # Examples to clarify shapes of the inputs and output # x: [B, ..., M, K], y: [B, ..., K, N] # fluid.layers.matmul(x, y) # out: [B, ..., M, N] # x: [B, M, K], y: [B, K, N] # fluid.layers.matmul(x, y) # out: [B, M, N] # x: [B, M, K], y: [K, N] # fluid.layers.matmul(x, y) # out: [B, M, N] # x: [M, K], y: [K, N] # fluid.layers.matmul(x, y) # out: [M, N] # x: [B, M, K], y: [K] # fluid.layers.matmul(x, y) # out: [B, M] # x: [K], y: [K] # fluid.layers.matmul(x, y) # out: [1] # x: [M], y: [N] # fluid.layers.matmul(x, y, True, True) # out: [M, N] import paddle import paddle.fluid as fluid paddle.enable_static() x = fluid.layers.data(name='x', shape=[2, 3], dtype='float32') y = fluid.layers.data(name='y', shape=[3, 2], dtype='float32') out = fluid.layers.matmul(x, y, True, True) """ if in_dygraph_mode(): out = _varbase_creator(dtype=x.dtype) _C_ops.matmul(x, y, out, 'transpose_X', transpose_x, 'transpose_Y', transpose_y, 'alpha', float(alpha)) return out def __check_input(x, y): var_names = {'x': x, 'y': y} for name, val in var_names.items(): check_variable_and_dtype( val, name, ['float16', 'float32', 'float64'], 'matmul') x_shape = list(x.shape) y_shape = list(y.shape) if len(x_shape) == 1: x_shape = [1] + x_shape if len(y_shape) == 1: y_shape = y_shape + [1] # check the inner 2 dimensions if transpose_x: x_shape[-2], x_shape[-1] = x_shape[-1], x_shape[-2] if transpose_y: y_shape[-2], y_shape[-1] = y_shape[-1], y_shape[-2] if x_shape[-1] != y_shape[-2]: assert (x_shape[-1] == -1) or (y_shape[-2] == -1), \ "After performing an optional transpose, Input X's width should be " \ "equal to Y's width for multiplication " \ "prerequisites. But received X's shape: %s, Y's shape: %s\n" % \ (x_shape, y_shape) if len(y_shape) > 2 and len(x_shape) > 2: for i, dim_x in enumerate(x_shape[:-2]): # don't check neg shape if dim_x < 0 or y_shape[i] < 0: continue if dim_x != y_shape[i]: raise ValueError( "When the matrix is larger than 2 dimensions, the higher " "dimensional values of the two matrices need to be equal. " "But received x_shape[%d] != y_shape[%d]. X's shape: %s, " "Y's shape: %s.\n" % (i, i, x_shape, y_shape)) attrs = { 'transpose_X': transpose_x, 'transpose_Y': transpose_y, 'alpha': float(alpha), } __check_input(x, y) helper = LayerHelper('matmul', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='matmul', inputs={'X': x, 'Y': y}, outputs={'Out': out}, attrs=attrs) return out def topk(input, k, name=None): """ :alias_main: paddle.topk :alias: paddle.topk,paddle.tensor.topk,paddle.tensor.search.topk :old_api: paddle.fluid.layers.topk This OP is used to find values and indices of the k largest entries for the last dimension. If the input is a 1-D Tensor, finds the k largest entries and outputs their values and indices. If the input is a Tensor with higher rank, this operator computes the top k entries along the last dimension. .. code-block:: text Case 1: Input: input.shape = [3, 4] input.data = [[5, 4, 2, 3], [9, 7, 10, 25], [6, 2, 10, 1]] k = 2 Output: The first output: values.shape = [3, 2] values.data = [[5, 4], [10, 25], [6, 10]] The second output: indices.shape = [3, 2] indices.data = [[0, 1], [2, 3], [0, 2]] Args: input(Variable): The input tensor. Support data types: float32, float64. k(int | Variable): The number of top elements to look for along the last dimension of input tensor. name (str, optional): Please refer to :ref:`api_guide_Name`, Default None. Returns: Values (Variable): Input tensor's k largest elements along each last dimensional slice. The dimension is: :math:`input.shape[:-1]+[k]`. Indices (Variable): Indices of k largest elements alone the last dimension of input. The dimension is same as values. Raises: ValueError: If :math:`k < 1` or :math:`k > last dimension of input`. Examples: .. code-block:: python import paddle.fluid as fluid import paddle.fluid.layers as layers # set batch size=None input = fluid.data(name="input", shape=[None, 13, 11], dtype='float32') top5_values, top5_indices = layers.topk(input, k=5) # top5_values.shape[None, 13, 5], top5_indices.shape=[None, 13, 5] # 1D Tensor input1 = fluid.data(name="input1", shape=[None, 13], dtype='float32') top5_values, top5_indices = layers.topk(input1, k=5) #top5_values.shape=[None, 5], top5_indices.shape=[None, 5] # k=Variable input2 = fluid.data(name="input2", shape=[None, 13, 11], dtype='float32') vk = fluid.data(name="vk", shape=[None, 1], dtype='int32') # save k in vk.data[0] vk_values, vk_indices = layers.topk(input2, k=vk) #vk_values.shape=[None, 13, k], vk_indices.shape=[None, 13, k] """ if in_dygraph_mode(): _k = k.numpy().item(0) if isinstance(k, Variable) else k out, indices = _C_ops.top_k(input, 'k', _k) out.stop_gradient = True indices.stop_gradient = True return out, indices inputs = {"X": [input]} attrs = {} if isinstance(k, Variable): inputs['K'] = [k] else: attrs = {'k': k} helper = LayerHelper("top_k", **locals()) values = helper.create_variable_for_type_inference(dtype=input.dtype) indices = helper.create_variable_for_type_inference(dtype="int64") helper.append_op( type="top_k", inputs=inputs, outputs={"Out": [values], "Indices": [indices]}, attrs=attrs) values.stop_gradient = True indices.stop_gradient = True return values, indices def ctc_greedy_decoder(input, blank, input_length=None, padding_value=0, name=None): r""" This op is used to decode sequences by greedy policy by the following steps: 1. Get the indexes of maximum value for each row in input. a.k.a. numpy.argmax(input, axis=0). 2. For each sequence in result of step1, merge repeated tokens between two blanks and delete all blanks. This op is implemented in two modes: lod and padding, either of them can be used. The input can be either LoDTensor or Tensor, corresponding to lod and padding mode respectively. A simple example as below: .. code-block:: text Given: (1) for lod mode: input.data = [[0.6, 0.1, 0.3, 0.1], [0.3, 0.2, 0.4, 0.1], [0.1, 0.5, 0.1, 0.3], [0.5, 0.1, 0.3, 0.1], [0.5, 0.1, 0.3, 0.1], [0.2, 0.2, 0.2, 0.4], [0.2, 0.2, 0.1, 0.5], [0.5, 0.1, 0.3, 0.1]] input.lod = [[4, 4]] Computation: step1: Apply argmax to first input sequence which is input.data[0:4]. Then we get: [[0], [2], [1], [0]] step2: merge repeated tokens and remove blank which is 0. Then we get first output sequence: [[2], [1]] Finally: output.data = [[2], [1], [3]] output.lod = [[2, 1]] (2) for padding mode: input.data = [[[0.6, 0.1, 0.3, 0.1], [0.3, 0.2, 0.4, 0.1], [0.1, 0.5, 0.1, 0.3], [0.5, 0.1, 0.3, 0.1]], [[0.5, 0.1, 0.3, 0.1], [0.2, 0.2, 0.2, 0.4], [0.2, 0.2, 0.1, 0.5], [0.5, 0.1, 0.3, 0.1]]] input_length.data = [[4], [4]] input.shape = [2, 4, 4] step1: Apply argmax to first input sequence which is input.data[0:4]. Then we get: [[0], [2], [1], [0]], for input.data[4:8] is [[0], [3], [3], [0]], shape is [2,4,1] step2: Change the argmax result to use padding mode, then argmax result is [[0, 2, 1, 0], [0, 3, 3, 0]], shape is [2, 4], lod is [], input_length is [[4], [4]] step3: Apply ctc_align to padding argmax result, padding_value is 0 Finally: output.data = [[2, 1, 0, 0], [3, 0, 0, 0]] output_length.data = [[2], [1]] Parameters: input(Variable): the probabilities of variable-length sequences. When in lod mode, it is a 2-D LoDTensor with LoD information. It's shape is [Lp, num_classes + 1] where Lp is the sum of all input sequences' length and num_classes is the true number of classes. When in padding mode, it is a 3-D Tensor with padding, It's shape is [batch_size, N, num_classes + 1]. (not including the blank label). The data type can be float32 or float64. blank(int): the blank label index of Connectionist Temporal Classification (CTC) loss, which is in the half-opened interval [0, num_classes + 1). input_length(Variable, optional): 2-D LoDTensor, shape is [batch_size, 1], data type is int64. It is used for padding mode. In lod mode, input_length is None. padding_value(int): padding value. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: For lod mode, returns the result of CTC greedy decoder, 2-D LoDTensor, shape is [Lp, 1], \ data type is int64. 'Lp' is the sum of all output sequences' length. If all the sequences \ in result were empty, the result LoDTensor will be [-1] with empty \ LoD [[]]. For padding mode, returns a tuple of (output, output_length), which was described as below: output, 2-D Tensor, shape is [batch_size, N], data type is int64. output_length, 2-D Tensor, shape is [batch_size, 1], data type is int64. It is the length of \ each sequence of output for padding mode. Return type: For lod mode: Variable For padding mode: tuple of two Variables (output, output_length). Examples: .. code-block:: python # for lod mode import paddle.fluid as fluid x = fluid.data(name='x', shape=[None, 8], dtype='float32', lod_level=1) cost = fluid.layers.ctc_greedy_decoder(input=x, blank=0) # for padding mode x_pad = fluid.data(name='x_pad', shape=[10, 4, 8], dtype='float32') x_pad_len = fluid.data(name='x_pad_len', shape=[10, 1], dtype='int64') out, out_len = fluid.layers.ctc_greedy_decoder(input=x_pad, blank=0, input_length=x_pad_len) """ check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'ctc_greedy_decoder') helper = LayerHelper("ctc_greedy_decoder", **locals()) _, topk_indices = topk(input, k=1) # ctc align op ctc_out = helper.create_variable_for_type_inference(dtype="int64") if input_length is None: helper.append_op( type="ctc_align", inputs={"Input": [topk_indices]}, outputs={"Output": [ctc_out]}, attrs={"merge_repeated": True, "blank": blank}) return ctc_out else: ctc_out_len = helper.create_variable_for_type_inference(dtype="int64") ctc_input = squeeze(topk_indices, [2]) helper.append_op( type="ctc_align", inputs={"Input": [ctc_input], "InputLength": [input_length]}, outputs={"Output": [ctc_out], "OutputLength": [ctc_out_len]}, attrs={ "merge_repeated": True, "blank": blank, "padding_value": padding_value }) return ctc_out, ctc_out_len def transpose(x, perm, name=None): """ Permute the data dimensions of `input` according to `perm`. The `i`-th dimension of the returned tensor will correspond to the perm[i]-th dimension of `input`. Args: x (Tensor): The input Tensor. It is a N-D Tensor of data types bool, float32, float64, int32. perm (list|tuple): Permute the input according to the data of perm. name (str): The name of this layer. It is optional. Returns: Tensor: A transposed n-D Tensor, with data type being bool, float32, float64, int32, int64. For Example: .. code-block:: text x = [[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] [[13 14 15 16] [17 18 19 20] [21 22 23 24]]] shape(x) = [2,3,4] # Example 1 perm0 = [1,0,2] y_perm0 = [[[ 1 2 3 4] [13 14 15 16]] [[ 5 6 7 8] [17 18 19 20]] [[ 9 10 11 12] [21 22 23 24]]] shape(y_perm0) = [3,2,4] # Example 2 perm1 = [2,1,0] y_perm1 = [[[ 1 13] [ 5 17] [ 9 21]] [[ 2 14] [ 6 18] [10 22]] [[ 3 15] [ 7 19] [11 23]] [[ 4 16] [ 8 20] [12 24]]] shape(y_perm1) = [4,3,2] Examples: .. code-block:: python import paddle x = paddle.randn([2, 3, 4]) x_transposed = paddle.transpose(x, perm=[1, 0, 2]) print(x_transposed.shape) # [3L, 2L, 4L] """ if in_dygraph_mode(): out, _ = _C_ops.transpose2(x, 'axis', perm) return out check_variable_and_dtype( x, 'x', ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], 'transpose') check_type(perm, 'perm', (list, tuple), 'transpose') if isinstance(perm, tuple): perm = list(perm) if len(perm) != len(x.shape): raise ValueError( "Input(perm) is the permutation of dimensions of Input(x), " "its length should be equal to dimensions of Input(x), " "but received dimension of Input(x) is %s, " "the length of Input(perm) is %s." % (len(x.shape), len(perm))) for idx, dim in enumerate(perm): if dim >= len(x.shape): raise ValueError( "Each element in Input(perm) should be less than Input(x)'s dimension, " "but %d-th element in Input(perm) is %d which exceeds Input(x)'s " "dimension %d." % (idx, perm[idx], len(x.shape))) helper = LayerHelper('transpose', **locals()) out = helper.create_variable_for_type_inference(x.dtype) x_shape = helper.create_variable_for_type_inference(x.dtype) helper.append_op( type='transpose2', inputs={'X': [x]}, outputs={'Out': [out], 'XShape': [x_shape]}, attrs={'axis': perm}) return out def im2sequence(input, filter_size=1, stride=1, padding=0, input_image_size=None, out_stride=1, name=None): r""" :api_attr: Static Graph Extracts image patches from the input tensor to form a tensor of shape {input.batch_size * output_height * output_width, filter_size_height * filter_size_width * input.channels}. This op use filter to scan images and convert these images to sequences. After expanding, the number of time step are output_height * output_width for an image, in which output_height and output_width are calculated by below equation: .. math:: output\_height = 1 + \ (padding\_up + padding\_down + input\_height - filter\_size\_height + stride\_height - 1) / stride\_height \\\\ output\_width = 1 + \ (padding\_left + padding\_right + input\_width - filter\_size\_width + stride\_width - 1) / stride\_width And the dimension of each time step is filter_size_height * filter_size_width * input.channels. Parameters: input (Variable): The input should be a 4-D Tensor in :math:`NCHW` format. The data type is float32. filter_size(int32 | List[int32]): The filter size. If filter_size is a List, it must contain two integers, :math:`[filter\_size\_height, filter\_size\_width]` . Otherwise, the filter size will be a square :math:`[filter\_size, filter\_size]` . Default is 1. stride(int32 | List[int32]): The stride size. If stride is a List, it must contain two integers, :math:`[stride\_height, stride\_width]` . Otherwise, the stride size will be a square :math:`[stride\_size, stride\_size]` . Default is 1. padding(int32 | List[int32]): The padding size. If padding is a List, it can contain four integers like :math:`[padding\_up, padding\_left, padding\_down, padding\_right]` to indicate paddings of four direction. Or it can contain two integers :math:`[padding\_height, padding\_width]` which means padding_up = padding_down = padding_height and padding_left = padding_right = padding_width. Otherwise, a scalar padding means padding_up = padding_down = padding_left = padding_right = padding. Default is 0. input_image_size(Variable, optional): the input contains image real size.It's dim is :math:`[batchsize, 2]` . It is just for batch inference when not None. Default is None. out_stride(int32 | List[int32]): The scaling of image through CNN. It is valid only when input_image_size is not None. If out_stride is List, it must contain two integers, :math:`[out\_stride\_height, out\_stride\_W]` . Otherwise, the out_stride_height = out_stride_width = out_stride. Default is 1. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: The output is a 2-D LoDTensor with shape {input.batch\_size * output\_height * output\_width, \ filter\_size\_height * filter\_size\_width * input.channels}. The data type is float32. Return Type: Variable Examples: .. code-block:: text Given: x = [[[[ 6. 2. 1.] [ 8. 3. 5.] [ 0. 2. 6.]] [[ 2. 4. 4.] [ 6. 3. 0.] [ 6. 4. 7.]]] [[[ 6. 7. 1.] [ 5. 7. 9.] [ 2. 4. 8.]] [[ 1. 2. 1.] [ 1. 3. 5.] [ 9. 0. 8.]]]] x.dims = {2, 2, 3, 3} And: filter = [2, 2] stride = [1, 1] padding = [0, 0] Then: output.data = [[ 6. 2. 8. 3. 2. 4. 6. 3.] [ 2. 1. 3. 5. 4. 4. 3. 0.] [ 8. 3. 0. 2. 6. 3. 6. 4.] [ 3. 5. 2. 6. 3. 0. 4. 7.] [ 6. 7. 5. 7. 1. 2. 1. 3.] [ 7. 1. 7. 9. 2. 1. 3. 5.] [ 5. 7. 2. 4. 1. 3. 9. 0.] [ 7. 9. 4. 8. 3. 5. 0. 8.]] output.dims = {8, 8} output.lod = [[4, 4]] Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() data = fluid.data(name='data', shape=[None, 3, 32, 32], dtype='float32') output = fluid.layers.im2sequence( input=data, stride=[1, 1], filter_size=[2, 2]) """ assert not in_dygraph_mode(), ( "sequence layer is not supported in dygraph mode yet.") check_variable_and_dtype(input, 'input', ['float32'], 'im2sequence') if isinstance(filter_size, int): filter_size = [filter_size, filter_size] if isinstance(stride, int): stride = [stride, stride] if isinstance(padding, int): padding = [padding, padding] if len(padding) == 2: padding.append(padding[0]) padding.append(padding[1]) inputs = {"X": input} attrs = {"kernels": filter_size, "strides": stride, "paddings": padding} if input_image_size: if isinstance(out_stride, int): out_stride = [out_stride, out_stride] inputs["Y"] = input_image_size attrs["out_stride"] = out_stride helper = LayerHelper('im2sequence', **locals()) out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) helper.append_op( type='im2sequence', inputs=inputs, outputs={'Out': out}, attrs=attrs) return out @templatedoc() def row_conv(input, future_context_size, param_attr=None, act=None): """ :api_attr: Static Graph ${comment} Args: input (${x_type}): ${x_comment}. future_context_size (int): Future context size. Please note, the shape of convolution kernel is [future_context_size + 1, D]. param_attr (ParamAttr): Attributes of parameters, including name, initializer etc. act (str): Non-linear activation to be applied to output variable. Returns: ${out_comment}. Examples: .. code-block:: python # for LodTensor inputs import paddle paddle.enable_static() x = paddle.static.data(name='x', shape=[9, 16], dtype='float32', lod_level=1) out = paddle.static.nn.row_conv(input=x, future_context_size=2) # for Tensor inputs x = paddle.static.data(name='x', shape=[9, 4, 16], dtype='float32') out = paddle.static.nn.row_conv(input=x, future_context_size=2) """ helper = LayerHelper('row_conv', **locals()) check_variable_and_dtype(input, 'input', ['float32'], 'row_conv') dtype = helper.input_dtype() filter_shape = [future_context_size + 1, input.shape[-1]] filter_param = helper.create_parameter( attr=helper.param_attr, shape=filter_shape, dtype=dtype) out = helper.create_variable_for_type_inference(dtype) helper.append_op( type='row_conv', inputs={'X': [input], 'Filter': [filter_param]}, outputs={'Out': [out]}) return helper.append_activation(out) @templatedoc() def multiplex(inputs, index, name=None): """ Based on the given index parameter, the OP selects a specific row from each input Tensor to construct the output Tensor. If the input of this OP contains :math:`m` Tensors, where :math:`I_{i}` means the i-th input Tensor, :math:`i` between :math:`[0,m)` . And :math:`O` means the output, where :math:`O[i]` means the i-th row of the output, then the output satisfies that :math:`O[i] = I_{index[i]}[i]` . For Example: .. code-block:: text Given: inputs = [[[0,0,3,4], [0,1,3,4], [0,2,4,4], [0,3,3,4]], [[1,0,3,4], [1,1,7,8], [1,2,4,2], [1,3,3,4]], [[2,0,3,4], [2,1,7,8], [2,2,4,2], [2,3,3,4]], [[3,0,3,4], [3,1,7,8], [3,2,4,2], [3,3,3,4]]] index = [[3],[0],[1],[2]] out = [[3,0,3,4], # out[0] = inputs[index[0]][0] = inputs[3][0] = [3,0,3,4] [0,1,3,4], # out[1] = inputs[index[1]][1] = inputs[0][1] = [0,1,3,4] [1,2,4,2], # out[2] = inputs[index[2]][2] = inputs[1][2] = [1,2,4,2] [2,3,3,4]] # out[3] = inputs[index[3]][3] = inputs[2][3] = [2,3,3,4] Args: inputs (list): The input Tensor list. The list elements are N-D Tensors of data types float32, float64, int32, int64. All input Tensor shapes should be the same and rank must be at least 2. index (Tensor): Used to select some rows in the input Tensor to construct an index of the output Tensor. It is a 2-D Tensor with data type int32 or int64 and shape [M, 1], where M is the number of input Tensors. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: Output of multiplex OP, with data type being float32, float64, int32, int64. Examples: .. code-block:: python import paddle import numpy as np img1 = np.array([[1, 2], [3, 4]]).astype(np.float32) img2 = np.array([[5, 6], [7, 8]]).astype(np.float32) inputs = [paddle.to_tensor(img1), paddle.to_tensor(img2)] index = paddle.to_tensor(np.array([[1], [0]]).astype(np.int32)) res = paddle.multiplex(inputs, index) print(res) # [array([[5., 6.], [3., 4.]], dtype=float32)] """ if in_dygraph_mode(): return _C_ops.multiplex(index, inputs) helper = LayerHelper('multiplex', **locals()) check_type(inputs, 'inputs', (list), 'multiplex') if len(inputs) < 2: raise ValueError( "inputs should be a list object with at least 2 elements.") for id, x in enumerate(inputs): check_variable_and_dtype(x, 'input[' + str(id) + ']', ['float32', 'float64', 'int32', 'int64'], 'multiplex') check_variable_and_dtype(index, "index", ['int32', 'int64'], 'multiplex') out = helper.create_variable_for_type_inference(inputs[0].dtype) helper.append_op( type='multiplex', inputs={'X': inputs, 'Ids': index}, outputs={'Out': [out]}) return out def smooth_l1(x, y, inside_weight=None, outside_weight=None, sigma=None): """ This layer computes the smooth L1 loss for Variable :attr:`x` and :attr:`y`. It takes the first dimension of :attr:`x` and :attr:`y` as batch size. For each instance, it computes the smooth L1 loss element by element first and then sums all the losses. So the shape of output Variable is [batch_size, 1]. Args: x (Variable): A tensor with rank at least 2. The input value of smooth L1 loss op with shape [batch_size, dim1, ..., dimN]. A LoDTensor or Tensor with type float32. y (Variable): A tensor with rank at least 2. The target value of smooth L1 loss op with same shape as :attr:`x`. A LoDTensor or Tensor with type float32. inside_weight (Variable|None): A tensor with rank at least 2. This input is optional and should have same shape with :attr:`x`. If provided, the result of (:attr:`x` - :attr:`y`) will be multiplied by this tensor element by element. A Tensor with type float32. outside_weight (Variable|None): A tensor with rank at least 2. This input is optional and should have same shape with :attr:`x`. If provided, the out smooth L1 loss will be multiplied by this tensor element by element. A Tensor with type float32. sigma (float|None): Hyper parameter of smooth L1 loss layer. A float scalar with default value 1.0. Returns: Variable: The output smooth L1 loss with shape [batch_size, 1]. A Tensor with type float32. Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle paddle.enable_static() data = fluid.data(name="x", shape=[-1, 3], dtype="float32") label = fluid.data(name="y", shape=[-1, 3], dtype="float32") result = fluid.layers.smooth_l1(data,label) place = fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) x = np.random.rand(3,3).astype("float32") y = np.random.rand(3,3).astype("float32") output= exe.run(feed={"x":x, "y":y}, fetch_list=[result]) print(output) #[array([[0.08220536], # [0.36652038], # [0.20541131]], dtype=float32)] """ check_variable_and_dtype(x, 'X', ['float32', 'float64'], 'smooth_l1_loss') check_variable_and_dtype(y, 'Y', ['float32', 'float64'], 'smooth_l1_loss') helper = LayerHelper('smooth_l1_loss', **locals()) diff = helper.create_variable_for_type_inference(dtype=x.dtype) loss = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='smooth_l1_loss', inputs={ 'X': x, 'Y': y, 'InsideWeight': inside_weight, 'OutsideWeight': outside_weight }, outputs={'Diff': diff, 'Out': loss}, attrs={'sigma': sigma if sigma is not None else 1.0}) return loss @deprecated(since='2.0.0', update_to='paddle.nn.functional.one_hot') def one_hot(input, depth, allow_out_of_range=False): """ **WARING:** This OP requires the last dimension of Tensor shape must be equal to 1. This OP will be deprecated in a future release. It is recommended to use fluid. :ref:`api_fluid_one_hot` . The operator converts each id in the input to an one-hot vector with a :attr:`depth` length. The value in the vector dimension corresponding to the id is 1, and the value in the remaining dimension is 0. The shape of output Tensor or LoDTensor is generated by adding :attr:`depth` dimension behind the last dimension of the input shape. .. code-block:: text Example 1 (allow_out_of_range=False): input: X.shape = [4, 1] X.data = [[1], [1], [3], [0]] depth = 4 output: Out.shape = [4, 4] Out.data = [[0., 1., 0., 0.], [0., 1., 0., 0.], [0., 0., 0., 1.], [1., 0., 0., 0.]] Example 2 (allow_out_of_range=True): input: X.shape = [4, 1] X.data = [[1], [1], [5], [0]] depth = 4 allow_out_of_range = True output: Out.shape = [4, 4] Out.data = [[0., 1., 0., 0.], [0., 1., 0., 0.], [0., 0., 0., 0.], # This id is 5, which goes beyond depth, so set it all-zeros data. [1., 0., 0., 0.]] Example 3 (allow_out_of_range=False): input: X.shape = [4, 1] X.data = [[1], [1], [5], [0]] depth = 4 allow_out_of_range = False output: Throw an exception for Illegal value The second dimension in X is 5, which is greater than depth. Allow_out_of_range =False means that does not allow the word id to exceed depth, so it throws an exception. Args: input(Variable): Tensor or LoDTensor with shape :math:`[N_1, N_2, ..., N_k, 1]` , which contains at least one dimension and the last dimension must be 1. The data type is int32 or int64. depth(scalar): An integer defining the :attr:`depth` of the one hot dimension. If input is word id, depth is generally the dictionary size. allow_out_of_range(bool): A bool value indicating whether the input indices could be out of range :math:`[0, depth)` . When input indices are out of range, exceptions :code:`Illegal value` is raised if :attr:`allow_out_of_range` is False, or zero-filling representations is created if it is set True. Default: False. Returns: Variable: The one-hot representations of input. A Tensor or LoDTensor with type float32. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() # Correspond to the first example above, where label.shape is [4, 1] and one_hot_label.shape is [4, 4]. label = fluid.data(name="label", shape=[4, 1], dtype="int64") one_hot_label = fluid.layers.one_hot(input=label, depth=4) """ if in_dygraph_mode(): if isinstance(depth, Variable): depth = depth.numpy() assert depth.shape == ( 1, ), "depth of type Variable should have shape [1]" depth = depth.item(0) out = _C_ops.one_hot(input, 'depth', depth, 'allow_out_of_range', allow_out_of_range) out.stop_gradient = True return out helper = LayerHelper("one_hot", **locals()) check_variable_and_dtype(input, 'input', ['int32', 'int64'], 'one_hot') check_type(depth, 'depth', (six.integer_types, Variable), 'one_hot') one_hot_out = helper.create_variable_for_type_inference(dtype='float32') if not isinstance(depth, Variable): # user attribute inputs = {'X': input} attrs = {'depth': depth, 'allow_out_of_range': allow_out_of_range} else: depth.stop_gradient = True inputs = {'X': input, 'depth_tensor': depth} attrs = {'allow_out_of_range': allow_out_of_range} helper.append_op( type="one_hot", inputs=inputs, attrs=attrs, outputs={'Out': one_hot_out}) one_hot_out.stop_gradient = True return one_hot_out def autoincreased_step_counter(counter_name=None, begin=1, step=1): """ :api_attr: Static Graph Create an auto-increase variable. which will be automatically increased by 1 in every iteration. By default, the first return of this counter is 1, and the step size is 1. Args: counter_name(str, optional): The counter name. Default '@STEP_COUNTER@'. begin(int, optional): The first return value of this counter. Default 1. step(int, optional): The step size. Default 1. Returns: Variable: The auto-increased Variable with data type int64. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() global_step = fluid.layers.autoincreased_step_counter( counter_name='@LR_DECAY_COUNTER@', begin=0, step=1) """ helper = LayerHelper('global_step_counter') if counter_name is None: counter_name = '@STEP_COUNTER@' counter, is_new_var = helper.create_or_get_global_variable( name=counter_name, dtype='int64', shape=[1], persistable=True, belong_to_optimizer=True) if is_new_var: helper.set_variable_initializer( counter, initializer=Constant( value=begin - 1, force_cpu=True)) helper.main_program.global_block()._prepend_op( type='increment', inputs={'X': [counter]}, outputs={'Out': [counter]}, attrs={'step': float(step)}) counter.stop_gradient = True return counter def reshape(x, shape, actual_shape=None, act=None, inplace=False, name=None): r""" :alias_main: paddle.reshape :alias: paddle.reshape,paddle.tensor.reshape,paddle.tensor.manipulation.reshape This operator changes the shape of ``x`` without changing its data. The target shape can be given by ``shape`` or ``actual_shape``. When ``shape`` and ``actual_shape`` are set at the same time, ``actual_shape`` has a higher priority than ``shape`` but at this time ``shape`` can only be an integer list or tuple, and ``shape`` still should be set correctly to guarantee shape inference in compile-time. Some tricks exist when specifying the target shape. 1. -1 means the value of this dimension is inferred from the total element number of x and remaining dimensions. Thus one and only one dimension can be set -1. 2. 0 means the actual dimension value is going to be copied from the corresponding dimension of x. The index of 0s in shape can not exceed the dimension of x. Here are some examples to explain it. 1. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape is [6, 8], the reshape operator will transform x into a 2-D tensor with shape [6, 8] and leaving x's data unchanged. 2. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape specified is [2, 3, -1, 2], the reshape operator will transform x into a 4-D tensor with shape [2, 3, 4, 2] and leaving x's data unchanged. In this case, one dimension of the target shape is set to -1, the value of this dimension is inferred from the total element number of x and remaining dimensions. 3. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape is [-1, 0, 3, 2], the reshape operator will transform x into a 4-D tensor with shape [2, 4, 3, 2] and leaving x's data unchanged. In this case, besides -1, 0 means the actual dimension value is going to be copied from the corresponding dimension of x. **Note**: The parameter ``actual_shape`` will be deprecated in the future and only use ``shape`` instead to represent the target shape. Args: x(Tensor): An N-D Tensor. The data type is ``float32``, ``float64``, ``int32`` or ``int64``. shape(list|tuple|Tensor): Define the target shape. At most one dimension of the target shape can be -1. The data type is ``int32`` . If ``shape`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``shape`` is an Tensor, it should be an 1-D Tensor . actual_shape(variable, optional): An 1-D ``Tensor`` or ``LoDTensor`` . The data type is ``int32`` . If provided, reshape according to this given shape rather than ``shape`` specifying shape. That is to say ``actual_shape`` has a higher priority than ``shape(list|tuple)`` but not ``shape(Tensor)``. \ This argument ``actual_shape`` will be removed in a future version. \ Instructions for updating: ``actual_shape`` will be removed in future versions and replaced by ``shape``. act (str, optional): The non-linear activation to be applied to the reshaped input. Default None. inplace(bool, optional): If ``inplace`` is True, the input and output of ``layers.reshape`` are the same variable. Otherwise, the input and output of ``layers.reshape`` are different variable. Default False. Note that if ``x`` is more than one OPs' input, ``inplace`` must be False. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Tensor: A reshaped Tensor with the same data type as ``x``. It is a new tensor variable if ``inplace`` is ``False``, otherwise it is ``x``. If ``act`` is None, return the reshaped tensor variable, otherwise return the activated tensor variable. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() # example 1: # attr shape is a list which doesn't contain Tensors. data_1 = fluid.data( name='data_1', shape=[2, 4, 6], dtype='float32') reshaped_1 = fluid.layers.reshape( x=data_1, shape=[-1, 0, 3, 2]) # the shape of reshaped_1 is [2,4,3,2]. # example 2: # attr shape is a list which contains Tensors. data_2 = fluid.layers.fill_constant([2,25], "int32", 3) dim = fluid.layers.fill_constant([1], "int32", 5) reshaped_2 = fluid.layers.reshape(data_2, shape=[dim, 10]) # the shape of reshaped_2 is [5,10]. # example 3: data_3 = fluid.data( name="data_3", shape=[2,4,6], dtype='float32') reshaped_3 = fluid.layers.reshape(x=data_3, shape=[6,8]) # the shape of reshaped_3 is [6,8]. """ if in_dygraph_mode(): #TODO(zhiqiu): enable inplace in dygraph mode. if inplace: warnings.warn( "Inplace on reshape is not allowed and will be discarded in dygraph mode currently." ) if isinstance(shape, (list, tuple)): shape = [ item.numpy().item(0) if isinstance(item, Variable) else item for item in shape ] out, _ = _C_ops.reshape2(x, None, 'shape', shape) elif isinstance(shape, Variable): shape.stop_gradient = True out, _ = _C_ops.reshape2(x, shape) else: raise ValueError( "shape must be an instance of `list`, `tuple` or `Variable`," " got '{}.'".format(type(shape))) return dygraph_utils._append_activation_in_dygraph(out, act) check_variable_and_dtype(x, 'x', [ 'float16', 'float32', 'float64', 'int32', 'int64', 'bool', 'uint16' ], 'reshape') check_type(shape, 'shape', (list, tuple, Variable), 'reshape') check_type(actual_shape, 'actual_shape', (Variable, type(None)), 'reshape') helper = LayerHelper("reshape2", **locals()) def get_attr_shape(list_shape): unk_dim_idx = -1 attrs_shape = [] for dim_idx, dim_size in enumerate(list_shape): if isinstance(dim_size, Variable): attrs_shape.append(-1) else: attrs_shape.append(dim_size) if dim_size == -1: assert unk_dim_idx == -1, ( "Only one dimension value of 'shape' in reshape can " "be -1. But received shape[%d] is also -1." % dim_idx) unk_dim_idx = dim_idx elif dim_size == 0: assert dim_idx < len(x.shape), ( "The index of 0 in `shape` must be less than " "the input tensor X's dimensions. " "But received shape[%d] = 0, X's dimensions = %d." % (dim_idx, len(x.shape))) else: assert dim_size > 0, ( "Each dimension value of 'shape' in reshape must not " "be negative except one unknown dimension. " "But received shape[%d] = %s." % (dim_idx, str(dim_size))) return attrs_shape inputs = {"X": x} attrs = {} if isinstance(shape, Variable): shape.stop_gradient = True inputs["Shape"] = shape elif isinstance(shape, (list, tuple)): assert len(shape) > 0, ("The size of 'shape' in reshape can't be zero, " "but received %s." % len(shape)) attrs["shape"] = get_attr_shape(shape) if utils._contain_var(shape): inputs['ShapeTensor'] = utils._convert_to_tensor_list(shape) elif isinstance(actual_shape, Variable): actual_shape.stop_gradient = True inputs["Shape"] = actual_shape out = x if inplace else helper.create_variable_for_type_inference( dtype=x.dtype) x_shape = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type="reshape2", inputs=inputs, attrs=attrs, outputs={"Out": out, "XShape": x_shape}) return helper.append_activation(out) def squeeze(input, axes, name=None): """ This OP will squeeze single-dimensional entries of input tensor's shape. If axes is provided, will remove the dims by axes, the dims selected by axes should be one. If not provide axes, all dims equal to one will be deleted. .. code-block:: text Case1: Input: X.shape = (1, 3, 1, 5) axes = [0] Output: Out.shape = (3, 1, 5) Case2: Input: X.shape = (1, 3, 1, 5) axes = [] Output: Out.shape = (3, 5) Case3: Input: X.shape = [1,3,1,5] axes = [-2] Output: Out.shape = [1,3,5] Args: input (Variable): The input Tensor. Supported data type: float32, float64, bool, int8, int32, int64. axes (list): One integer or List of integers, indicating the dimensions to be squeezed. Axes range is :math:`[-rank(input), rank(input))`. If axes is negative, :math:`axes=axes+rank(input)`. name (str, optional): Please refer to :ref:`api_guide_Name`, Default None. Returns: Variable: Output squeezed Tensor. Data type is same as input Tensor. Examples: .. code-block:: python import paddle.fluid as fluid import paddle.fluid.layers as layers # set batch size=None x = fluid.data(name='x', shape=[None, 5, 1, 10]) y = layers.squeeze(input=x, axes=[2]) # y.shape=[None, 5, 10] """ if in_dygraph_mode(): out, _ = _C_ops.squeeze2(input, 'axes', axes) return out helper = LayerHelper("squeeze", **locals()) check_variable_and_dtype( input, 'input', ['float16', 'float32', 'float64', 'bool', 'int8', 'int32', 'int64'], 'squeeze') check_type(axes, 'axis/axes', (list, tuple), 'squeeze') out = helper.create_variable_for_type_inference(dtype=input.dtype) x_shape = helper.create_variable_for_type_inference(dtype=input.dtype) helper.append_op( type="squeeze2", inputs={"X": input}, attrs={"axes": axes}, outputs={"Out": out, "XShape": x_shape}) return out def unsqueeze(input, axes, name=None): """ Insert single-dimensional entries to the shape of a Tensor. Takes one required argument axes, a list of dimensions that will be inserted. Dimension indices in axes are as seen in the output tensor. For example: .. code-block:: text Given a tensor such that tensor with shape [3, 4, 5], then Unsqueezed tensor with axes=[0, 4] has shape [1, 3, 4, 5, 1]. Args: input (Variable): The input Tensor to be unsqueezed. Supported data type: float32, float64, bool, int8, int32, int64. axes (int|list|tuple|Variable): Indicates the dimensions to be inserted. The data type is ``int32`` . If ``axes`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``axes`` is an Variable, it should be an 1-D Tensor . name (str|None): Name for this layer. Returns: Variable: Unsqueezed Tensor, with the same data type as input. Examples: .. code-block:: python import paddle.fluid as fluid x = fluid.layers.data(name='x', shape=[5, 10]) y = fluid.layers.unsqueeze(input=x, axes=[1]) """ if in_dygraph_mode(): if isinstance(axes, int): axes = [axes] elif isinstance(axes, Variable): axes = axes.numpy().tolist() elif isinstance(axes, (list, tuple)): axes = [ item.numpy().item(0) if isinstance(item, Variable) else item for item in axes ] out, _ = _C_ops.unsqueeze2(input, 'axes', axes) return out check_type(axes, 'axis/axes', (int, list, tuple, Variable), 'unsqueeze') check_variable_and_dtype( input, 'input', ['float16', 'float32', 'float64', 'bool', 'int8', 'int32', 'int64'], 'unsqueeze') helper = LayerHelper("unsqueeze2", **locals()) inputs = {"X": input} attrs = {} if isinstance(axes, int): axes = [axes] if isinstance(axes, Variable): axes.stop_gradient = True inputs["AxesTensor"] = axes elif isinstance(axes, (list, tuple)): if utils._contain_var(axes): inputs["AxesTensorList"] = utils._convert_to_tensor_list(axes) else: attrs["axes"] = axes out = helper.create_variable_for_type_inference(dtype=input.dtype) x_shape = helper.create_variable_for_type_inference(dtype=input.dtype) helper.append_op( type="unsqueeze2", inputs=inputs, attrs=attrs, outputs={"Out": out, "XShape": x_shape}) return out def lod_reset(x, y=None, target_lod=None): """ Set LoD of :attr:`x` to a new one specified by :attr:`y` or :attr:`target_lod`. When :attr:`y` provided, :attr:`y.lod` would be considered as target LoD first, otherwise :attr:`y.data` would be considered as target LoD. If :attr:`y` is not provided, target LoD should be specified by :attr:`target_lod`. If target LoD is specified by :attr:`y.data` or :attr:`target_lod`, only one level LoD is supported. .. code-block:: text * Example 1: Given a 1-level LoDTensor x: x.lod = [[ 2, 3, 1 ]] x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] x.dims = [6, 1] target_lod: [4, 2] then we get a 1-level LoDTensor: out.lod = [[4, 2]] out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] out.dims = [6, 1] * Example 2: Given a 1-level LoDTensor x: x.lod = [[2, 3, 1]] x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] x.dims = [6, 1] y is a Tensor: y.data = [[2, 4]] y.dims = [1, 3] then we get a 1-level LoDTensor: out.lod = [[2, 4]] out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] out.dims = [6, 1] * Example 3: Given a 1-level LoDTensor x: x.lod = [[2, 3, 1]] x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] x.dims = [6, 1] y is a 2-level LoDTensor: y.lod = [[2, 2], [2, 2, 1, 1]] y.data = [[1.1], [2.1], [3.1], [4.1], [5.1], [6.1]] y.dims = [6, 1] then we get a 2-level LoDTensor: out.lod = [[2, 2], [2, 2, 1, 1]] out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] out.dims = [6, 1] Args: x (Variable): Input variable which could be a Tensor or LoDTensor. The data type should be int32, int64, float32 or float64. y (Variable, optional): If provided, output's LoD would be derived from :attr:`y`. If y's lod level>0, the data type can be any type. If y's lod level=0, the data type should be int32. target_lod (list|tuple, optional): One level LoD which should be considered as target LoD when :attr:`y` not provided. Returns: Variable: Output variable with LoD specified by this layer. Raises: ValueError: If :attr:`y` and :attr:`target_lod` are both None. Examples: .. code-block:: python import paddle.fluid as fluid x = fluid.layers.data(name='x', shape=[10]) y = fluid.layers.data(name='y', shape=[10, 20], lod_level=2) out = fluid.layers.lod_reset(x=x, y=y) """ check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], 'lod_reset') helper = LayerHelper("lod_reset", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) if y is not None: check_type(y, 'y', (Variable), 'lod_reset') #TODO: check y.lod_level = 0 dtype helper.append_op( type="lod_reset", inputs={'X': x, 'Y': y}, outputs={'Out': out}) elif target_lod is not None: helper.append_op( type="lod_reset", inputs={'X': x}, attrs={'target_lod': target_lod}, outputs={'Out': out}) else: raise ValueError("y and target_lod should not be both none.") return out def lod_append(x, level): """ Append level to LoD of :attr:`x`. .. code-block:: text * Example 1: given a 1-level LoDTensor x: x.lod = [[ 2, 3, 1 ]] x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] x.dims = [6, 1] level: [1, 1, 1, 1, 1, 1, 1] then we get a 2-level LoDTensor: x.lod = [[ 2, 3, 1 ], [1, 1, 1, 1, 1, 1]] x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] x.dims = [6, 1] Args: x (Variable): Input variable which could be a tensor or LoDTensor. The data type should be int32, int64, float32 or float64. level (list|tuple|Variable, optional): The LoD level to be appended into LoD of x. If level is variable and its lod level>0, the data type can be any type. If level is variable and its lod level=0, the data type should be int32. Returns: Variable: Output variable with new LoD level. Raises: ValueError: If :attr:`y` is None or and :attr:`level` is not Iterator. Examples: .. code-block:: python import paddle.fluid as fluid x = fluid.layers.data(name='x', shape=[6, 10], lod_level=1) out = fluid.layers.lod_append(x, [1,1,1,1,1,1]) """ from collections import Iterable if x is None: raise ValueError("Input(x) can't be None.") if (not isinstance(level, Iterable)) and (not isinstance(level, Variable)): raise ValueError("Input(level) must be list, tuple or Variable.") check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], 'lod_append') helper = LayerHelper("lod_append", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) inputs = {'X': x} attrs = {'append': True} if isinstance(level, Variable): inputs['Y'] = level #TODO: check y.lod_level = 0 dtype else: attrs['target_lod'] = level helper.append_op( type="lod_reset", inputs=inputs, attrs=attrs, outputs={'Out': out}) return out def lrn(input, n=5, k=1.0, alpha=1e-4, beta=0.75, name=None, data_format='NCHW'): r""" :alias_main: paddle.nn.functional.lrn :alias: paddle.nn.functional.lrn,paddle.nn.functional.norm.lrn :old_api: paddle.fluid.layers.lrn This operator implements the Local Response Normalization Layer. This layer performs a type of "lateral inhibition" by normalizing over local input regions. For more information, please refer to `ImageNet Classification with Deep Convolutional Neural Networks <https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf>`_ The formula is as follows: .. math:: Output(i, x, y) = Input(i, x, y) / \\left(k + \\alpha \\sum\\limits^{\\min(C-1, i + n/2)}_{j = \\max(0, i - n/2)}(Input(j, x, y))^2\\right)^{\\beta} In the above equation: - :math:`n` : The number of channels to sum over. - :math:`k` : The offset (avoid being divided by 0). - :math:`\\alpha` : The scaling parameter. - :math:`\\beta` : The exponent parameter. Args: input (Variable): Input feature, 4D-Tensor with the shape of [N,C,H,W] or [N, H, W, C], where N is the batch size, C is the input channel, H is Height, W is weight. The data type is float32. The rank of this tensor must be 4, otherwise it will raise ValueError. n (int, optional): The number of channels to sum over. Default: 5 k (float, optional): An offset, positive. Default: 1.0 alpha (float, optional): The scaling parameter, positive. Default:1e-4 beta (float, optional): The exponent, positive. Default:0.75 name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. Returns: Variable: A tensor variable storing the transformation result with the same shape and data type as input. Examples: .. code-block:: python import paddle.fluid as fluid data = fluid.data( name="data", shape=[None, 3, 112, 112], dtype="float32") lrn = fluid.layers.lrn(input=data) print(lrn.shape) # [-1, 3, 112, 112] print(lrn.dtype) # float32 """ helper = LayerHelper('lrn', **locals()) check_variable_and_dtype(input, 'input', ['float32'], 'lrn') dtype = helper.input_dtype() input_shape = input.shape dims = len(input_shape) if dims != 4: raise ValueError( "Input's dimension size of Op(lrn) must be 4, but received %d." % (dims)) if data_format not in ['NCHW', 'NHWC']: raise ValueError( "Attr(data_format) of Op(lrn) got wrong value: received " + data_format + " but only NCHW or NHWC supported.") mid_out = helper.create_variable_for_type_inference( dtype=dtype, stop_gradient=True) lrn_out = helper.create_variable_for_type_inference(dtype) helper.append_op( type="lrn", inputs={"X": input}, outputs={ "Out": lrn_out, "MidOut": mid_out, }, attrs={ "n": n, "k": k, "alpha": alpha, "beta": beta, "data_format": data_format }) return lrn_out def pad(x, paddings, pad_value=0., name=None): r""" :alias_main: paddle.nn.functional.pad :alias: paddle.nn.functional.pad,paddle.nn.functional.common.pad :old_api: paddle.fluid.layers.pad This op will pad a tensor with a constant value given by :attr:`pad_value`, and the padded shape is specified by :attr:`paddings`. Specifically, the number of values padded before the elements of :attr:`x` in dimension :attr:`i` is indicated by :attr:`paddings[2*i]`, and the number of values padded after the elements of :attr:`x` in dimension :attr:`i` is indicated by :attr:`paddings[2*i+1]`. See below for an example. .. code-block:: text Given: x = [[1, 2], [3, 4]] paddings = [0, 1, 1, 2] pad_value = 0 Return: out = [[0, 1, 2, 0, 0] [0, 3, 4, 0, 0] [0, 0, 0, 0, 0]] Args: x (Variable): Tensor, data type is float32. paddings (list): A list of integers. Its elements specify the padded width before and after each dimension in turn. The length of :attr:`paddings` must be equal to :math:`rank(x) \\times 2`. pad_value (float): The constant value used to pad. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: The padded tensor, with the same data type and rank as :attr:`x` Return Type: Variable Examples: .. code-block:: python # x is a rank 2 tensor variable import paddle.fluid as fluid x = fluid.data(name='data', shape=[300, 300], dtype='float32') out = fluid.layers.pad(x=x, paddings=[0, 1, 1, 2], pad_value=0.) """ check_variable_and_dtype(x, 'x', [ 'float16', 'float32', 'float64', 'int32', 'int64', 'complex64', 'complex128' ], "pad") helper = LayerHelper('pad', **locals()) dtype = helper.input_dtype(input_param_name='x') out = helper.create_variable_for_type_inference(dtype) helper.append_op( type='pad', inputs={'X': x}, outputs={'Out': out}, attrs={'paddings': paddings, 'pad_value': float(pad_value)}) return out def pad_constant_like(x, y, pad_value=0., name=None): r""" Pad :attr:`y` with :attr:`pad_value`, the number of values padded to the edges of each axis is specified by the difference of the shape of :attr:`x` and :attr:`y` . ((0, shape_x_0 - shape_y_0), ... (0, shape_x_n - shape_y_n)) specify padding widths for each axis. The input should be a k-D tensor(k > 0 and k < 7). See below for an example. .. code-block:: text Given: X = [[[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 7, 8], [ 9, 10, 11]], [[12, 13, 14], [15, 16, 17]]], [[[18, 19, 20], [21, 22, 23]], [[24, 25, 26], [27, 28, 29]], [[30, 31, 32], [33, 34, 35]]]] X.shape = (2, 3, 2, 3) Y = [[[[35, 36, 37]], [[38, 39, 40]], [[41, 42, 43]]]] Y.shape = (1, 3, 1, 3) And pad_value = 0. Return: Out = [[[[35, 36, 37], [ 0, 0, 0]], [[38, 39, 40], [ 0, 0, 0]], [[41, 42, 43], [ 0, 0, 0]]], [[[ 0, 0, 0], [ 0, 0, 0]], [[ 0, 0, 0], [ 0, 0, 0]], [[ 0, 0, 0], [ 0, 0, 0]]]] Out.shape = [2, 3, 2, 3] Args: x (Variable): Tensor, its shape specifies the shape of output. y (Variable): Tensor, its rank is the same with :attr:`x`, and for each dimension :math:`i` , :math:`y\_shape[i] <= x\_shape[i]` . The data type can be float32 or float64. pad_value (float): The constant value used to pad. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: The padded tensor, with the same shape as :attr:`x` and the same data type as :attr:`y` Return Type: Variable Examples: .. code-block:: python # x is a rank 4 tensor variable, x.shape = (2, 3, 2, 3) # y is a rank 4 tensor variable, y.shape = (1, 3, 1, 3) import paddle.fluid as fluid x = fluid.data(name='x', shape=[2,3,2,3], dtype='float32') y = fluid.data(name='y', shape=[1,3,1,3], dtype='float32') out = fluid.layers.pad_constant_like(x=x, y=y, pad_value=0.) # out is a rank 4 tensor variable, and out.shape = [2, 3 ,2 , 3] """ check_type(x, 'x', (Variable), 'pad_constant_like') check_variable_and_dtype(y, 'y', ['float32', 'float64', 'int32', 'int64'], "pad_constant_like") helper = LayerHelper('pad_constant_like', **locals()) dtype = helper.input_dtype(input_param_name='y') out = helper.create_variable_for_type_inference(dtype) helper.append_op( type='pad_constant_like', inputs={'X': x, 'Y': y}, outputs={'Out': out}, attrs={'pad_value': float(pad_value)}) return out def label_smooth(label, prior_dist=None, epsilon=0.1, dtype="float32", name=None): r""" :alias_main: paddle.nn.functional.label_smooth :alias: paddle.nn.functional.label_smooth,paddle.nn.functional.common.label_smooth :old_api: paddle.fluid.layers.label_smooth Label smoothing is a mechanism to regularize the classifier layer and is called label-smoothing regularization (LSR). Label smoothing is proposed to encourage the model to be less confident, since optimizing the log-likelihood of the correct label directly may cause overfitting and reduce the ability of the model to adapt. Label smoothing replaces the ground-truth label :math:`y` with the weighted sum of itself and some fixed distribution :math:`\mu`. For class :math:`k`, i.e. .. math:: \\tilde{y_k} = (1 - \epsilon) * y_k + \epsilon * \mu_k, where :math:`1 - \epsilon` and :math:`\epsilon` are the weights respectively, and :math:`\\tilde{y}_k` is the smoothed label. Usually uniform distribution is used for :math:`\mu`. See more details about label smoothing in https://arxiv.org/abs/1512.00567. Parameters: label(Variable): The input variable containing the label data. The label data should use one-hot representation. It's a multidimensional tensor with a shape of :math:`[N_1, ..., Depth]`, where Depth is class number. The dtype can be "float32" and "float64". prior_dist(Variable, optional): The prior distribution to be used to smooth labels. If not provided, an uniform distribution is used. It's a multidimensional tensor with a shape of :math:`[1, class\_num]` . The default value is None. epsilon(float, optional): The weight used to mix up the original ground-truth distribution and the fixed distribution. The default value is 0.1. dtype(np.dtype|core.VarDesc.VarType|str, optional): The data type can be set as 'float32', 'float64'. The default value is 'float32'. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Variable: The tensor variable containing the smoothed labels. Examples: .. code-block:: python import paddle.fluid as fluid import paddle.fluid.layers as layers label = layers.data(name="label", shape=[1], dtype="int32") one_hot_label = layers.one_hot(input=label, depth=10) smooth_label = layers.label_smooth( label=one_hot_label, epsilon=0.1, dtype="float32") """ if epsilon > 1. or epsilon < 0.: raise ValueError("The value of epsilon must be between 0 and 1.") if in_dygraph_mode(): return _C_ops.label_smooth(label, prior_dist, 'epsilon', float(epsilon)) check_variable_and_dtype(label, 'label', ['float32', 'float64'], 'label_smooth') helper = LayerHelper("label_smooth", **locals()) label.stop_gradient = True smooth_label = helper.create_variable_for_type_inference(dtype) helper.append_op( type="label_smooth", inputs={"X": label, "PriorDist": prior_dist} if prior_dist else {"X": label}, outputs={"Out": smooth_label}, attrs={"epsilon": float(epsilon)}) return smooth_label @templatedoc() def roi_pool(input, rois, pooled_height=1, pooled_width=1, spatial_scale=1.0, rois_num=None, name=None): """ This operator implements the roi_pooling layer. Region of interest pooling (also known as RoI pooling) is to perform max pooling on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7). The operator has three steps: 1. Dividing each region proposal into equal-sized sections with the pooled_width and pooled_height; 2. Finding the largest value in each section; 3. Copying these max values to the output buffer. For more information, please refer to https://stackoverflow.com/questions/43430056/what-is-roi-layer-in-fast-rcnn Args: input (Variable): Input feature, 4D-Tensor with the shape of [N,C,H,W], where N is the batch size, C is the input channel, H is Height, W is weight. The data type is float32 or float64. rois (Variable): ROIs (Regions of Interest) to pool over. 2D-LoDTensor with the shape of [num_rois,4], the lod level is 1. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates. pooled_height (int, optional): The pooled output height, data type is int32. Default: 1 pooled_width (int, optional): The pooled output height, data type is int32. Default: 1 spatial_scale (float, optional): Multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling. Default: 1.0 rois_num (Tensor): The number of RoIs in each image. Default: None name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Variable: The pooled feature, 4D-Tensor with the shape of [num_rois, C, pooled_height, pooled_width]. Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle paddle.enable_static() DATATYPE='float32' place = fluid.CPUPlace() #place = fluid.CUDAPlace(0) input_data = np.array([i for i in range(1,17)]).reshape(1,1,4,4).astype(DATATYPE) roi_data =fluid.create_lod_tensor(np.array([[1., 1., 2., 2.], [1.5, 1.5, 3., 3.]]).astype(DATATYPE),[[2]], place) rois_num_data = np.array([2]).astype('int32') x = fluid.data(name='input', shape=[None,1,4,4], dtype=DATATYPE) rois = fluid.data(name='roi', shape=[None,4], dtype=DATATYPE) rois_num = fluid.data(name='rois_num', shape=[None], dtype='int32') pool_out = fluid.layers.roi_pool( input=x, rois=rois, pooled_height=1, pooled_width=1, spatial_scale=1.0, rois_num=rois_num) exe = fluid.Executor(place) out, = exe.run(feed={'input':input_data ,'roi':roi_data, 'rois_num': rois_num_data}, fetch_list=[pool_out.name]) print(out) #array([[[[11.]]], [[[16.]]]], dtype=float32) print(np.array(out).shape) # (2, 1, 1, 1) """ if in_dygraph_mode(): assert rois_num is not None, "rois_num should not be None in dygraph mode." pool_out, argmaxes = _C_ops.roi_pool( input, rois, rois_num, "pooled_height", pooled_height, "pooled_width", pooled_width, "spatial_scale", spatial_scale) return pool_out, argmaxes check_variable_and_dtype(input, 'input', ['float32'], 'roi_pool') check_variable_and_dtype(rois, 'rois', ['float32'], 'roi_pool') helper = LayerHelper('roi_pool', **locals()) dtype = helper.input_dtype() pool_out = helper.create_variable_for_type_inference(dtype) argmaxes = helper.create_variable_for_type_inference(dtype='int32') inputs = { "X": input, "ROIs": rois, } if rois_num is not None: inputs['RoisNum'] = rois_num helper.append_op( type="roi_pool", inputs=inputs, outputs={"Out": pool_out, "Argmax": argmaxes}, attrs={ "pooled_height": pooled_height, "pooled_width": pooled_width, "spatial_scale": spatial_scale }) return pool_out @templatedoc() def roi_align(input, rois, pooled_height=1, pooled_width=1, spatial_scale=1.0, sampling_ratio=-1, rois_num=None, name=None): """ ${comment} Args: input (Variable): ${x_comment} rois (Variable): ROIs (Regions of Interest) to pool over.It should be a 2-D LoDTensor of shape (num_rois, 4), the lod level is 1. The data type is float32 or float64. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates. pooled_height (int32, optional): ${pooled_height_comment} Default: 1 pooled_width (int32, optional): ${pooled_width_comment} Default: 1 spatial_scale (float32, optional): ${spatial_scale_comment} Default: 1.0 sampling_ratio(int32, optional): ${sampling_ratio_comment} Default: -1 rois_num (Tensor): The number of RoIs in each image. Default: None name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Variable: Output: ${out_comment}. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() x = fluid.data( name='data', shape=[None, 256, 32, 32], dtype='float32') rois = fluid.data( name='rois', shape=[None, 4], dtype='float32') rois_num = fluid.data(name='rois_num', shape=[None], dtype='int32') align_out = fluid.layers.roi_align(input=x, rois=rois, pooled_height=7, pooled_width=7, spatial_scale=0.5, sampling_ratio=-1, rois_num=rois_num) """ if in_dygraph_mode(): assert rois_num is not None, "rois_num should not be None in dygraph mode." align_out = _C_ops.roi_align( input, rois, rois_num, "pooled_height", pooled_height, "pooled_width", pooled_width, "spatial_scale", spatial_scale, "sampling_ratio", sampling_ratio) return align_out check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'roi_align') check_variable_and_dtype(rois, 'rois', ['float32', 'float64'], 'roi_align') helper = LayerHelper('roi_align', **locals()) dtype = helper.input_dtype() align_out = helper.create_variable_for_type_inference(dtype) inputs = { "X": input, "ROIs": rois, } if rois_num is not None: inputs['RoisNum'] = rois_num helper.append_op( type="roi_align", inputs=inputs, outputs={"Out": align_out}, attrs={ "pooled_height": pooled_height, "pooled_width": pooled_width, "spatial_scale": spatial_scale, "sampling_ratio": sampling_ratio }) return align_out def dice_loss(input, label, epsilon=0.00001, name=None): r""" Dice loss for comparing the similarity between the input predictions and the label. This implementation is for binary classification, where the input is sigmoid predictions of each pixel, usually used for segmentation task. The dice loss can be defined as the following equation: .. math:: dice\_loss &= 1 - \frac{2 * intersection\_area}{total\_area} \\ &= \frac{(total\_area - intersection\_area) - intersection\_area}{total\_area} \\ &= \frac{(union\_area - intersection\_area)}{total\_area} Parameters: input (Tensor): Tensor, rank>=2, shape is :math:`[N_1, N_2, ..., N_k, D]`, where :math:`N_1` is the batch_size, :math:`D` is the number of categories. It is usually the output predictions of sigmoid activation. The data type can be float32 or float64. label (Tensor): Tensor, the groud truth with the same rank as input, shape is :math:`[N_1, N_2, ..., N_k, 1]`. where :math:`N_1` is the batch_size. The data type can be int32 or int64. epsilon (float): The epsilon will be added to the numerator and denominator. If both input and label are empty, it makes sure dice is 1. Default: 0.00001 name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor, which shape is [1], data type is the same as `input` . Example: .. code-block:: python import paddle import paddle.nn.functional as F x = paddle.randn((3,224,224,2)) label = paddle.randint(high=2, shape=(3,224,224,1)) predictions = F.softmax(x) loss = F.dice_loss(input=predictions, label=label) """ assert input.dtype in (paddle.float32, paddle.float64) assert label.dtype in (paddle.int32, paddle.int64) assert len(input.shape) >= 2, \ "The rank of input should be greater than or equal to 2." assert len(input.shape) == len(label.shape), ( "The rank of input and label should be equal, " "but received input: %d, label: %d." % (len(input.shape), len(label.shape))) assert label.shape[-1] == 1, ("The last dimension of label should be 1, " "but received %d." % label.shape[-1]) assert input.shape[:-1] == label.shape[:-1], ( "All dimensions should be equal except the last one.") assert input.numel() > 0 and label.numel() > 0, \ "Any dimension of input and label cannot be equal to 0." label = squeeze(label, [-1]) label = paddle.nn.functional.one_hot(label, input.shape[-1]) reduce_dim = list(range(1, len(input.shape))) inse = reduce_sum(input * label, dim=reduce_dim) dice_denominator = reduce_sum( input, dim=reduce_dim) + reduce_sum( label, dim=reduce_dim) dice_score = 1 - inse * 2 / (dice_denominator + epsilon) return reduce_mean(dice_score) def image_resize(input, out_shape=None, scale=None, name=None, resample='BILINEAR', actual_shape=None, align_corners=True, align_mode=1, data_format='NCHW'): """ This op resizes a batch of images. The input must be a 3-D Tensor of the shape (num_batches, channels, in_w) or a 4-D Tensor of the shape (num_batches, channels, in_h, in_w) or (num_batches, in_h, in_w, channels), or a 5-D Tensor of the shape (num_batches, channels, in_d, in_h, in_w) or (num_batches, in_d, in_h, in_w, channels), and the resizing only applies on the three dimensions(depth, height and width). **Warning:** the parameter :attr:`actual_shape` will be deprecated in the future and only use :attr:`out_shape` instead. Supporting resample methods: 'LINEAR' : Linear interpolation 'BILINEAR' : Bilinear interpolation 'TRILINEAR' : Trilinear interpolation 'NEAREST' : Nearest neighbor interpolation 'BICUBIC' : Bicubic interpolation Linear interpolation is the method of using a line connecting two known quantities to determine the value of an unknown quantity between the two known quantities. Nearest neighbor interpolation is to perform nearest neighbor interpolation in both the 3rd dimension(in height direction) and the 4th dimension(in width direction) on input tensor. Bilinear interpolation is an extension of linear interpolation for interpolating functions of two variables (e.g. H-direction and W-direction in this op) on a rectilinear 2D grid. The key idea is to perform linear interpolation first in one direction, and then again in the other direction. Trilinear interpolation is an extension of linear interpolation for interpolating functions of three variables (e.g. D-direction, H-direction and W-direction in this op) on a rectilinear 3D grid. The linear interpolation is performed on three directions. Bicubic interpolation is an extension of cubic interpolation for interpolating data points on a two-dimensional regular grid. The interpolated surface is smoother than corresponding surfaces obtained by bilinear interpolation or nearest-neighbor interpolation. Align_corners and align_mode are optional parameters,the calculation method of interpolation can be selected by them. Example: .. code-block:: text For scale: if align_corners = True && out_size > 1 : scale_factor = (in_size-1.0)/(out_size-1.0) else: scale_factor = float(in_size/out_size) Nearest neighbor interpolation: if: align_corners = False input : (N,C,H_in,W_in) output: (N,C,H_out,W_out) where: H_out = floor (H_{in} * scale_{factor}) W_out = floor (W_{in} * scale_{factor}) else: align_corners = True input : (N,C,H_in,W_in) output: (N,C,H_out,W_out) where: H_out = round(H_{in} * scale_{factor}) W_out = round(W_{in} * scale_{factor}) linear interpolation: if: align_corners = False , align_mode = 0 input : (N,C,W_in) output: (N,C,W_out) where: W_out = (W_{in}+0.5) * scale_{factor} - 0.5 else: input : (N,C,W_in) output: (N,C,H_out,W_out) where: W_out = W_{in} * scale_{factor} Bilinear interpolation: if: align_corners = False , align_mode = 0 input : (N,C,H_in,W_in) output: (N,C,H_out,W_out) where: H_out = (H_{in}+0.5) * scale_{factor} - 0.5 W_out = (W_{in}+0.5) * scale_{factor} - 0.5 else: input : (N,C,H_in,W_in) output: (N,C,H_out,W_out) where: H_out = H_{in} * scale_{factor} W_out = W_{in} * scale_{factor} Trilinear interpolation: if: align_corners = False , align_mode = 0 input : (N,C,D_in,H_in,W_in) output: (N,C,D_out,H_out,W_out) where: D_out = (D_{in}+0.5) * scale_{factor} - 0.5 H_out = (H_{in}+0.5) * scale_{factor} - 0.5 W_out = (W_{in}+0.5) * scale_{factor} - 0.5 else: input : (N,C,D_in,H_in,W_in) output: (N,C,D_out,H_out,W_out) where: D_out = D_{in} * scale_{factor} Trilinear interpolation: if: align_corners = False , align_mode = 0 input : (N,C,D_in,H_in,W_in) output: (N,C,D_out,H_out,W_out) where: D_out = (D_{in}+0.5) * scale_{factor} - 0.5 H_out = (H_{in}+0.5) * scale_{factor} - 0.5 W_out = (W_{in}+0.5) * scale_{factor} - 0.5 else: input : (N,C,D_in,H_in,W_in) output: (N,C,D_out,H_out,W_out) where: D_out = D_{in} * scale_{factor} H_out = H_{in} * scale_{factor} W_out = W_{in} * scale_{factor} For details of linear interpolation, please refer to Wikipedia: https://en.wikipedia.org/wiki/Linear_interpolation. For details of nearest neighbor interpolation, please refer to Wikipedia: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation. For details of bilinear interpolation, please refer to Wikipedia: https://en.wikipedia.org/wiki/Bilinear_interpolation. For details of trilinear interpolation, please refer to Wikipedia: https://en.wikipedia.org/wiki/Trilinear_interpolation. For details of bicubic interpolation, please refer to Wikipedia: https://en.wikipedia.org/wiki/Bicubic_interpolation Parameters: input (Variable): 3-D, 4-D or 5-D Tensor, its data type is float32, float64, or uint8, its data format is specified by :attr:`data_format`. out_shape (list|tuple|Variable|None): Output shape of image resize layer, the shape is (out_w, ) when input is a 3-D Tensor, the shape is (out_h, out_w) when input is a 4-D Tensor and is (out_d, out_h, out_w) when input is a 5-D Tensor. Default: None. If a list, each element can be an integer or a Tensor Variable of shape: [1]. If a Tensor Variable, its dimensions size should be a 1. scale(float|Variable|None): The multiplier for the input height or width. At least one of :attr:`out_shape` or :attr:`scale` must be set. And :attr:`out_shape` has a higher priority than :attr:`scale`. Default: None. name(str|None): A name for this layer(optional). If set None, the layer will be named automatically. resample(str): The resample method. It supports 'LINEAR', 'BICUBIC', 'BILINEAR', 'TRILINEAR' and 'NEAREST' currently. Default: 'BILINEAR' actual_shape(Variable): An optional input to specify output shape dynamically. If provided, image resize according to this given shape rather than :attr:`out_shape` and :attr:`scale` specifying shape. That is to say actual_shape has the highest priority. It is recommended to use :attr:`out_shape` if you want to specify output shape dynamically, because :attr:`actual_shape` will be deprecated. When using actual_shape to specify output shape, one of :attr:`out_shape` and :attr:`scale` should also be set, otherwise errors would be occurred in graph constructing stage. Default: None align_corners(bool) : An optional bool, If True, the centers of the 4 corner pixels of the input and output tensors are aligned, preserving the values at the corner pixels. Default: True align_mode(int) : An optional for linear/bilinear/trilinear interpolation. Refer to the fomula in the the example code above, it can be \'0\' for src_idx = scale*(dst_indx+0.5)-0.5 , can be \'1\' for src_idx = scale*dst_index. data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`, `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. Returns: A 3-D Tensor of the shape (num_batches, channels, out_w) or (num_batches, out_w, channels), A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels), or 5-D Tensor of the shape (num_batches, channels, out_d, out_h, out_w) or (num_batches, out_d, out_h, out_w, channels). Raises: TypeError: out_shape should be a list or tuple or Variable. TypeError: actual_shape should either be Variable or None. ValueError: The 'resample' of image_resize can only be 'LINEAR', 'BILINEAR', 'TRILINEAR', 'BICUBIC' or 'NEAREST' currently. ValueError: 'LINEAR' only support 3-D tensor. ValueError: 'BICUBIC', 'BILINEAR' and 'NEAREST' only support 4-D tensor. ValueError: 'TRILINEAR' only support 5-D tensor. ValueError: One of out_shape and scale must not be None. ValueError: out_shape length should be 1 for input 3-D tensor. ValueError: out_shape length should be 2 for input 4-D tensor. ValueError: out_shape length should be 3 for input 5-D tensor. ValueError: scale should be greater than zero. TypeError: align_corners should be a bool value ValueError: align_mode can only be '0' or '1' ValueError: data_format can only be 'NCW', 'NWC', 'NCHW', 'NHWC', 'NCDHW' or 'NDHWC'. Examples: .. code-block:: python #declarative mode import paddle import paddle.fluid as fluid import numpy as np paddle.enable_static() input = fluid.data(name="input", shape=[None,3,6,10]) #1 output = fluid.layers.image_resize(input=input,out_shape=[12,12]) #2 #x = np.array([2]).astype("int32") #dim1 = fluid.data(name="dim1", shape=[1], dtype="int32") #fluid.layers.assign(input=x, output=dim1) #output = fluid.layers.image_resize(input=input,out_shape=[12,dim1]) #3 #x = np.array([3,12]).astype("int32") #shape_tensor = fluid.data(name="shape_tensor", shape=[2], dtype="int32") #fluid.layers.assign(input=x, output=shape_tensor) #output = fluid.layers.image_resize(input=input,out_shape=shape_tensor) #4 #x = np.array([0.5]).astype("float32") #scale_tensor = fluid.data(name="scale", shape=[1], dtype="float32") #fluid.layers.assign(x,scale_tensor) #output = fluid.layers.image_resize(input=input,scale=scale_tensor) place = fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) input_data = np.random.rand(2,3,6,10).astype("float32") output_data = exe.run(fluid.default_main_program(), feed={"input":input_data}, fetch_list=[output], return_numpy=True) print(output_data[0].shape) #1 # (2, 3, 12, 12) #2 # (2, 3, 12, 2) #3 # (2, 3, 3, 12) #4 # (2, 3, 3, 5) #imperative mode import paddle.fluid.dygraph as dg with dg.guard(place) as g: input = dg.to_variable(input_data) output = fluid.layers.image_resize(input=input, out_shape=[12,12]) print(output.shape) # [2L, 3L, 12L, 12L] """ resample_methods = { 'LINEAR': 'linear', 'BILINEAR': 'bilinear', 'TRILINEAR': 'trilinear', 'NEAREST': 'nearest', 'LINEAR': 'linear', } resample = resample.upper() if resample not in resample_methods: raise ValueError( "The 'resample' of image_resize can only be 'LINEAR', 'BILINEAR', 'TRILINEAR' " "or 'NEAREST' currently.") resample_type = resample_methods[resample] if resample == 'LINEAR' and len(input.shape) != 3: raise ValueError("'LINER only support 3-D tensor.") elif resample in ['BILINEAR', 'NEAREST'] and len(input.shape) != 4: raise ValueError("'BILINEAR' and 'NEAREST' only support 4-D tensor.") elif resample == 'TRILINEAR' and len(input.shape) != 5: raise ValueError("'TRILINEAR'only support 5-D tensor.") if not isinstance(align_corners, bool): raise TypeError("Attr align_corners should be a bool value") if align_mode != 0 and align_mode != 1: raise ValueError("align_mode can only be 0 or 1") if out_shape is None and scale is None: raise ValueError("One of out_shape and scale must not be None.") helper = LayerHelper('{}_interp'.format(resample_type), **locals()) dtype = helper.input_dtype() if len(input.shape) == 3 and data_format not in ['NCW', 'NWC']: raise ValueError( "Got wrong value for param `data_format`: " + data_format + " received but only `NCW` or `NWC` supported for 3-D input.") elif len(input.shape) == 4 and data_format not in ['NCHW', 'NHWC']: raise ValueError( "Got wrong value for param `data_format`: " + data_format + " received but only `NCHW` or `NHWC` supported for 4-D input.") elif len(input.shape) == 5 and data_format not in ['NCDHW', 'NDHWC']: raise ValueError( "Got wrong value for param `data_format`: " + data_format + " received but only `NCDHW` or `NDHWC` supported for 5-D input.") def _is_list_or_turple_(data): return (isinstance(data, list) or isinstance(data, tuple)) if data_format == 'NCHW' or data_format == 'NCDHW' or data_format == 'NCW': data_layout = 'NCHW' if data_format == 'NHWC' or data_format == 'NDHWC' or data_format == 'NWC': data_layout = 'NHWC' inputs = {"X": input} attrs = { "out_d": -1, "out_h": -1, "out_w": -1, "interp_method": resample_type, "align_corners": align_corners, "align_mode": align_mode, "data_layout": data_layout } if out_shape is not None: if isinstance(out_shape, Variable): out_shape.stop_gradient = True inputs['OutSize'] = out_shape else: if not (_is_list_or_turple_(out_shape)): raise TypeError( "out_shape should be a list or tuple or Variable.") # Validate the shape contain_var = False for dim_idx, dim_size in enumerate(out_shape): if isinstance(dim_size, Variable): contain_var = True continue assert dim_size > 0, ( "Each dimension size given in out_shape must be greater than 0." ) if contain_var: new_size_tensor = [] size_list = [] for dim in out_shape: if isinstance(dim, Variable): dim.stop_gradient = True new_size_tensor.append(dim) size_list.append(-1) else: assert (isinstance(dim, int)) temp_out = helper.create_variable_for_type_inference( 'int32') fill_constant( [1], 'int32', dim, force_cpu=True, out=temp_out) new_size_tensor.append(temp_out) size_list.append(dim) inputs['SizeTensor'] = new_size_tensor if len(input.shape) == 3: if len(out_shape) != 1: raise ValueError("out_shape length should be 1 for " "input 3-D tensor.") if contain_var: attrs['out_w'] = size_list[0] else: out_shape = list(map(int, out_shape)) attrs['out_w'] = out_shape[0] elif len(input.shape) == 4: if len(out_shape) != 2: raise ValueError("out_shape length should be 2 for " "input 4-D tensor.") if contain_var: attrs['out_h'] = size_list[0] attrs['out_w'] = size_list[1] else: out_shape = list(map(int, out_shape)) attrs['out_h'] = out_shape[0] attrs['out_w'] = out_shape[1] if len(input.shape) == 5: if len(out_shape) != 3: raise ValueError("out_shape length should be 3 for " "input 5-D tensor.") if contain_var: attrs['out_d'] = size_list[0] attrs['out_h'] = size_list[1] attrs['out_w'] = size_list[2] else: out_shape = list(map(int, out_shape)) attrs['out_d'] = out_shape[0] attrs['out_h'] = out_shape[1] attrs['out_w'] = out_shape[2] else: if isinstance(scale, Variable): scale.stop_gradient = True inputs["Scale"] = scale elif isinstance(scale, float) or isinstance(scale, int): if scale <= 0: raise ValueError("Attr(scale) should be greater than zero.") attrs['scale'] = float(scale) else: raise TypeError( "Attr(scale)'s type should be float, int or Variable.") if isinstance(actual_shape, Variable): warnings.warn( "actual_shape will be deprecated, it is recommended to use " "out_shape instead of actual_shape to specify output shape dynamically." ) actual_shape.stop_gradient = True inputs["OutSize"] = actual_shape elif actual_shape is not None: raise TypeError("actual_shape should either be Variable or None.") out = helper.create_variable_for_type_inference(dtype) helper.append_op( type='{}_interp'.format(resample_type), inputs=inputs, outputs={"Out": out}, attrs=attrs) return out @templatedoc(op_type="linear_interp") def resize_linear(input, out_shape=None, scale=None, name=None, actual_shape=None, align_corners=True, align_mode=1, data_format='NCW'): """ This op resizes the input by performing linear interpolation based on given output shape which specified by actual_shape, out_shape and scale in priority order. **Warning:** the parameter :attr:`actual_shape` will be deprecated in the future and only use :attr:`out_shape` instead. Align_corners and align_mode are optional parameters,the calculation method of interpolation can be selected by them. Example: .. code-block:: text For scale: if align_corners = True && out_size > 1 : scale_factor = (in_size-1.0)/(out_size-1.0) else: scale_factor = float(in_size/out_size) Linear interpolation: if: align_corners = False , align_mode = 0 input : (N,C,W_in) output: (N,C,W_out) where: W_out = (W_{in}+0.5) * scale_{factor} - 0.5 else: input : (N,C,W_in) output: (N,C,W_out) where: W_out = W_{in} * scale_{factor} Parameters: input(Variable): 3-D Tensor(NCW), its data type is float32, float64, or uint8, its data format is specified by :attr:`data_format`. out_shape(list|tuple|Variable|None): Output shape of resize linear layer, the shape is (out_w,). Default: None. If a list, each element can be an integer or a Tensor Variable with shape: [1]. If a Tensor Variable, its dimension size should be 1. scale(float|Variable|None): The multiplier for the input height or width. At least one of :attr:`out_shape` or :attr:`scale` must be set. And :attr:`out_shape` has a higher priority than :attr:`scale`. Default: None. actual_shape(Variable): An optional input to specify output shape dynamically. If provided, image resize according to this given shape rather than :attr:`out_shape` and :attr:`scale` specifying shape. That is to say actual_shape has the highest priority. It is recommended to use :attr:`out_shape` if you want to specify output shape dynamically, because :attr:`actual_shape` will be deprecated. When using actual_shape to specify output shape, one of :attr:`out_shape` and :attr:`scale` should also be set, otherwise errors would be occurred in graph constructing stage. Default: None align_corners(bool): ${align_corners_comment} align_mode(bool): ${align_mode_comment} data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCW"`, `"NWC"`. The default is `"NCW"`. When it is `"NCW"`, the data is stored in the order of: `[batch_size, input_channels, input_width]`. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Variable: 3-D tensor(NCW or NWC). Examples: .. code-block:: python #declarative mode import paddle.fluid as fluid import numpy as np input = fluid.data(name="input", shape=[None,3,100]) output = fluid.layers.resize_linear(input=input,out_shape=[50,]) place = fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) input_data = np.random.rand(1,3,100).astype("float32") output_data = exe.run(fluid.default_main_program(), feed={"input":input_data}, fetch_list=[output], return_numpy=True) print(output_data[0].shape) # (1, 3, 50) #imperative mode import paddle.fluid.dygraph as dg with dg.guard(place) as g: input = dg.to_variable(input_data) output = fluid.layers.resize_linear(input=input, out_shape=[50,]) print(output.shape) # [1L, 3L, 50L] """ return image_resize(input, out_shape, scale, name, 'LINEAR', actual_shape, align_corners, align_mode, data_format) @templatedoc(op_type="bilinear_interp") def resize_bilinear(input, out_shape=None, scale=None, name=None, actual_shape=None, align_corners=True, align_mode=1, data_format='NCHW'): """ This op resizes the input by performing bilinear interpolation based on given output shape which specified by actual_shape, out_shape and scale in priority order. **Warning:** the parameter :attr:`actual_shape` will be deprecated in the future and only use :attr:`out_shape` instead. Bilinear interpolation is an extension of linear interpolation for interpolating functions of two variables (e.g. H-direction and W-direction in this op) on a rectilinear 2D grid. The key idea is to perform linear interpolation first in one direction, and then again in the other direction. For details of bilinear interpolation, please refer to Wikipedia: https://en.wikipedia.org/wiki/Bilinear_interpolation Align_corners and align_mode are optional parameters,the calculation method of interpolation can be selected by them. Example: .. code-block:: text For scale: if align_corners = True && out_size > 1 : scale_factor = (in_size-1.0)/(out_size-1.0) else: scale_factor = float(in_size/out_size) Bilinear interpolation: if: align_corners = False , align_mode = 0 input : (N,C,H_in,W_in) output: (N,C,H_out,W_out) where: H_out = (H_{in}+0.5) * scale_{factor} - 0.5 W_out = (W_{in}+0.5) * scale_{factor} - 0.5 else: input : (N,C,H_in,W_in) output: (N,C,H_out,W_out) where: H_out = H_{in} * scale_{factor} W_out = W_{in} * scale_{factor} Parameters: input(Variable): 4-D Tensor(NCHW), its data type is float32, float64, or uint8, its data format is specified by :attr:`data_format`. out_shape(list|tuple|Variable|None): Output shape of resize bilinear layer, the shape is (out_h, out_w).Default: None. If a list, each element can be an integer or a Tensor Variable with shape: [1]. If a Tensor Variable, its dimension size should be 1. scale(float|Variable|None): The multiplier for the input height or width. At least one of :attr:`out_shape` or :attr:`scale` must be set. And :attr:`out_shape` has a higher priority than :attr:`scale`. Default: None. actual_shape(Variable): An optional input to specify output shape dynamically. If provided, image resize according to this given shape rather than :attr:`out_shape` and :attr:`scale` specifying shape. That is to say actual_shape has the highest priority. It is recommended to use :attr:`out_shape` if you want to specify output shape dynamically, because :attr:`actual_shape` will be deprecated. When using actual_shape to specify output shape, one of :attr:`out_shape` and :attr:`scale` should also be set, otherwise errors would be occurred in graph constructing stage. Default: None align_corners(bool): ${align_corners_comment} align_mode(bool): ${align_mode_comment} data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Variable: 4-D tensor(NCHW or NHWC). Examples: .. code-block:: python #declarative mode import paddle.fluid as fluid import numpy as np import paddle paddle.enable_static() input = fluid.data(name="input", shape=[None,3,6,10]) #1 output = fluid.layers.resize_bilinear(input=input,out_shape=[12,12]) #2 #x = np.array([2]).astype("int32") #dim1 = fluid.data(name="dim1", shape=[1], dtype="int32") #fluid.layers.assign(input=x, output=dim1) #output = fluid.layers.resize_bilinear(input=input,out_shape=[12,dim1]) #3 #x = np.array([3,12]).astype("int32") #shape_tensor = fluid.data(name="shape_tensor", shape=[2], dtype="int32") #fluid.layers.assign(input=x, output=shape_tensor) #output = fluid.layers.resize_bilinear(input=input,out_shape=shape_tensor) #4 #x = np.array([0.5]).astype("float32") #scale_tensor = fluid.data(name="scale", shape=[1], dtype="float32") #fluid.layers.assign(x,scale_tensor) #output = fluid.layers.resize_bilinear(input=input,scale=scale_tensor) place = fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) input_data = np.random.rand(2,3,6,10).astype("float32") output_data = exe.run(fluid.default_main_program(), feed={"input":input_data}, fetch_list=[output], return_numpy=True) print(output_data[0].shape) #1 # (2, 3, 12, 12) #2 # (2, 3, 12, 2) #3 # (2, 3, 3, 12) #4 # (2, 3, 3, 5) #imperative mode import paddle.fluid.dygraph as dg with dg.guard(place) as g: input = dg.to_variable(input_data) output = fluid.layers.resize_bilinear(input=input, out_shape=[12,12]) print(output.shape) # [2L, 3L, 12L, 12L] """ return image_resize(input, out_shape, scale, name, 'BILINEAR', actual_shape, align_corners, align_mode, data_format) @templatedoc(op_type="trilinear_interp") def resize_trilinear(input, out_shape=None, scale=None, name=None, actual_shape=None, align_corners=True, align_mode=1, data_format='NCDHW'): """ This op resizes the input by performing trilinear interpolation based on given output shape which specified by actual_shape, out_shape and scale in priority order. **Warning:** the parameter :attr:`actual_shape` will be deprecated in the future and only use :attr:`out_shape` instead. Trilinear interpolation is an extension of linear interpolation for interpolating functions of three variables (e.g. D-direction, H-direction and W-direction in this op) on a rectilinear 3D grid. The linear interpolation is performed on three directions. For details of trilinear interpolation, please refer to Wikipedia: https://en.wikipedia.org/wiki/Trilinear_interpolation Align_corners and align_mode are optional parameters,the calculation method of interpolation can be selected by them. Example: .. code-block:: text For scale: if align_corners = True && out_size > 1 : scale_factor = (in_size-1.0)/(out_size-1.0) else: scale_factor = float(in_size/out_size) Bilinear interpolation: if: align_corners = False , align_mode = 0 input : (N,C,D_in,H_in,W_in) output: (N,C,D_out,H_out,W_out) where: D_out = (D_{in}+0.5) * scale_{factor} - 0.5 H_out = (H_{in}+0.5) * scale_{factor} - 0.5 W_out = (W_{in}+0.5) * scale_{factor} - 0.5 else: input : (N,C,D_in,H_in,W_in) output: (N,C,D_out,H_out,W_out) where: D_out = D_{in} * scale_{factor} H_out = H_{in} * scale_{factor} W_out = W_{in} * scale_{factor} Parameters: input(${x_type}): 5-D Tensor, its data type is float32, float64, or uint8, its data format is specified by :attr:`data_format`. out_shape(list|tuple|Variable|None): The output shape of resized tensor, the shape is (out_d, out_h, out_w). Default: None. Every element should be an integer or a Tensor Variable with shape: [1] if it is a list. If it is a Tensor Variable, its dimension size should be 1. scale(float|Variable|None): The multiplier for the input depth, height or width. At least one of :attr:`out_shape` or :attr:`scale` must be set. And :attr:`out_shape` has a higher priority than :attr:`scale`. Default: None. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` actual_shape(Variable): An optional input to specify output shape dynamically. If provided, image resize according to this given shape rather than :attr:`out_shape` and :attr:`scale` specifying shape. That is to say actual_shape has the highest priority. It is recommended to use :attr:`out_shape` if you want to specify output shape dynamically, because :attr:`actual_shape` will be deprecated. When using actual_shape to specify output shape, one of :attr:`out_shape` and :attr:`scale` should also be set, otherwise errors would be occurred in graph constructing stage. Default: None align_corners(bool): ${align_corners_comment} align_mode(bool): ${align_mode_comment} data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCDHW"`, `"NDHWC"`. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. Returns: Variable: A 5-D Tensor(NCDHW or NDHWC) Examples: .. code-block:: python #declarative mode import paddle.fluid as fluid import paddle import numpy as np paddle.enable_static() input = fluid.data(name="input", shape=[None,3,6,8,10]) #1 output = fluid.layers.resize_trilinear(input=input,out_shape=[12,12,12]) #2 #x = np.array([2]).astype("int32") #dim1 = fluid.data(name="dim1", shape=[1], dtype="int32") #fluid.layers.assign(input=x, output=dim1) #output = fluid.layers.resize_trilinear(input=input,out_shape=[12,dim1,4]) #3 #x = np.array([3,12,12]).astype("int32") #shape_tensor = fluid.data(name="shape_tensor", shape=[3], dtype="int32") #fluid.layers.assign(input=x, output=shape_tensor) #output = fluid.layers.resize_trilinear(input=input,out_shape=shape_tensor) #4 #x = np.array([0.5]).astype("float32") #scale_tensor = fluid.data(name="scale", shape=[1], dtype="float32") #fluid.layers.assign(x,scale_tensor) #output = fluid.layers.resize_trilinear(input=input,scale=scale_tensor) place = fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) input_data = np.random.rand(2,3,6,8,10).astype("float32") output_data = exe.run(fluid.default_main_program(), feed={"input":input_data}, fetch_list=[output], return_numpy=True) print(output_data[0].shape) #1 # (2, 3, 12, 12, 12) #2 # (2, 3, 12, 2, 4) #3 # (2, 3, 3, 12, 12) #4 # (2, 3, 3, 4, 5) #imperative mode import paddle.fluid.dygraph as dg with dg.guard(place) as g: input = dg.to_variable(input_data) output = fluid.layers.resize_trilinear(input=input, out_shape=[12,12,12]) print(output.shape) # [2L, 3L, 12L, 12L, 12L] """ return image_resize(input, out_shape, scale, name, 'TRILINEAR', actual_shape, align_corners, align_mode, data_format) @templatedoc(op_type="nearest_interp") def resize_nearest(input, out_shape=None, scale=None, name=None, actual_shape=None, align_corners=True, data_format='NCHW'): """ This op resizes the input by performing nearest neighbor interpolation in both the height direction and the width direction based on given output shape which is specified by actual_shape, out_shape and scale in priority order. **Warning:** the parameter :attr:`actual_shape` will be deprecated in the future and only use :attr:`out_shape` instead. Example: .. code-block:: text For scale: if align_corners = True && out_size > 1 : scale_factor = (in_size-1.0)/(out_size-1.0) else: scale_factor = float(in_size/out_size) Nearest neighbor interpolation: if: align_corners = False input : (N,C,H_in,W_in) output: (N,C,H_out,W_out) where: H_out = floor(H_{in} * scale_{factor}) W_out = floor(W_{in} * scale_{factor}) else: align_corners = True input : (N,C,H_in,W_in) output: (N,C,H_out,W_out) where: H_out = round(H_{in} * scale_{factor}) W_out = round(W_{in} * scale_{factor}) For details of nearest neighbor interpolation, please refer to Wikipedia: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation Parameters: input(${x_type}): 4-D Tensor, its data type is float32, float64, or uint8, its data format is specified by :attr:`data_format`. out_shape(list|tuple|Variable|None): The output shape of resized tensor, the shape is (out_h, out_w). Default: None. Every element should be an integer or a tensor Variable with shape: [1] if it is a list. If it is a tensor Variable, its dimension size should be 1. scale(float|Variable|None): The multiplier for the input height or width. At least one of :attr:`out_shape` or :attr:`scale` must be set. And :attr:`out_shape` has a higher priority than :attr:`scale`. Default: None. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` actual_shape(Variable): An optional input to specify output shape dynamically. If provided, image resize according to this given shape rather than :attr:`out_shape` and :attr:`scale` specifying shape. That is to say actual_shape has the highest priority. It is recommended to use :attr:`out_shape` if you want to specify output shape dynamically, because :attr:`actual_shape` will be deprecated. When using actual_shape to specify output shape, one of :attr:`out_shape` and :attr:`scale` should also be set, otherwise errors would be occurred in graph constructing stage. Default: None align_corners(bool): ${align_corners_comment} data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. Returns: Variable: 4-D tensor(NCHW or NHWC). Examples: .. code-block:: python #declarative mode import paddle.fluid as fluid import numpy as np import paddle paddle.enable_static() input = fluid.data(name="input", shape=[None,3,6,10]) #1 output = fluid.layers.resize_nearest(input=input,out_shape=[12,12]) #2 #x = np.array([2]).astype("int32") #dim1 = fluid.data(name="dim1", shape=[1], dtype="int32") #fluid.layers.assign(input=x, output=dim1) #output = fluid.layers.resize_nearest(input=input,out_shape=[12,dim1]) #3 #x = np.array([3,12]).astype("int32") #shape_tensor = fluid.data(name="shape_tensor", shape=[2], dtype="int32") #fluid.layers.assign(input=x, output=shape_tensor) #output = fluid.layers.resize_nearest(input=input,out_shape=shape_tensor) #4 #x = np.array([0.5]).astype("float32") #scale_tensor = fluid.data(name="scale", shape=[1], dtype="float32") #fluid.layers.assign(x,scale_tensor) #output = fluid.layers.resize_nearest(input=input,scale=scale_tensor) place = fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) input_data = np.random.rand(2,3,6,10).astype("float32") output_data = exe.run(fluid.default_main_program(), feed={"input":input_data}, fetch_list=[output], return_numpy=True) print(output_data[0].shape) #1 # (2, 3, 12, 12) #2 # (2, 3, 12, 2) #3 # (2, 3, 3, 12) #4 # (2, 3, 3, 5) #imperative mode import paddle.fluid.dygraph as dg with dg.guard(place) as g: input = dg.to_variable(input_data) output = fluid.layers.resize_nearest(input=input, out_shape=[12,12]) print(output.shape) # [2L, 3L, 12L, 12L] """ return image_resize( input, out_shape, scale, name, 'NEAREST', actual_shape, align_corners, align_mode=1, data_format=data_format) def image_resize_short(input, out_short_len, resample='BILINEAR'): """ This op resizes a batch of images. The short edge of input images will be resized to the given 'out_short_len'. The long edge of input images will be resized proportionately to make images' length-width ratio constant. Parameters: input (Variable): 4-D tensor(NCHW), The input tensor of image resize layer. out_short_len(int): The length of output images' short edge. resample (str): resample method, default: BILINEAR. Returns: Variable: 4-D tensor(NCHW). Examples: .. code-block:: python import paddle.fluid as fluid input = fluid.data(name="input", shape=[None,3,6,9], dtype="float32") out = fluid.layers.image_resize_short(input, out_short_len=3) """ in_shape = input.shape if len(in_shape) != 4: raise ValueError( "The rank of input must be 4 (num_batches, channels, in_h, in_w).") hw = in_shape[2:4] short_idx = hw.index(min(hw)) long_idx = 1 - short_idx out_shape = list(hw) out_shape[short_idx] = out_short_len out_shape[long_idx] = int( float(out_shape[long_idx]) * (float(out_short_len) / float(hw[ short_idx])) + 0.5) return image_resize(input=input, out_shape=out_shape, resample=resample) @deprecated(since="2.0.0", update_to="paddle.gather") def gather(input, index, overwrite=True): """ Output is obtained by gathering entries of the outer-most dimension of X indexed by `index` and concatenate them together. .. math:: Out = X[Index] .. code-block:: text Given: X = [[1, 2], [3, 4], [5, 6]] Index = [1, 2] Then: Out = [[3, 4], [5, 6]] Args: input (Tensor): The source input tensor with rank>=1. Supported data type is int32, int64, float32, float64 and uint8 (only for CPU), float16 (only for GPU). index (Tensor): The index input tensor with rank=1. Data type is int32 or int64. overwrite (bool, optional): The mode that updating the grad when has same index. If True, use the overwrite mode to update the grad of the same index, if False, use the accumulate mode to update the grad of the same index. Default value is True. Returns: output (Tensor): The output is a tensor with the same rank as input. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() x = fluid.data(name='x', shape=[-1, 5], dtype='float32') index = fluid.data(name='index', shape=[-1, 1], dtype='int32') output = fluid.layers.gather(x, index) """ if in_dygraph_mode(): return _C_ops.gather(input, index, None, 'overwrite', overwrite) check_variable_and_dtype( input, 'x', ['float16', 'float32', 'float64', 'int32', 'int64', 'uint8'], 'gather') check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'gather') helper = LayerHelper('gather', **locals()) dtype = helper.input_dtype() out = helper.create_variable_for_type_inference(dtype) helper.append_op( type="gather", inputs={"X": input, "Index": index}, outputs={"Out": out}, attrs={'overwrite': overwrite}) return out @deprecated(since="2.0.0", update_to="paddle.gather_nd") def gather_nd(input, index, name=None): """ **Gather Nd Layer** This function is actually a high-dimensional extension of :code:`gather` and supports for simultaneous indexing by multiple axes. :attr:`index` is a K-dimensional integer tensor, which is regarded as a (K-1)-dimensional tensor of :attr:`index` into :attr:`input`, where each element defines a slice of params: .. math:: output[(i_0, ..., i_{K-2})] = input[index[(i_0, ..., i_{K-2})]] Obviously, :code:`index.shape[-1] <= input.rank` . And, the output tensor has shape :code:`index.shape[:-1] + input.shape[index.shape[-1]:]` . .. code-block:: text Given: input = [[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]] input.shape = (2, 3, 4) * Case 1: index = [[1]] gather_nd(input, index) = [input[1, :, :]] = [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]] * Case 2: index = [[0,2]] gather_nd(input, index) = [input[0, 2, :]] = [8, 9, 10, 11] * Case 3: index = [[1, 2, 3]] gather_nd(input, index) = [input[1, 2, 3]] = [23] Args: input (Tensor): The input Tensor which it's data type should be bool, float32, float64, int32, int64. index (Tensor): The index input with rank > 1, index.shape[-1] <= input.rank. Its dtype should be int32, int64. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: output (Tensor): A tensor with the shape index.shape[:-1] + input.shape[index.shape[-1]:] Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() x = fluid.data(name='x', shape=[3, 4, 5], dtype='float32') index = fluid.data(name='index', shape=[2, 2], dtype='int32') output = fluid.layers.gather_nd(x, index) """ if in_dygraph_mode(): return _C_ops.gather_nd(input, index) check_variable_and_dtype(input, 'input', ['bool', 'float32', 'float64', 'int32', 'int64'], 'gather_np') check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'gather_np') helper = LayerHelper('gather_nd', **locals()) dtype = helper.input_dtype() output = helper.create_variable_for_type_inference(dtype) helper.append_op( type="gather_nd", inputs={"X": input, "Index": index}, outputs={"Out": output}) return output @deprecated(since="2.0.0", update_to="paddle.scatter") def scatter(input, index, updates, name=None, overwrite=True): """ :alias_main: paddle.scatter :alias: paddle.scatter,paddle.tensor.scatter,paddle.tensor.manipulation.scatter :old_api: paddle.fluid.layers.scatter **Scatter Layer** Output is obtained by updating the input on selected indices based on updates. .. code-block:: python import numpy as np #input: input = np.array([[1, 1], [2, 2], [3, 3]]) index = np.array([2, 1, 0, 1]) # shape of updates should be the same as input # shape of updates with dim > 1 should be the same as input updates = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) overwrite = False # calculation: if not overwrite: for i in range(len(index)): input[index[i]] = np.zeros((2)) for i in range(len(index)): if (overwrite): input[index[i]] = updates[i] else: input[index[i]] += updates[i] # output: out = np.array([[3, 3], [6, 6], [1, 1]]) out.shape # [3, 2] Args: input (Variable): The input N-D Tensor with rank>=1. Data type can be float32. index (Variable): The index 1-D Tensor. Data type can be int32, int64. The length of index cannot exceed updates's length, and the value in index cannot exceed input's length. updates (Variable): update input with updates parameter based on index. shape should be the same as input, and dim value with dim > 1 should be the same as input. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . overwrite (bool): The mode that updating the output when there are same indices. If True, use the overwrite mode to update the output of the same index, if False, use the accumulate mode to update the output of the same index. Default value is True. Returns: Variable(Tensor|LoDTensor): The output is a Tensor with the same shape as input. Examples: .. code-block:: python import paddle import numpy as np import paddle.fluid as fluid paddle.enable_static() input = fluid.layers.data(name='data', shape=[3, 2], dtype='float32', append_batch_size=False) index = fluid.layers.data(name='index', shape=[4], dtype='int64', append_batch_size=False) updates = fluid.layers.data(name='update', shape=[4, 2], dtype='float32', append_batch_size=False) output = fluid.layers.scatter(input, index, updates, overwrite=False) exe = fluid.Executor(fluid.CPUPlace()) exe.run(fluid.default_startup_program()) in_data = np.array([[1, 1], [2, 2], [3, 3]]).astype(np.float32) index_data = np.array([2, 1, 0, 1]).astype(np.int64) update_data = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]).astype(np.float32) res = exe.run(fluid.default_main_program(), feed={'data':in_data, "index":index_data, "update":update_data}, fetch_list=[output]) print(res) # [array([[3., 3.], # [6., 6.], # [1., 1.]], dtype=float32)] """ helper = LayerHelper('scatter', **locals()) dtype = helper.input_dtype() out = helper.create_variable_for_type_inference(dtype) helper.append_op( type="scatter", inputs={"X": input, "Ids": index, "Updates": updates}, attrs={'overwrite': overwrite}, outputs={"Out": out}) return out def scatter_nd_add(ref, index, updates, name=None): r""" **Scatter_nd_add Layer** Output is obtained by applying sparse addition to a single value or slice in a Variable. :attr:`ref` is a Tensor with rank :math:`R` and :attr:`index` is a Tensor with rank :math:`K` . Thus, :attr:`index` has shape :math:`[i_0, i_1, ..., i_{K-2}, Q]` where :math:`Q \leq R` . :attr:`updates` is a Tensor with rank :math:`K - 1 + R - Q` and its shape is :math:`index.shape[:-1] + ref.shape[index.shape[-1]:]` . According to the :math:`[i_0, i_1, ..., i_{K-2}]` of :attr:`index` , add the corresponding :attr:`updates` slice to the :attr:`ref` slice which is obtained by the last one dimension of :attr:`index` . .. code-block:: text Given: * Case 1: ref = [0, 1, 2, 3, 4, 5] index = [[1], [2], [3], [1]] updates = [9, 10, 11, 12] we get: output = [0, 22, 12, 14, 4, 5] * Case 2: ref = [[65, 17], [-14, -25]] index = [[], []] updates = [[[-1, -2], [1, 2]], [[3, 4], [-3, -4]]] ref.shape = (2, 2) index.shape = (2, 0) updates.shape = (2, 2, 2) we get: output = [[67, 19], [-16, -27]] Args: ref (Variable): The ref input. Its dtype should be int32, int64, float32, float64. index (Variable): The index input with rank > 1 and index.shape[-1] <= ref.rank. Its dtype should be int32 or int64 as it is used as indexes. updates (Variable): The updated value of scatter_nd_add op, and it must have the same dtype as ref. It must have the shape index.shape[:-1] + ref.shape[index.shape[-1]:]. name (str|None): The output variable name. If set None, the layer will be named automatically. Returns: output (Variable): The output is a tensor with the same shape and dtype as ref. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() ref = fluid.data(name='ref', shape=[3, 5, 9, 10], dtype='float32') index = fluid.data(name='index', shape=[3, 2], dtype='int32') updates = fluid.data(name='update', shape=[3, 9, 10], dtype='float32') output = fluid.layers.scatter_nd_add(ref, index, updates) """ if in_dygraph_mode(): op = getattr(_C_ops, 'scatter_nd_add') return op(ref, index, updates) if ref.dtype != updates.dtype: raise ValueError("ref and updates must have same data type.") helper = LayerHelper('scatter_nd_add', **locals()) dtype = helper.input_dtype(input_param_name='ref') output = helper.create_variable_for_type_inference(dtype) helper.append_op( type="scatter_nd_add", inputs={"X": ref, "Index": index, "Updates": updates}, outputs={"Out": output}) return output def scatter_nd(index, updates, shape, name=None): """ **Scatter_nd Layer** Output is obtained by scattering the :attr:`updates` in a new tensor according to :attr:`index` . This op is similar to :code:`scatter_nd_add`, except the tensor of :attr:`shape` is zero-initialized. Correspondingly, :code:`scatter_nd(index, updates, shape)` is equal to :code:`scatter_nd_add(paddle.zeros(shape, updates.dtype), index, updates)` . If :attr:`index` has repeated elements, then the corresponding updates are accumulated. Because of the numerical approximation issues, the different order of repeated elements in :attr:`index` may cause different results. The specific calculation method can be seen :code:`scatter_nd_add` . This op is the inverse of the :code:`gather_nd` op. Args: index (Tensor): The index input with ndim > 1 and index.shape[-1] <= len(shape). Its dtype should be int32 or int64 as it is used as indexes. updates (Tensor): The updated value of scatter_nd op. Its dtype should be float32, float64. It must have the shape index.shape[:-1] + shape[index.shape[-1]:] shape(tuple|list): Shape of output tensor. name (str|None): The output Tensor name. If set None, the layer will be named automatically. Returns: output (Tensor): The output is a tensor with the same type as :attr:`updates` . Examples: .. code-block:: python import paddle import numpy as np index_data = np.array([[1, 1], [0, 1], [1, 3]]).astype(np.int64) index = paddle.to_tensor(index_data) updates = paddle.rand(shape=[3, 9, 10], dtype='float32') shape = [3, 5, 9, 10] output = paddle.scatter_nd(index, updates, shape) """ return scatter_nd_add(zeros(shape, updates.dtype), index, updates, name) @templatedoc() def random_crop(x, shape, seed=None): """ ${comment} Args: x(${x_type}): ${x_comment} shape(${shape_type}): ${shape_comment} seed(int|${seed_type}|None): ${seed_comment} By default, the seed will get from `random.randint(-65536, 65535)`. Returns: ${out_comment} Examples: .. code-block:: python import paddle.fluid as fluid img = fluid.data("img", [None, 3, 256, 256]) # cropped_img is [-1, 3, 224, 224] cropped_img = fluid.layers.random_crop(img, shape=[3, 224, 224]) # cropped_img2 shape: [-1, 2, 224, 224] # cropped_img2 = fluid.layers.random_crop(img, shape=[2, 224, 224]) # cropped_img3 shape: [-1, 3, 128, 224] # cropped_img3 = fluid.layers.random_crop(img, shape=[128, 224]) """ helper = LayerHelper("random_crop", **locals()) check_variable_and_dtype(x, 'x', ['float32', 'float64', 'uint8', 'int16', 'int32'], 'random_crop') check_type(shape, 'shape', (list, Variable), 'random_crop') dtype = x.dtype out = helper.create_variable_for_type_inference(dtype) if seed is None: seed = np.random.randint(-65536, 65536) op_attrs = {"shape": shape} if isinstance(seed, int): op_attrs["startup_seed"] = seed seed = helper.create_variable( name=unique_name.generate("random_crop_seed"), dtype="int64", persistable=True) elif not isinstance(seed, Variable): raise ValueError("'seed' must be a Variable or an int.") helper.append_op( type="random_crop", inputs={"X": x, "Seed": seed}, outputs={"Out": out, "SeedOut": seed}, attrs=op_attrs) return out def log(x, name=None): r""" Calculates the natural log of the given input tensor, element-wise. .. math:: Out = \\ln(x) Args: x (Tensor): Input Tensor. Must be one of the following types: float32, float64. name (str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: The natural log of the input Tensor computed element-wise. Examples: .. code-block:: python import paddle x = [[2,3,4], [7,8,9]] x = paddle.to_tensor(x, dtype='float32') res = paddle.log(x) # [[0.693147, 1.09861, 1.38629], [1.94591, 2.07944, 2.19722]] """ if in_dygraph_mode(): return _C_ops.log(x) check_variable_and_dtype(x, 'x', ['float32', 'float64'], "log") inputs = {'X': [x]} helper = LayerHelper('log', **locals()) dtype = helper.input_dtype(input_param_name='x') out = helper.create_variable_for_type_inference(dtype) helper.append_op(type="log", inputs={"X": x}, outputs={"Out": out}) return out @deprecated(since="2.0.0", update_to="paddle.nn.functional.relu") def relu(x, name=None): """ ${comment} Args: x(Variable): ${x_comment} name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Variable: ${out_comment} Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np in1 = np.array([[-1,0],[1,2.6]]) with fluid.dygraph.guard(): x1 = fluid.dygraph.to_variable(in1) out1 = fluid.layers.relu(x1) print(out1.numpy()) # [[0. 0. ] # [1. 2.6]] """ if in_dygraph_mode(): return _C_ops.relu(x) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'relu') inputs = {'X': [x]} helper = LayerHelper('relu', **locals()) dtype = helper.input_dtype(input_param_name='x') out = helper.create_variable_for_type_inference(dtype) helper.append_op( type="relu", inputs={"X": helper.input('x')}, outputs={"Out": out}) return out @deprecated(since="2.0.0", update_to="paddle.nn.functional.selu") def selu(x, scale=None, alpha=None, name=None): r""" Selu Operator. The equation is: .. math:: selu= \\lambda* \\begin{cases} x &\\quad \\text{ if } x>0 \n \\alpha * e^x - \\alpha &\\quad \\text{ if } x<=0 \\end{cases} The input `X` can carry the LoD (Level of Details) information, or not. And the output shares the LoD information with input `X`. Args: x (Variable): The input N-D Tensor. scale(float, optional): lambda in selu activation function, the default value is 1.0507009873554804934193349852946. For more information about this value, please refer to: https://arxiv.org/abs/1706.02515. alpha(float, optional): alpha in selu activation function, the default value is 1.6732632423543772848170429916717. For more information about this value, please refer to: https://arxiv.org/abs/1706.02515. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Variable(Tensor|LoDTensor): The output Tensor or LoDTensor with the same shape and LoD information as input. Examples: .. code-block:: python import paddle import paddle.fluid as fluid import numpy as np paddle.enable_static() inputs = fluid.layers.data(name="x", shape=[2, 2], dtype="float32") output = fluid.layers.selu(inputs) exe = fluid.Executor(fluid.CPUPlace()) exe.run(fluid.default_startup_program()) img = np.array([[0, 1],[2, 3]]).astype(np.float32) res = exe.run(fluid.default_main_program(), feed={'x':img}, fetch_list=[output]) print(res) # [array([[0. , 1.050701],[2.101402, 3.152103]], dtype=float32)] """ check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'selu') helper = LayerHelper('selu', **locals()) dtype = helper.input_dtype(input_param_name='x') out = helper.create_variable_for_type_inference(dtype) attrs = {} if scale is not None: attrs["scale"] = scale if alpha is not None: attrs["alpha"] = alpha helper.append_op( type="selu", inputs={"X": x}, outputs={"Out": out}, attrs=attrs) return out def mean_iou(input, label, num_classes): r""" Mean Intersection-Over-Union is a common evaluation metric for semantic image segmentation, which first computes the IOU for each semantic class and then computes the average over classes. IOU is defined as follows: .. math:: IOU = \\frac{true\_positive}{(true\_positive + false\_positive + false\_negative)}. The predictions are accumulated in a confusion matrix and mean-IOU is then calculated from it. Parameters: input (Tensor): A n-D Tensor of prediction results for semantic labels with type int32 or int64. label (Tensor): A Tensor of ground truth labels with type int32 or int64. Its shape should be the same as input. num_classes (int32): The possible number of labels. Returns: Three Tensors. - mean_iou(Tensor) : A 1-D Tensor representing the mean intersection-over-union with shape [1]. \ Data type is float32. - out_wrong(Tensor) : A 1-D Tensor with shape [num_classes]. Data type is int32. \ The wrong numbers of each class. - out_correct(Tensor): A 1-D Tensor with shape [num_classes]. Data type is int32. The correct numbers of each class. Examples: .. code-block:: python import paddle iou_shape = [64, 32, 32] num_classes = 5 predict = paddle.randint(low=0, high=255, shape=iou_shape, dtype='int64') label = paddle.randint(low=0, high=255, shape=iou_shape, dtype='int64') mean_iou, out_wrong, out_correct = paddle.metric.mean_iou(predict, label, num_classes) """ if in_dygraph_mode(): return _C_ops.mean_iou(input, label, 'num_classes', num_classes) helper = LayerHelper('mean_iou', **locals()) check_variable_and_dtype(input, 'Predictions', ['int32', 'int64'], 'mean_iou') check_variable_and_dtype(label, 'Labels', ['int32', 'int64'], 'mean_iou') out_mean_iou = helper.create_variable_for_type_inference(dtype='float32') out_wrong = helper.create_variable_for_type_inference(dtype='int32') out_correct = helper.create_variable_for_type_inference(dtype='int32') helper.append_op( type="mean_iou", inputs={"Predictions": input, "Labels": label}, outputs={ "OutMeanIou": out_mean_iou, "OutWrong": out_wrong, "OutCorrect": out_correct }, attrs={"num_classes": num_classes}) return out_mean_iou, out_wrong, out_correct def crop(x, shape=None, offsets=None, name=None): """ Crop input into output, as specified by offsets and shape. **Warning:** THIS OP IS DEPRECATED. It will be removed in the future version. Instructions for updating: Use :ref:`api_fluid_layers_crop_tensor` instead. .. code-block:: text * Case 1: Given X = [[0, 1, 2, 0, 0] [0, 3, 4, 0, 0] [0, 0, 0, 0, 0]], and shape = [2, 2], offsets = [0, 1], output is: Out = [[1, 2], [3, 4]]. * Case 2: Given X = [[0, 1, 2, 5, 0] [0, 3, 4, 6, 0] [0, 0, 0, 0, 0]], and shape is tensor shape = [[0, 0, 0] [0, 0, 0]] and offsets = [0, 1], output is: Out = [[1, 2, 5], [3, 4, 6]]. Parameters: x (Variable): Tensor, data type can be float32 or float64. shape (Variable|list/tuple of integers): The output shape is specified by `shape`, which can be a Tensor or a list/tuple of integers. If it is a Tensor, it's rank must be the same as `x` , only it's shape will be used, and the value of it will be ignored. This way is suitable for the case that the output shape may be changed each iteration. If it is a list/tuple of integers, it's length must be the same as the rank of `x` offsets (Variable|list/tuple of integers|None): Specifies the cropping offsets at each dimension. It can be a Tensor or a list/tuple of integers. If it is a Tensor, it's rank must be the same as `x`. This way is suitable for the case that the offsets may be changed each iteration. If it is a list/tuple of integers, it's length must be the same as the rank of `x`. If None, the offsets are 0 at each dimension. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name` . Usually name is no need to set and None by default. Returns: The cropped Tensor, which has the same rank and data type with `x` Return Type: Variable Raises: ValueError: If shape is not a list, tuple or Variable. Examples: .. code-block:: python import paddle.fluid as fluid import paddle.fluid as fluid import paddle paddle.enable_static() x = fluid.data(name="x", shape=[3, 3, 5], dtype="float32") y = fluid.data(name="y", shape=[2, 2, 3], dtype="float32") crop = fluid.layers.crop(x, shape=y) # or z = fluid.data(name="z", shape=[3, 3, 5], dtype="float32") crop = fluid.layers.crop(z, shape=[2, 2, 3]) """ check_variable_and_dtype(x, 'x', ['float32'], 'crop') check_type(shape, 'shape', (list, tuple, Variable), 'crop') helper = LayerHelper('crop', **locals()) if offsets is None: offsets = [0] * len(x.shape) out = helper.create_variable_for_type_inference(x.dtype) ipts = {'X': x} attrs = {} if isinstance(shape, Variable): ipts['Y'] = shape else: attrs['shape'] = shape if isinstance(offsets, Variable): ipts['Offsets'] = offsets else: attrs['offsets'] = offsets helper.append_op( type='crop', inputs=ipts, outputs={'Out': out}, attrs=None if len(attrs) == 0 else attrs) return out def crop_tensor(x, shape=None, offsets=None, name=None): """ Crop input into output, as specified by offsets and shape. .. code-block:: text * Case 1 (input is a 2-D Tensor): Input: X.shape = [3, 5] X.data = [[0, 1, 2, 0, 0], [0, 3, 4, 0, 0], [0, 0, 0, 0, 0]] Parameters: shape = [2, 2] offsets = [0, 1] Output: Out.shape = [2, 2] Out.data = [[1, 2], [3, 4]] * Case 2 (input is a 3-D Tensor): Input: X.shape = [2, 3, 4] X.data = [[[0, 1, 2, 3], [0, 5, 6, 7], [0, 0, 0, 0]], [[0, 3, 4, 5], [0, 6, 7, 8], [0, 0, 0, 0]]] Parameters: shape = [2, 2, -1] offsets = [0, 0, 1] Output: Out.shape = [2, 2, 3] Out.data = [[[1, 2, 3], [5, 6, 7]], [[3, 4, 5], [6, 7, 8]]] Parameters: x (Tensor): 1-D to 6-D Tensor, the data type is float32, float64, int32 or int64. shape (list|tuple|Tensor): The output shape is specified by `shape`. Its data type is int32. If a list/tuple, it's length must be the same as the dimension size of `x`. If a Tensor, it should be a 1-D Tensor. When it is a list, each element can be an integer or a Tensor of shape: [1]. If Variable contained, it is suitable for the case that the shape may be changed each iteration. offsets (list|tuple|Variable, optional): Specifies the cropping offsets at each dimension. Its data type is int32. If a list/tuple, it's length must be the same as the dimension size of `x`. If a Tensor, it should be a 1-D Tensor. When it is a list, each element can be an integer or a Tensor of shape: [1]. If Variable contained, it is suitable for the case that the offsets may be changed each iteration. Default: None, the offsets are 0 at each dimension. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Tensor: The cropped Tensor has same data type with `x`. Examples: .. code-block:: python :name: code-example1 import paddle x = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # x.shape = [3, 3] # x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # shape can be a 1-D Tensor or list or tuple. shape = paddle.to_tensor([2, 2], dtype='int32') # shape = [2, 2] # shape = (2, 2) out = paddle.crop(x, shape) # out.shape = [2, 2] # out = [[1,2], [4,5]] # offsets can be a 1-D Tensor or list or tuple. offsets = paddle.to_tensor([0, 1], dtype='int32') # offsets = [1, 0] # offsets = (1, 1) out = paddle.crop(x, shape, offsets) # out.shape = [2, 2] # if offsets = [0, 0], out = [[1,2], [4,5]] # if offsets = [0, 1], out = [[2,3], [5,6]] # if offsets = [1, 0], out = [[4,5], [7,8]] # if offsets = [1, 1], out = [[5,6], [8,9]] """ helper = LayerHelper('crop_tensor', **locals()) check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], 'crop_tensor') check_type(shape, 'shape', (list, tuple, Variable), 'crop_tensor') check_type(offsets, 'offsets', (list, tuple, Variable, type(None)), 'crop_tensor') if offsets is None: offsets = [0] * len(x.shape) out = helper.create_variable_for_type_inference(x.dtype) ipts = {'X': x} attrs = {} def _attr_shape_check(shape_val): if not isinstance(shape_val, int): raise TypeError( "Attr(shape)'s dtype of Op(crop_tensor) should be int32, but received: %s." % type(shape_val)) if shape_val == 0: raise ValueError( "Attr(shape) of Op(crop_tensor) should not be zero, but received: %s." % str(shape_val)) if shape_val < -1: raise ValueError( "When the element in Attr(shape) of Op(crop_tensor) is negative, only -1 is supported, but received: %s." % str(shape_val)) def _attr_offsets_check(offset_val): if not isinstance(offset_val, int): raise TypeError( "Attr(offsets)'s dtype of Op(crop_tensor) should be int32, but received: %s." % type(offset_val)) if offset_val < 0: raise ValueError( "Attr(offsets) of Op(crop_tensor) should be greater or equal to zero, but received: %s." % str(offset_val)) if isinstance(offsets, Variable): offsets.stop_gradient = True ipts['Offsets'] = offsets attrs['offsets'] = [-1] * len(x.shape) elif utils._contain_var(offsets): new_offsets_tensor = [] offsets_attr = [] for dim in offsets: if isinstance(dim, Variable): dim.stop_gradient = True new_offsets_tensor.append(dim) offsets_attr.append(-1) else: _attr_offsets_check(dim) temp_out = helper.create_variable_for_type_inference('int32') fill_constant([1], 'int32', dim, force_cpu=True, out=temp_out) new_offsets_tensor.append(temp_out) offsets_attr.append(dim) ipts['OffsetsTensor'] = new_offsets_tensor attrs['offsets'] = offsets_attr else: for offset in offsets: _attr_offsets_check(offset) attrs['offsets'] = offsets if isinstance(shape, Variable): shape.stop_gradient = True ipts['Shape'] = shape elif utils._contain_var(shape): new_shape_tensor = [] shape_attr = [] for dim_size in shape: if isinstance(dim_size, Variable): dim_size.stop_gradient = True new_shape_tensor.append(dim_size) shape_attr.append(0) else: _attr_shape_check(dim_size) temp_out = helper.create_variable_for_type_inference('int32') fill_constant( [1], 'int32', dim_size, force_cpu=True, out=temp_out) new_shape_tensor.append(temp_out) shape_attr.append(dim_size) ipts['ShapeTensor'] = new_shape_tensor attrs['shape'] = shape_attr else: for dim_size in shape: _attr_shape_check(dim_size) attrs['shape'] = shape helper.append_op( type='crop_tensor', inputs=ipts, outputs={'Out': out}, attrs=None if len(attrs) == 0 else attrs) return out def affine_grid(theta, out_shape, name=None): """ :alias_main: paddle.nn.functional.affine_grid :alias: paddle.nn.functional.affine_grid,paddle.nn.functional.vision.affine_grid :old_api: paddle.fluid.layers.affine_grid It generates a grid of (x,y) coordinates using the parameters of the affine transformation that correspond to a set of points where the input feature map should be sampled to produce the transformed output feature map. Args: theta (Variable) - A Tensor with shape [N, 2, 3]. It contains a batch of affine transform parameters. The data type can be float32 or float64. out_shape (Variable | list | tuple): The shape of target output with format [batch_size, channel, height, width]. ``out_shape`` can be a Tensor or a list or tuple. The data type must be int32. name(str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Variable: A Tensor with shape [batch_size, H, W, 2] while 'H' and 'W' are the height and width of feature map in affine transformation. The data type is the same as `theta`. Raises: ValueError: If the type of arguments is not supported. Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np place = fluid.CPUPlace() theta = fluid.data(name="x", shape=[None, 2, 3], dtype="float32") out_shape = fluid.data(name="y", shape=[4], dtype="int32") grid_0 = fluid.layers.affine_grid(theta, out_shape) grid_1 = fluid.layers.affine_grid(theta, [5, 3, 28, 28]) batch_size=2 exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) output= exe.run(feed={"x": np.random.rand(batch_size,2,3).astype("float32"), "y": np.array([5, 3, 28, 28]).astype("int32")}, fetch_list=[grid_0.name, grid_1.name]) print(output[0]) print(output[1]) """ helper = LayerHelper('affine_grid') check_variable_and_dtype(theta, 'theta', ['float32', 'float64'], 'affine_grid') if not (isinstance(out_shape, list) or isinstance(out_shape, tuple) or \ isinstance(out_shape, Variable)): raise ValueError("The out_shape should be a list, tuple or Variable.") if not isinstance(theta, Variable): raise ValueError("The theta should be a Variable.") out = helper.create_variable_for_type_inference(theta.dtype) ipts = {'Theta': theta} attrs = {} if isinstance(out_shape, Variable): ipts['OutputShape'] = out_shape check_variable_and_dtype(out_shape, 'out_shape', ['int32'], 'affine_grid') else: attrs['output_shape'] = out_shape if core.is_compiled_with_rocm(): # ROCM platform do not have MIOPEN kernel for affine_grid attrs['use_cudnn'] = False helper.append_op( type='affine_grid', inputs=ipts, outputs={'Output': out}, attrs=None if len(attrs) == 0 else attrs) return out def pad2d(input, paddings=[0, 0, 0, 0], mode='constant', pad_value=0.0, data_format="NCHW", name=None): """ Pad 2-d images according to 'paddings' and 'mode'. If mode is 'reflect', paddings[0] and paddings[1] must be no greater than height-1. And the width dimension has the same condition. Parameters: input (Tensor): The input image with [N, C, H, W] format or [N, H, W, C] format, which is a 4-D Tensor with data type float32. paddings (Tensor | List[int32]): The padding size. If padding is a List, it must contain four integers, (padding_top, padding_bottom, padding_left, padding_right). Otherwise, it is a 1-D Tensor with shape [4]. Data type is int32. Default is [0, 0, 0, 0]. mode (str): Three modes: 'constant' (default), 'reflect', 'edge' . When in 'constant' mode, this op uses a constant value to pad the input tensor. When in 'reflect' mode, uses reflection of the input boundaries to pad the input tensor. When in 'edge' mode, uses input boundaries to pad the input tensor. Default is 'constant' pad_value (float32): The value to fill the padded areas in 'constant' mode . Default is 0.0 data_format (str): An string from: "NHWC", "NCHW". Specify the data format of the input data. Default is "NCHW" name (str, optional) : The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Tensor, a 4-D Tensor padded according to paddings and mode and data type is same as input. Examples: .. code-block:: text Input = [[[[1., 2., 3.], [4., 5., 6.]]]] Case 0: paddings = [0, 1, 2, 3], mode = 'constant' pad_value = 0 Out = [[[[0., 0., 1., 2., 3., 0., 0., 0.], [0., 0., 4., 5., 6., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0.]]]] Case 1: paddings = [0, 1, 2, 1], mode = 'reflect' Out = [[[[3., 2., 1., 2., 3., 2.], [6., 5., 4., 5., 6., 5.], [3., 2., 1., 2., 3., 2.]]]] Case 2: paddings = [0, 1, 2, 1], mode = 'edge' Out = [[[[1., 1., 1., 2., 3., 3.], [4., 4., 4., 5., 6., 6.], [4., 4., 4., 5., 6., 6.]]]] Code Examples: .. code-block:: python import numpy as np import paddle import paddle.nn.functional as F # example 1 x_shape = (1, 1, 3, 4) x = np.arange(np.prod(x_shape), dtype=np.float32).reshape(x_shape) + 1 tensor_x = paddle.to_tensor(x) y = paddle.fluid.layers.pad2d(tensor_x, paddings=[1, 2, 2, 1], pad_value=1, mode='constant') print(y.numpy()) # [[[[ 1. 1. 1. 1. 1. 1. 1.] # [ 1. 1. 1. 2. 3. 4. 1.] # [ 1. 1. 5. 6. 7. 8. 1.] # [ 1. 1. 9. 10. 11. 12. 1.] # [ 1. 1. 1. 1. 1. 1. 1.] # [ 1. 1. 1. 1. 1. 1. 1.]]]] # example 2 x_shape = (1, 1, 2, 3) x = np.arange(np.prod(x_shape), dtype=np.float32).reshape(x_shape) + 1 tensor_x = paddle.to_tensor(x) y = paddle.fluid.layers.pad2d(tensor_x, paddings=[1, 1, 1, 1], mode='reflect') print(y.numpy()) # [[[[5. 4. 5. 6. 5.] # [2. 1. 2. 3. 2.] # [5. 4. 5. 6. 5.] # [2. 1. 2. 3. 2.]]]] """ if in_dygraph_mode(): _paddings = paddings.numpy().tolist() if isinstance( paddings, Variable) else paddings return _C_ops.pad2d(input, 'mode', mode, 'pad_value', pad_value, 'data_format', data_format, 'paddings', _paddings) check_variable_and_dtype( input, 'input', ['float16', 'float32', 'float64', 'int32', 'int64'], "pad2d") attrs = {'mode': mode, 'pad_value': pad_value, 'data_format': data_format} inputs = {'X': [input]} if isinstance(paddings, Variable): inputs['Paddings'] = [paddings] attrs['paddings'] = [] else: attrs['paddings'] = paddings helper = LayerHelper('pad2d', **locals()) assert mode in ['reflect', 'edge', 'constant' ], "mode should be one of constant, reflect, edge." dtype = helper.input_dtype(input_param_name='input') out = helper.create_variable_for_type_inference(dtype) helper.append_op( type='pad2d', inputs=inputs, outputs={"Out": out}, attrs=attrs) return out @deprecated(since="2.0.0", update_to="paddle.nn.functional.elu") def elu(x, alpha=1.0, name=None): """ :alias_main: paddle.nn.functional.elu :alias: paddle.nn.functional.elu,paddle.nn.functional.activation.elu :old_api: paddle.fluid.layers.elu ${comment} Args: x(${x_type}): ${x_comment} alpha(${alpha_type}|1.0): ${alpha_comment} name(str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: ${out_type}: ${out_comment} Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np input_elu = np.array([[-1,6],[1,15.6]]) with fluid.dygraph.guard(): x = fluid.dygraph.to_variable(input_elu) y = fluid.layers.elu(x, alpha=0.2) print(y.numpy()) # [[-0.12642411 6. ] # [ 1. 15.6 ]] """ helper = LayerHelper('elu', **locals()) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'elu') out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='elu', inputs={'X': x}, outputs={'Out': out}, attrs={'alpha': alpha}) return out @deprecated(since="2.0.0", update_to="paddle.nn.functional.relu6") def relu6(x, threshold=6.0, name=None): """ ${comment} Args: x(${x_type}): ${x_comment} threshold(float, optional): ${threshold_comment} name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: output(${out_type}): ${out_comment} Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np in1 = np.array([[-1,0],[2.5,7.8]]) with fluid.dygraph.guard(): x1 = fluid.dygraph.to_variable(in1) out1 = fluid.layers.relu6(x=x1, threshold=6.0) print(out1.numpy()) # [[0. 0. ] # [2.5 6. ]] """ check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'relu6') helper = LayerHelper('relu6', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='relu6', inputs={'X': x}, outputs={'Out': out}, attrs={ 'threshold': threshold, 'use_mkldnn': _global_flags()["FLAGS_use_mkldnn"] }) return out @templatedoc() def pow(x, factor=1.0, name=None): """ This is Pow Activation Operator. :math:`out = x^{factor}` Args: x(Variable): A ``Tensor`` or ``LoDTensor`` . The data type is ``float32`` or ``float64``. factor(float32|Variable, optional): A scalar with type ``float32`` or a ``Tensor`` with shape [1] and type ``float32``. The exponential factor of Pow. Default 1.0. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Variable: A ``Tensor`` or ``LoDTensor``. The data type is same as ``x``. Examples: .. code-block:: python import paddle.fluid as fluid x = fluid.data(name="x", shape=[32,32], dtype="float32") # example 1: argument factor is float y_1 = fluid.layers.pow(x, factor=2.0) # y_1 is x^{2.0} # example 2: argument factor is Variable factor_tensor = fluid.layers.fill_constant([1], "float32", 3.0) y_2 = fluid.layers.pow(x, factor=factor_tensor) # y_2 is x^{3.0} """ check_variable_and_dtype( x, 'x', ['int32', 'int64', 'float16', 'float32', 'float64'], 'pow') helper = LayerHelper('pow', **locals()) inputs = {'X': x} attrs = {} if isinstance(factor, Variable): check_variable_and_dtype(factor, 'factor', ['float32'], 'pow') factor.stop_gradient = True inputs['FactorTensor'] = factor else: attrs['factor'] = factor out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='pow', inputs=inputs, outputs={'Out': out}, attrs=attrs) return out @templatedoc() def stanh(x, scale_a=0.67, scale_b=1.7159, name=None): """ stanh activation. .. math:: out = b * \\frac{e^{a * x} - e^{-a * x}}{e^{a * x} + e^{-a * x}} Parameters: x (Tensor): The input Tensor with data type float32, float64. scale_a (float, optional): The scale factor a of the input. Default is 0.67. scale_b (float, optional): The scale factor b of the output. Default is 1.7159. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: A Tensor with the same data type and shape as ``x`` . Examples: .. code-block:: python import paddle x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0]) out = paddle.stanh(x, scale_a=0.67, scale_b=1.72) # [1.00616539, 1.49927628, 1.65933108, 1.70390463] """ if in_dygraph_mode(): return _C_ops.stanh(x, 'scale_a', scale_a, 'scale_b', scale_b) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'stanh') helper = LayerHelper('stanh', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='stanh', inputs={'X': x}, outputs={'Out': out}, attrs={'scale_a': scale_a, 'scale_b': scale_b}) return out @templatedoc() def hard_sigmoid(x, slope=0.2, offset=0.5, name=None): """ ${comment} Parameters: x (${x_type}): ${x_comment} slope (float, optional): ${slope_comment} offset (float, optional): ${offset_comment} name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: ${out_type}: ${out_comment} Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() data = fluid.layers.fill_constant(shape=[3, 2], value=0.5, dtype='float32') # [[0.5, 0.5], [0.5, 0.5], [0.5, 0.5]] result = fluid.layers.hard_sigmoid(data) # [[0.6, 0.6], [0.6, 0.6], [0.6, 0.6]] """ if in_dygraph_mode(): return _C_ops.hard_sigmoid(x, 'slope', slope, 'offset', offset) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'hard_sigmoid') helper = LayerHelper('hard_sigmoid', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='hard_sigmoid', inputs={'X': x}, outputs={'Out': out}, attrs={'slope': slope, 'offset': offset}) return out @templatedoc() def swish(x, beta=1.0, name=None): r""" :alias_main: paddle.nn.functional.swish :alias: paddle.nn.functional.swish,paddle.nn.functional.activation.swish :old_api: paddle.fluid.layers.swish Elementwise swish activation function. See `Searching for Activation Functions <https://arxiv.org/abs/1710.05941>`_ for more details. Equation: .. math:: out = \\frac{x}{1 + e^{- beta * x}} Args: x(Variable): Tensor or LoDTensor, dtype: float32 or float64, the input of swish activation. beta(float): Constant beta of swish operator, default 1.0. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Variable: Output of the swish activation, Tensor or LoDTensor, with the same dtype and shape with the input x. Examples: .. code-block:: python # declarative mode import numpy as np from paddle import fluid x = fluid.data(name="x", shape=(-1, 3), dtype="float32") y = fluid.layers.swish(x, beta=2.0) place = fluid.CPUPlace() exe = fluid.Executor(place) start = fluid.default_startup_program() main = fluid.default_main_program() data = np.random.randn(2, 3).astype("float32") exe.run(start) y_np, = exe.run(main, feed={"x": data}, fetch_list=[y]) data # array([[-1.1239197 , 1.3391294 , 0.03921051], # [ 1.1970421 , 0.02440812, 1.2055548 ]], dtype=float32) y_np # array([[-0.2756806 , 1.0610548 , 0.01998957], # [ 0.9193261 , 0.01235299, 0.9276883 ]], dtype=float32) .. code-block:: python # imperative mode import numpy as np from paddle import fluid import paddle.fluid.dygraph as dg data = np.random.randn(2, 3).astype("float32") place = fluid.CPUPlace() with dg.guard(place) as g: x = dg.to_variable(data) y = fluid.layers.swish(x) y_np = y.numpy() data # array([[-0.0816701 , 1.1603649 , -0.88325626], # [ 0.7522361 , 1.0978601 , 0.12987892]], dtype=float32) y_np # array([[-0.03916847, 0.8835007 , -0.25835553], # [ 0.51126915, 0.82324016, 0.06915068]], dtype=float32) """ check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'swish') helper = LayerHelper('swish', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='swish', inputs={'X': x}, outputs={'Out': out}, attrs={'slope': beta}) return out @deprecated(since="2.0.0", update_to="paddle.static.nn.prelu") def prelu(x, mode, param_attr=None, data_format="NCHW", name=None): r""" prelu activation. .. math:: prelu(x) = max(0, x) + \alpha * min(0, x) There are three modes for the activation: .. code-block:: text all: All elements share same alpha. channel: Elements in same channel share same alpha. element: All elements do not share alpha. Each element has its own alpha. Parameters: x (Tensor): The input Tensor or LoDTensor with data type float32. mode (str): The mode for weight sharing. param_attr (ParamAttr|None, optional): The parameter attribute for the learnable \ weight (alpha), it can be create by ParamAttr. None by default. \ For detailed information, please refer to :ref:`api_fluid_ParamAttr`. name (str, optional): Name for the operation (optional, default is None). \ For more information, please refer to :ref:`api_guide_Name`. data_format(str, optional): Data format that specifies the layout of input. It may be "NC", "NCL", "NCHW", "NCDHW", "NLC", "NHWC" or "NDHWC". Default: "NCHW". Returns: Tensor: A tensor with the same shape and data type as x. Examples: .. code-block:: python import paddle x = paddle.to_tensor([-1., 2., 3.]) param = paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(0.2)) out = paddle.static.nn.prelu(x, 'all', param) # [-0.2, 2., 3.] """ check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'prelu') helper = LayerHelper('prelu', **locals()) if mode not in ['all', 'channel', 'element']: raise ValueError('mode should be one of all, channel, element.') alpha_shape = [1] if mode == 'channel': true_data_format = [ 'NC', 'NCL', 'NCHW', 'NCDHW', 'NLC', 'NHWC', 'NDHWC' ] if data_format not in true_data_format: raise ValueError( "data_format must be one of 'NC', 'NCL', 'NCHW', 'NCDHW', " "'NLC', 'NHWC', 'NDHWC' but receive {}".format(data_format)) data_format = 'NCHW' if data_format[1] == 'C' else 'NHWC' assert len( x.shape ) >= 2, "The size of input shape should be equal or larger than 2 in prelu() when mode is 'channel'" #NOTE(zhiqiu): The alpha_shape should be [1, channel] + [1] * len(x.shape[2:]). # To be consistent with Prelu, it is simplified. #NOTE(zhiqiu): Revert shape to [1, channel, 1, 1] for compatibility with saved model of old version. #NOTE(GuoxiaWang): support NHWC data format if data_format == 'NHWC': alpha_shape = [1, 1, 1, x.shape[1]] else: alpha_shape = [1, x.shape[1], 1, 1] elif mode == 'element': assert len( x.shape ) >= 1, "The size of input shape should be equal or larger than 1 in prelu() when mode is 'element'" alpha_shape = [1] + list(x.shape)[1:] dtype = helper.input_dtype(input_param_name='x') alpha = helper.create_parameter( attr=helper.param_attr, shape=alpha_shape, dtype=dtype, is_bias=False, default_initializer=Constant(0.25)) out = helper.create_variable_for_type_inference(dtype) helper.append_op( type="prelu", inputs={"X": x, 'Alpha': alpha}, attrs={"mode": mode, "data_format": data_format}, outputs={"Out": out}) return out @templatedoc() def brelu(x, t_min=0.0, t_max=24.0, name=None): """ ${comment} Args: x(${x_type}): ${x_comment} t_min(${t_min_type}|0.0): ${t_min_comment} t_max(${t_max_type}|24.0): ${t_max_comment} name(str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: ${out_type}: ${out_comment} Examples: .. code-block:: python import paddle.fluid as fluid import paddle import numpy as np paddle.enable_static() input_brelu = np.array([[-1,6],[1,15.6]]) with fluid.dygraph.guard(): x = fluid.dygraph.to_variable(input_brelu) y = fluid.layers.brelu(x, t_min=1.0, t_max=10.0) print(y.numpy()) #[[ 1. 6.] #[ 1. 10.]] """ if in_dygraph_mode(): return _C_ops.brelu(x, 't_min', t_min, 't_max', t_max) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'brelu') helper = LayerHelper('brelu', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='brelu', inputs={'X': x}, outputs={'Out': out}, attrs={'t_min': t_min, 't_max': t_max}) return out @deprecated(since="2.0.0", update_to="paddle.nn.functional.leaky_relu") @templatedoc() def leaky_relu(x, alpha=0.02, name=None): """ ${comment} Args: x(${x_type}): ${x_comment} alpha(${alpha_type}|0.02): ${alpha_comment} name(str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: output(${out_type}): ${out_comment} Examples: .. code-block:: python import paddle x = paddle.to_tensor([[-1, 2], [3, -4]], dtype='float32') y = paddle.fluid.layers.leaky_relu(x, alpha=0.1) print(y) # [[-0.1, 2], [3, -0.4]] """ return paddle.nn.functional.leaky_relu(x, alpha, name) def soft_relu(x, threshold=40.0, name=None): r""" SoftRelu Activation Operator. $out = \ln(1 + \exp(\max(\min(x, threshold), -threshold)))$ Args: x(Variable): Input of soft_relu operator. Data type can be float32, float64. threshold(float, optional): The threshold value of soft_relu, default value being 40.0. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Variable(Tensor|LoDTensor)): Output of soft_relu operator, shape and LoD same as input. Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import numpy as np import paddle paddle.enable_static() inputs = fluid.layers.data(name="x", shape=[2, 2], dtype="float32") output = fluid.layers.soft_relu(inputs, threshold=20.0) exe = fluid.Executor(fluid.CPUPlace()) exe.run(fluid.default_startup_program()) img = np.array([[0, 1],[2, 3]]).astype(np.float32) res = exe.run(fluid.default_main_program(), feed={'x':img}, fetch_list=[output]) print(res) # [array([[0.6931472, 1.3132616], [2.126928 , 3.0485873]], dtype=float32)] """ check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'soft_relu') helper = LayerHelper('soft_relu', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='soft_relu', inputs={'X': x}, outputs={'Out': out}, attrs={'threshold': threshold}) return out def flatten(x, axis=1, name=None): r""" **Flatten op** Flatten the input tensor into a 2D matrix. For Example: .. code-block:: text Case 1: Given X.shape = (3, 100, 100, 4) and axis = 2 We get: Out.shape = (3 * 100, 4 * 100) Case 2: Given X.shape = (3, 100, 100, 4) and axis = 0 We get: Out.shape = (1, 3 * 100 * 100 * 4) Args: x (Variable): A tensor of rank >= axis. A tensor with type float32, float64, int8, int32, int64, uint8. axis (int): Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [0, R], where R is the rank of the input tensor. Default: 1. name(str, Optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. Returns: Variable: A 2D tensor with the contents of the input tensor, with input \ dimensions up to axis flattened to the outer dimension of \ the output and remaining input dimensions flattened into the \ inner dimension of the output. A Tensor with type same as input x. Raises: ValueError: If x is not a variable. ValueError: If axis is not in range [0, rank(x)]. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() x = fluid.data(name="x", shape=[4, 4, 3], dtype="float32") # x shape is [4, 4, 3] out = fluid.layers.flatten(x=x, axis=2) # out shape is [16, 3] """ check_variable_and_dtype( x, 'x', ['float32', 'float64', 'int8', 'int32', 'int64', 'uint8'], 'flatten') helper = LayerHelper('flatten', **locals()) if not (isinstance(x, Variable)): raise ValueError("The input x should be a Variable") if not (isinstance(axis, int)) or axis > len(x.shape) or axis < 0: raise ValueError("The axis should be a int, and in range [0, rank(x)]") out = helper.create_variable_for_type_inference(x.dtype) x_shape = helper.create_variable_for_type_inference(x.dtype) helper.append_op( type='flatten2', inputs={"X": x}, outputs={'Out': out, 'XShape': x_shape}, attrs={"axis": axis}) return out def stack(x, axis=0, name=None): """ This OP stacks all the inputs :code:`x` along axis. .. code-block:: text Case 1: Input: x[0].shape = [1, 2] x[0].data = [ [1.0 , 2.0 ] ] x[1].shape = [1, 2] x[1].data = [ [3.0 , 4.0 ] ] x[2].shape = [1, 2] x[2].data = [ [5.0 , 6.0 ] ] Attrs: axis = 0 Output: Out.dims = [3, 1, 2] Out.data =[ [ [1.0, 2.0] ], [ [3.0, 4.0] ], [ [5.0, 6.0] ] ] Case 2: Input: x[0].shape = [1, 2] x[0].data = [ [1.0 , 2.0 ] ] x[1].shape = [1, 2] x[1].data = [ [3.0 , 4.0 ] ] x[2].shape = [1, 2] x[2].data = [ [5.0 , 6.0 ] ] Attrs: axis = 1 or axis = -2 Output: Out.shape = [1, 3, 2] Out.data =[ [ [1.0, 2.0] [3.0, 4.0] [5.0, 6.0] ] ] Args: x (list(Variable)|tuple(Variable)): Input :code:`x` can be a :code:`list` or :code:`tuple` of Tensors, the shapes of all these Tensors must be the same. Supposing input is N dims Tensors :math:`[d_0, d_1, ..., d_{n-1}]`, the output is N+1 dims Tensor :math:`[d_0, d_1, d_{axis-1}, len(x), d_{axis}, ..., d_{n-1}]`. Supported data types: float32, float64, int32, int64. axis (int, optional): The axis along which all inputs are stacked. ``axis`` range is ``[-(R+1), R+1)``, where ``R`` is the number of dimensions of the first input tensor ``x[0]``. If ``axis < 0``, ``axis = axis+R+1``. The default value of axis is 0. name (str, optional): Please refer to :ref:`api_guide_Name`, Default None. Returns: Variable: The stacked Tensor, has same data type with input Tensors. Output dim is :math:`rank(x[0])+1`. Examples: .. code-block:: python import paddle.fluid as fluid import paddle.fluid.layers as layers # set batch size=None x1 = fluid.data(name='x1', shape=[None, 1, 2], dtype='int32') x2 = fluid.data(name='x2', shape=[None, 1, 2], dtype='int32') # stack Tensor list data = layers.stack([x1,x2]) # stack according to axis 0, data.shape=[2, None, 1, 2] data = layers.stack([x1,x2], axis=1) # stack according to axis 1, data.shape=[None, 2, 1, 2] """ axis = 0 if axis is None else axis if in_dygraph_mode(): return _C_ops.stack(x, 'axis', axis) if not isinstance(x, list) and not isinstance(x, tuple): # NOTE:(zhiqiu) Only support Variable as input if the Variable is a LOD_TENSOR_ARRAY create by create_array, array_write, array_read, etc. # In that case, Variable is array of tensors indeed. if isinstance(x, Variable) and x.desc.type( ) == core.VarDesc.VarType.LOD_TENSOR_ARRAY: x = [x] else: raise TypeError("The type of '%s' in %s must be %s, but received %s" % ('x', 'stack', 'list[Tensor], tuple[Tensor] or TensorArray', type(x))) helper = LayerHelper('stack', **locals()) out = helper.create_variable_for_type_inference(x[0].dtype) if x[0].desc.type() == core.VarDesc.VarType.LOD_TENSOR_ARRAY: assert len(x) == 1, "If the elements of 'x' in stack are Variable(LoDTensorArray), " \ "number of the elements must be 1, but received %s." % len(x) out_index = helper.create_variable_for_type_inference(dtype="int32") for i in x: check_variable_and_dtype(i, 'x', \ ['float16', 'float32', 'float64', 'int32', 'int64'], 'stack') helper.append_op( type='tensor_array_to_tensor', inputs={'X': x[0]}, outputs={'Out': [out], 'OutIndex': [out_index]}, attrs={'axis': axis, 'use_stack': True}) else: helper.append_op( type='stack', inputs={'X': x}, outputs={'Y': out}, attrs={'axis': axis}) return out @templatedoc(op_type="filter_by_instag") def filter_by_instag(ins, ins_tag, filter_tag, is_lod, out_val_if_empty=0): """ **Filter By Instag Layer** This function filter a batch of ins by instag, There are multiple ins, and every ins belongs to some tags. We can specify some tags we want. So the ins which belongs to that tags remains in the output, and others removed. For example, one batch has 4 ins. Every ins has its tag list. | Ins | Ins_Tag | |:-----:|:------:| | 0 | 0, 1 | | 1 | 1, 3 | | 2 | 0, 3 | | 3 | 2, 6 | And Lod is [1,1,1,1] And the filter tags [1] From the definition above, ins which has tag 1 can pass the filter So Ins 0 and Ins 1 can pass and be seen in the output, Ins 2 and 3 cannot pass because they do not has tag 1. Actually, if is_lod is false, it is normal tensor that equals to lod_tensor with all 1, similar to the example above. Args: ins (Variable): Input Variable (LoDTensor), usually it is 2D tensor And first dimension can have lod info or not. ins_tag (Variable): Input Variable (LoDTensor), usually it is 1D list And split them by lod info filter_tag (Variable): Input Variable (1D Tensor/List), usually it is list that holds the tags. is_lod (Bool): Boolean value to indicate ins is lod tensor or not. out_val_if_empty(Int64): If the output after filter is empty, this value will be set to Output tensor. Returns: Variable: filtered ins (LoDTensor) and loss weight (Tensor) Examples: .. code-block:: python import paddle.fluid.layers as layers ins = layers.data(name='Ins', shape=[-1,32], lod_level=0, dtype='float64') ins_tag = layers.data(name='Ins_tag', shape=[-1,16], lod_level=0, dtype='int64') filter_tag = layers.data(name='Filter_tag', shape=[-1,16], dtype='int64') out, loss_weight = layers.filter_by_instag(ins, ins_tag, filter_tag, True) """ helper = LayerHelper('filter_by_instag', **locals()) out = helper.create_variable_for_type_inference(dtype=ins.dtype) loss_weight = helper.create_variable_for_type_inference(dtype=np.float64) mmap = helper.create_variable_for_type_inference(dtype=ins_tag.dtype) helper.append_op( type='filter_by_instag', inputs={'Ins': ins, 'Ins_tag': ins_tag, 'Filter_tag': filter_tag}, outputs={'Out': out, 'LossWeight': loss_weight, 'IndexMap': mmap}, attrs={'is_lod': is_lod, 'out_val_if_empty': out_val_if_empty}) return [out, loss_weight] def unstack(x, axis=0, num=None): """ :alias_main: paddle.unstack :alias: paddle.unstack,paddle.tensor.unstack,paddle.tensor.manipulation.unstack :old_api: paddle.fluid.layers.unstack **UnStack Layer** This layer unstacks input Tensor :code:`x` into several Tensors along :code:`axis`. If :code:`axis` < 0, it would be replaced with :code:`axis+rank(x)`. If :code:`num` is None, it would be inferred from :code:`x.shape[axis]`, and if :code:`x.shape[axis]` <= 0 or is unknown, :code:`ValueError` is raised. Args: x (Tensor): Input Tensor. It is a N-D Tensors of data types float32, float64, int32, int64. axis (int): The axis along which the input is unstacked. num (int|None): The number of output variables. Returns: list(Tensor): The unstacked Tensors list. The list elements are N-D Tensors of data types float32, float64, int32, int64. Raises: ValueError: If x.shape[axis] <= 0 or axis is not in range [-D, D). Examples: .. code-block:: python import paddle x = paddle.ones(name='x', shape=[2, 3, 5], dtype='float32') # create a tensor with shape=[2, 3, 5] y = paddle.unstack(x, axis=1) # unstack with second axis, which results 3 tensors with shape=[2, 5] """ if in_dygraph_mode(): if num == None: num = x.shape[axis] if num == 0: return [] return _C_ops.unstack(x, num, 'axis', int(axis), 'num', num) helper = LayerHelper('unstack', **locals()) if num is None: if axis is None or x.shape[axis] <= 0: raise ValueError('unknown unstack number') else: num = x.shape[axis] outs = [] for _ in range(num): outs.append(helper.create_variable_for_type_inference(x.dtype)) helper.append_op( type='unstack', inputs={'X': [x]}, outputs={'Y': outs}, attrs={'axis': axis, 'num': num}) return outs @deprecated(since='2.0.0', update_to="paddle.expand") def expand(x, expand_times, name=None): """ :alias_main: paddle.expand :alias: paddle.expand,paddle.tensor.expand,paddle.tensor.manipulation.expand :old_api: paddle.fluid.layers.expand This operation tiles ``x`` multiple times according to the parameter ``expand_times``. The times number for each dimension of ``x`` is set by the parameter ``expand_times``. The rank of ``x`` should be less than or equal to 6. Please note that size of ``expand_times`` must be the same with X's rank. Following is a using case: .. code-block:: text Input(X) is a 3-D tensor with shape [2, 3, 1]: [ [[1], [2], [3]], [[4], [5], [6]] ] Attr(expand_times): [1, 2, 2] Output(Out) is a 3-D tensor with shape [2, 6, 2]: [ [[1, 1], [2, 2], [3, 3], [1, 1], [2, 2], [3, 3]], [[4, 4], [5, 5], [6, 6], [4, 4], [5, 5], [6, 6]] ] Args: x (Variable): A ``Tensor`` or ``LoDTensor`` with dimension in [1, 6]. The data type is ``bool``, ``float32``, ``float64`` or ``int32`` . expand_times (list|tuple|Variable): The data type is ``int32`` . If ``expand_times`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``expand_times`` is an Variable, it should be an 1-D Tensor. Expand times number for each dimension of ``x`` . name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Variable: A ``Tensor`` or ``LoDTensor``. The data type is same as ``x``. After expanding, size of each dimension of output is equal to the size of the corresponding dimension of ``x`` multiplying the corresponding value given by ``expand_times`` . Raises: TypeError: The type of ``expand_times`` must be list, tuple or Variable. ValueError: The elements of ``expand_times`` cannot be negative. Examples: .. code-block:: python import paddle.fluid as fluid # example 1: data_1 = fluid.layers.fill_constant(shape=[2, 3, 1], dtype='int32', value=0) expanded_1 = fluid.layers.expand(data_1, expand_times=[1, 2, 2]) # the shape of expanded_1 is [2, 6, 2]. # example 2: data_2 = fluid.layers.fill_constant(shape=[12, 14], dtype="int32", value=3) expand_times = fluid.layers.fill_constant(shape=[2], dtype="int32", value=4) expanded_2 = fluid.layers.expand(data_2, expand_times=expand_times) # the shape of expanded_2 is [48, 56]. """ if in_dygraph_mode(): attrs = () expand_times_tensor = None if isinstance(expand_times, (list, tuple)): expand_times = [ item.numpy().item(0) if isinstance(item, Variable) else item for item in expand_times ] attrs += ('expand_times', expand_times) elif isinstance(expand_times, Variable): expand_times_tensor = expand_times expand_times_tensor.stop_gradient = True return _C_ops.expand(x, expand_times_tensor, *attrs) inputs = {"X": [x]} attrs = {} check_variable_and_dtype( x, 'x', ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], 'expand') check_type(expand_times, 'expand_times', (list, tuple, Variable), 'expand') if convert_dtype(x.dtype) == 'bool' and x.stop_gradient == True: raise ValueError( "expand op bool date type must set the stop_gradient to be False") helper = LayerHelper('expand', input=x, **locals()) def get_attr_expand_times(list_expand_times): attrs_expand_times = [] for idx, times in enumerate(list_expand_times): if isinstance(times, Variable): attrs_expand_times.append(-1) else: attrs_expand_times.append(times) assert times > 0, ( "Each element given in expand_times must not be negative.") return attrs_expand_times if isinstance(expand_times, Variable): expand_times.stop_gradient = True inputs['ExpandTimes'] = expand_times elif isinstance(expand_times, (list, tuple)): attrs['expand_times'] = get_attr_expand_times(expand_times) if utils._contain_var(expand_times): inputs['expand_times_tensor'] = utils._convert_to_tensor_list( expand_times) dtype = helper.input_dtype(input_param_name='x') out = helper.create_variable_for_type_inference(dtype) helper.append_op( type='expand', inputs=inputs, outputs={'Out': out}, attrs=attrs) return out @deprecated(since='2.0.0', update_to="paddle.expand_as") def expand_as(x, target_tensor, name=None): """ :alias_main: paddle.expand_as :alias: paddle.expand_as,paddle.tensor.expand_as,paddle.tensor.manipulation.expand_as :old_api: paddle.fluid.layers.expand_as expand_as operator tiles to the input by given expand tensor. You should set expand tensor for each dimension by providing tensor 'target_tensor'. The rank of X should be in [1, 6]. Please note that size of 'target_tensor' must be the same with X's rank. Following is a using case: .. code-block:: text Input(X) is a 3-D tensor with shape [2, 3, 1]: [ [[1], [2], [3]], [[4], [5], [6]] ] target_tensor's shape: [2, 6, 2] Output(Out) is a 3-D tensor with shape [2, 6, 2]: [ [[1, 1], [2, 2], [3, 3], [1, 1], [2, 2], [3, 3]], [[4, 4], [5, 5], [6, 6], [4, 4], [5, 5], [6, 6]] ] Args: x (Variable): A Tensor with dtype float64, float32, int32. A tensor with rank in [1, 6]. target_tensor (Variable): A Tensor with dtype float64, float32, int32. target_tensor for expanding to Input(X). Only use target_tensor'shape. Returns: Variable: A Tensor with dtype float64, float32, int32. After expanding, size of each dimension of Output(Out) is equal to the size of the corresponding dimension of target_tensor multiplying the corresponding value given by target_tensor. Examples: .. code-block:: python import paddle import paddle.fluid as fluid import numpy as np paddle.enable_static() data = fluid.layers.data(name="data", shape=[-1,10], dtype='float64') target_tensor = fluid.layers.data( name="target_tensor", shape=[-1,20], dtype='float64') result = fluid.layers.expand_as(x=data, target_tensor=target_tensor) use_cuda = False place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) x = np.random.rand(3,10) y = np.random.rand(3,20) output= exe.run(feed={"data":x,"target_tensor":y},fetch_list=[result.name]) print(output[0].shape) #(3,20) """ if in_dygraph_mode(): return _C_ops.expand_as(x, target_tensor) check_variable_and_dtype( x, 'x', ['float32', 'float64', 'int32', 'int64', 'bool'], 'expand_as') check_variable_and_dtype(target_tensor, 'target_tensor', ['float32', 'float64', 'int32', 'int64', 'bool'], 'expand_as') helper = LayerHelper('expand_as', input=x, **locals()) dtype = helper.input_dtype(input_param_name='x') out = helper.create_variable_for_type_inference(dtype) inputs = {'X': x, 'target_tensor': target_tensor} helper.append_op(type='expand_as', inputs=inputs, outputs={'Out': out}) return out from paddle.fluid.framework import convert_np_dtype_to_dtype_ @deprecated(since='1.8.0', update_to="paddle.uniform") @templatedoc() def uniform_random_batch_size_like(input, shape, dtype='float32', input_dim_idx=0, output_dim_idx=0, min=-1.0, max=1.0, seed=0): """ This OP initializes a variable with random values sampled from a uniform distribution in the range [min, max). The input_dim_idx used to get the input dimension value which will be used to resize the output dimension. .. code-block:: text *Case 1: Given: input =[[0.946741 , 0.1357001 , 0.38086128]] # input.shape=[1,3] shape=[2,4] result.shape[output_dim_idx] = input.shape[input_dim_idx], output_dim_idx = 0, input_dim_idx = 0, result.shape[0] = input.shape[0], then: result=[[ 0.3443427 , -0.23056602, 0.3477049 , 0.06139076]] # result.shape=[1,4] *Case 2: Given: input =[[0.946741 , 0.1357001 , 0.38086128]] # input.shape=[1,3] shape=[2,4] input_dim_idx=1 output_dim_idx=1 result.shape[output_dim_idx] = input.shape[input_dim_idx], output_dim_idx = 1, input_dim_idx = 1, result.shape[1] = input.shape[1], then: result=[[-0.23133647, -0.84195036, 0.21441269], [-0.08774924, 0.25605237, -0.09403259]] # result.shape=[2,3] Args: input (Variable): A Tensor. Supported data types: float32, float64. shape (tuple|list): A python list or python tuple. The shape of the output Tensor, the data type is int. input_dim_idx (int, optional): An index used to get the input dimension value which will be used to resize the output dimension. Default 0. output_dim_idx (int, optional): An index used to indicate the specific dimension that will be replaced by corresponding input dimension value. Default 0. min (float, optional): The lower bound on the range of random values to generate, the min is included in the range. Default -1.0. max (float, optional): The upper bound on the range of random values to generate, the max is excluded in the range. Default 1.0. seed (int, optional): Random seed used for generating samples. 0 means use a seed generated by the system.Note that if seed is not 0, this operator will always generate the same random numbers every time. dtype(np.dtype|core.VarDesc.VarType|str, optional): The data type of output Tensor. Supported data types: float32, float64. Default float32. Returns: Variable: A Tensor of the specified shape filled with uniform_random values. The shape of the Tensor is determined by the shape parameter and the specified dimension of the input Tensor. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() # example 1: input = fluid.data(name="input", shape=[1, 3], dtype='float32') out_1 = fluid.layers.uniform_random_batch_size_like(input, [2, 4]) # out_1.shape=[1, 4] # example 2: out_2 = fluid.layers.uniform_random_batch_size_like(input, [2, 4], input_dim_idx=1, output_dim_idx=1) # out_2.shape=[2, 3] """ check_variable_and_dtype(input, 'Input', ("float32", 'float64', "uint16"), 'uniform_random_batch_size_like') check_type(shape, 'shape', (list, tuple), 'uniform_random_batch_size_like') check_dtype(dtype, 'dtype', ('float32', 'float64', "uint16"), 'uniform_random_batch_size_like') helper = LayerHelper('uniform_random_batch_size_like', **locals()) out = helper.create_variable_for_type_inference(dtype) c_dtype = convert_np_dtype_to_dtype_(dtype) helper.append_op( type='uniform_random_batch_size_like', inputs={'Input': input}, outputs={'Out': out}, attrs={ 'shape': shape, 'input_dim_idx': input_dim_idx, 'output_dim_idx': output_dim_idx, 'min': min, 'max': max, 'seed': seed, 'dtype': c_dtype }) return out @deprecated(since="2.0.0", update_to="paddle.normal") @templatedoc() def gaussian_random(shape, mean=0.0, std=1.0, seed=0, dtype='float32', name=None): """ This OP returns a Tensor filled with random values sampled from a Gaussian distribution, with ``shape`` and ``dtype``. Args: shape(list|tuple|Tensor): The shape of the output Tensor. If ``shape`` is a list or tuple, the elements of it should be integers or Tensors (with the shape [1], and the data type int32 or int64). If ``shape`` is a Tensor, it should be a 1-D Tensor(with the data type int32 or int64). mean(float|int, optional): Mean of the output tensor, default is 0.0. std(float|int, optional): Standard deviation of the output tensor, default is 1.0. seed(int, optional): ${seed_comment} dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of the output Tensor. Supported data types: float32, float64. Default is float32. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: A Tensor filled with random values sampled from a Gaussian distribution, with ``shape`` and ``dtype``. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() # example 1: # attr shape is a list which doesn't contain Tensor. result_1 = fluid.layers.gaussian_random(shape=[3, 4]) # [[-0.31261674, 1.8736548, -0.6274357, 0.96988016], # [-0.12294637, 0.9554768, 1.5690808, -1.2894802 ], # [-0.60082096, -0.61138713, 1.5345167, -0.21834975]] # example 2: # attr shape is a list which contains Tensor. dim_1 = fluid.layers.fill_constant([1], "int64", 2) dim_2 = fluid.layers.fill_constant([1], "int32", 3) result_2 = fluid.layers.gaussian_random(shape=[dim_1, dim_2]) # [[ 0.51398206, -0.3389769, 0.23597084], # [ 1.0388143, -1.2015356, -1.0499583 ]] # example 3: # attr shape is a Tensor, the data type must be int64 or int32. var_shape = fluid.data(name='var_shape', shape=[2], dtype="int64") result_3 = fluid.layers.gaussian_random(var_shape) # if var_shape's value is [2, 3] # result_3 is: # [[-0.12310527, 0.8187662, 1.923219 ] # [ 0.70721835, 0.5210541, -0.03214082]] .. code-block:: python # declarative mode # required: skiptest import numpy as np from paddle import fluid x = fluid.layers.gaussian_random((2, 3), std=2., seed=10) place = fluid.CPUPlace() exe = fluid.Executor(place) start = fluid.default_startup_program() main = fluid.default_main_program() exe.run(start) x_np, = exe.run(main, feed={}, fetch_list=[x]) x_np # array([[2.3060477, 2.676496 , 3.9911983], # [0.9990833, 2.8675377, 2.2279181]], dtype=float32) .. code-block:: python # imperative mode import numpy as np from paddle import fluid import paddle.fluid.dygraph as dg place = fluid.CPUPlace() with dg.guard(place) as g: x = fluid.layers.gaussian_random((2, 4), mean=2., dtype="float32", seed=10) x_np = x.numpy() x_np # array([[2.3060477 , 2.676496 , 3.9911983 , 0.9990833 ], # [2.8675377 , 2.2279181 , 0.79029655, 2.8447366 ]], dtype=float32) """ if not isinstance(dtype, core.VarDesc.VarType): dtype = convert_np_dtype_to_dtype_(dtype) if in_dygraph_mode(): shape = utils.convert_shape_to_list(shape) return _C_ops.gaussian_random('shape', shape, 'mean', float(mean), 'std', float(std), 'seed', seed, 'dtype', dtype) check_type(shape, 'shape', (list, tuple, Variable), 'gaussian_random/randn') check_dtype(dtype, 'dtype', ['float32', 'float64'], 'gaussian_random/randn') inputs = {} attrs = { 'mean': mean, 'std': std, 'seed': seed, 'dtype': dtype, 'use_mkldnn': False } utils.get_shape_tensor_inputs( inputs=inputs, attrs=attrs, shape=shape, op_type='gaussian_random/randn') helper = LayerHelper('gaussian_random', **locals()) out = helper.create_variable_for_type_inference(dtype) helper.append_op( type='gaussian_random', inputs=inputs, outputs={'Out': out}, attrs=attrs) return out @templatedoc() def sampling_id(x, min=0.0, max=1.0, seed=0, dtype='float32'): """ This op is used for sampling id from multinomial distribution from the input, sampling one id for one sample. Parameters: x (Variable): 2-D tensor, [batch_size, input_feature_dimensions] min (Float): minimum , default 0.0. max (Float): maximum, default 1.0. seed (Float): Random seed, default 0. if seed is not 0, will generate same number every time. dtype(np.dtype|core.VarDesc.VarType|str): The type of output data : float32, float_16, int etc Returns: Variable: sampling tensor. Examples: .. code-block:: python import paddle.fluid as fluid x = fluid.data( name="X", shape=[13, 11], dtype='float32') out = fluid.layers.sampling_id(x) """ helper = LayerHelper('sampling_id', **locals()) out = helper.create_variable_for_type_inference(dtype) helper.append_op( type='sampling_id', inputs={'X': x}, outputs={'Out': out}, attrs={'min': min, 'max': max, 'seed': seed}) return out @deprecated(since='1.8.0', update_to="paddle.normal") @templatedoc() def gaussian_random_batch_size_like(input, shape, input_dim_idx=0, output_dim_idx=0, mean=0.0, std=1.0, seed=0, dtype='float32'): """ ${comment} Args: input (Variable): ${input_comment} shape (tuple|list): ${shape_comment} input_dim_idx (int): ${input_dim_idx_comment} output_dim_idx (int): ${output_dim_idx_comment} mean (float): ${mean_comment} std (float): ${std_comment} seed (int): ${seed_comment} dtype(np.dtype|core.VarDesc.VarType|str): The type of output data, float32 or float_64. Returns: out (Variable): ${out_comment} Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() input = fluid.data(name="input", shape=[13, 11], dtype='float32') out = fluid.layers.gaussian_random_batch_size_like( input, shape=[-1, 11], mean=1.0, std=2.0) """ helper = LayerHelper('gaussian_random_batch_size_like', **locals()) check_type(input, 'input', (Variable), 'fluid.layers.gaussian_random_batch_size_like') check_type(shape, 'shape', (list, tuple), 'fluid.layers.gaussian_random_batch_size_like') check_dtype(dtype, 'dtype', ['float16', 'float32', 'int'], 'fluid.layers.gaussian_random_batch_size_like') out = helper.create_variable_for_type_inference(dtype) c_dtype = convert_np_dtype_to_dtype_(dtype) helper.append_op( type='gaussian_random_batch_size_like', inputs={'Input': input}, outputs={'Out': out}, attrs={ 'shape': shape, 'input_dim_idx': input_dim_idx, 'output_dim_idx': output_dim_idx, 'mean': mean, 'std': std, 'seed': seed, 'dtype': c_dtype }) return out @templatedoc() def sum(x): """ ${comment} Case 1: :: Input: Input. Shape = [2, 3] Input = [[1, 2, 3], [4, 5, 6]] Output: The output. Shape = [2, 3] Output = [[1, 2, 3], [4, 5, 6]] Case 2: :: Input: First input: Input1. Shape = [2, 3] Input1 = [[1, 2, 3], [4, 5, 6]] The second input: Input2. Shape = [2, 3] Input2 = [[7, 8, 9], [10, 11, 12]] Output: The output. Shape = [2, 3] Output = [[8, 10, 12], [14, 16, 18]] Args: x (Variable|list(Variable)): ${x_comment} Returns: Variable: ${out_comment} Examples: .. code-block:: python import paddle.fluid as fluid input0 = fluid.layers.fill_constant(shape=[2, 3], dtype='int64', value=5) input1 = fluid.layers.fill_constant(shape=[2, 3], dtype='int64', value=3) sum = fluid.layers.sum([input0, input1]) # You can print out 'sum' via executor. out = fluid.layers.Print(sum, message="the sum of input0 and input1: ") exe = fluid.Executor(fluid.CPUPlace()) exe.run(fluid.default_main_program()) # The printed result is: # 1570701754 the sum of input0 and input1: The place is:CPUPlace # Tensor[sum_0.tmp_0] # shape: [2,3,] # dtype: l # data: 8,8,8,8,8,8, # the sum of input0 and input1 is 2-D Tensor with shape [2,3]. # dtype is the corresponding C++ data type, which may vary in different environments. # Eg: if the data type of tensor is int64, then the corresponding C++ data type is int64_t, # so the dtype value is typeid(int64_t).Name(), which is 'x' on MacOS, 'l' on Linux, # and '__int64' on Windows. They both represent 64-bit integer variables. """ return paddle.add_n(x) @templatedoc() def slice(input, axes, starts, ends): """ This operator produces a slice of ``input`` along multiple axes. Similar to numpy: https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html Slice uses ``axes``, ``starts`` and ``ends`` attributes to specify the start and end dimension for each axis in the list of axes and Slice uses this information to slice the input data tensor. If a negative value is passed to ``starts`` or ``ends`` such as :math:`-i`, it represents the reverse position of the axis :math:`i-1` (here 0 is the initial position). If the value passed to ``starts`` or ``ends`` is greater than n (the number of elements in this dimension), it represents n. For slicing to the end of a dimension with unknown size, it is recommended to pass in INT_MAX. The size of ``axes`` must be equal to ``starts`` and ``ends``. Following examples will explain how slice works: .. code-block:: text Case1: Given: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] axes = [0, 1] starts = [1, 0] ends = [2, 3] Then: result = [ [5, 6, 7], ] Case2: Given: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] axes = [0, 1] starts = [0, 1] ends = [-1, 1000] # -1 denotes the reverse 0th position of dimension 0. Then: result = [ [2, 3, 4], ] # result = data[0:1, 1:4] Args: input (Tensor): A ``Tensor`` . The data type is ``float16``, ``float32``, ``float64``, ``int32`` or ``int64``. axes (list|tuple): The data type is ``int32`` . Axes that `starts` and `ends` apply to . starts (list|tuple|Tensor): The data type is ``int32`` . If ``starts`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``starts`` is an Tensor, it should be an 1-D Tensor. It represents starting indices of corresponding axis in ``axes``. ends (list|tuple|Tensor): The data type is ``int32`` . If ``ends`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``ends`` is an Tensor, it should be an 1-D Tensor . It represents ending indices of corresponding axis in ``axes``. Returns: Tensor: A ``Tensor``. The data type is same as ``input``. Raises: TypeError: The type of ``starts`` must be list, tuple or Tensor. TypeError: The type of ``ends`` must be list, tuple or Tensor. Examples: .. code-block:: python import paddle input = paddle.rand(shape=[4, 5, 6], dtype='float32') # example 1: # attr starts is a list which doesn't contain tensor. axes = [0, 1, 2] starts = [-3, 0, 2] ends = [3, 2, 4] sliced_1 = paddle.slice(input, axes=axes, starts=starts, ends=ends) # sliced_1 is input[0:3, 0:2, 2:4]. # example 2: # attr starts is a list which contain tensor. minus_3 = paddle.full([1], -3, "int32") sliced_2 = paddle.slice(input, axes=axes, starts=[minus_3, 0, 2], ends=ends) # sliced_2 is input[0:3, 0:2, 2:4]. """ if in_dygraph_mode(): attrs = () starts_tensor = None ends_tensor = None if isinstance(axes, (list, tuple)): axes = list(axes) if len(axes) == 0: raise ValueError( "Input axes should not be an empty list/tuple.") for i in range(len(axes)): if axes[i] < 0: axes[i] = max(0, axes[i] + len(input.shape)) else: axes[i] = min(len(input.shape) - 1, axes[i]) else: raise ValueError( "Input axes must be a python list or tuple, but reveived {}". format(type(axes))) infer_flags = list(1 for i in range(len(axes))) if isinstance(starts, (list, tuple)): starts = [ item.numpy().item(0) if isinstance(item, Variable) else item for item in starts ] attrs += ('starts', starts) elif isinstance(starts, Variable): starts_tensor = starts starts.stop_gradient = True infer_flags = list(-1 for i in range(len(axes))) if isinstance(ends, (list, tuple)): ends = [ item.numpy().item(0) if isinstance(item, Variable) else item for item in ends ] attrs += ('ends', ends) elif isinstance(ends, Variable): ends_tensor = ends ends_tensor.stop_gradient = True infer_flags = list(-1 for i in range(len(axes))) return _C_ops.slice(input, starts_tensor, ends_tensor, 'axes', axes, 'infer_flags', infer_flags, *attrs) if not isinstance(starts, (list, tuple, Variable)): raise ValueError( "Input starts must be an Variable, python list or tuple.") if not isinstance(ends, (list, tuple, Variable)): raise ValueError( "Input ends must be an Variable, python list or tuple.") helper = LayerHelper('slice', **locals()) inputs = {'Input': input} attrs = {'axes': axes} infer_flags = list(1 for i in range(len(axes))) # starts if isinstance(starts, Variable): starts.stop_gradient = True inputs['StartsTensor'] = starts infer_flags = list(-1 for i in range(len(axes))) elif isinstance(starts, (list, tuple)): attrs['starts'] = [] if utils._contain_var(starts): inputs['StartsTensorList'] = utils._convert_to_tensor_list(starts) for i, dim in enumerate(starts): if isinstance(dim, Variable): attrs['starts'].append(-1) infer_flags[i] = -1 else: attrs['starts'].append(dim) else: attrs['starts'] = starts # ends if isinstance(ends, Variable): ends.stop_gradient = True inputs['EndsTensor'] = ends infer_flags = list(-1 for i in range(len(axes))) elif isinstance(ends, (list, tuple)): attrs['ends'] = [] if utils._contain_var(ends): inputs['EndsTensorList'] = utils._convert_to_tensor_list(ends) for i, dim in enumerate(ends): if isinstance(dim, Variable): attrs['ends'].append(-1) infer_flags[i] = -1 else: attrs['ends'].append(dim) else: attrs['ends'] = ends # infer_flags attrs['infer_flags'] = infer_flags out = helper.create_variable_for_type_inference( dtype=helper.input_dtype('input')) helper.append_op( type='slice', inputs=inputs, attrs=attrs, outputs={'Out': out}) return out @deprecated(since='2.0.0', update_to="paddle.strided_slice") def strided_slice(input, axes, starts, ends, strides): """ :alias_main: paddle.strided_slice :alias: paddle.strided_slice,paddle.tensor.strided_slice,paddle.tensor.manipulation.strided_slice :old_api: paddle.fluid.layers.strided_slice This operator produces a slice of ``input`` along multiple axes. Similar to numpy: https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html Slice uses ``axes``, ``starts`` and ``ends`` attributes to specify the start and end dimension for each axis in the list of axes and Slice uses this information to slice the input data tensor. If a negative value is passed to ``starts`` or ``ends`` such as :math:`-i`, it represents the reverse position of the axis :math:`i-1` th(here 0 is the initial position). The ``strides`` represents steps of slicing and if the ``strides`` is negative, slice operation is in the opposite direction. If the value passed to ``starts`` or ``ends`` is greater than n (the number of elements in this dimension), it represents n. For slicing to the end of a dimension with unknown size, it is recommended to pass in INT_MAX. The size of ``axes`` must be equal to ``starts`` , ``ends`` and ``strides``. Following examples will explain how strided_slice works: .. code-block:: text Case1: Given: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] axes = [0, 1] starts = [1, 0] ends = [2, 3] strides = [1, 1] Then: result = [ [5, 6, 7], ] Case2: Given: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] axes = [0, 1] starts = [0, 1] ends = [2, 0] strides = [1, -1] Then: result = [ [8, 7, 6], ] Case3: Given: data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] axes = [0, 1] starts = [0, 1] ends = [-1, 1000] strides = [1, 3] Then: result = [ [2], ] Args: input (Variable): An N-D ``Tensor`` or ``LoDTensor`` . The data type is ``bool``, ``float32``, ``float64``, ``int32`` or ``int64``. axes (list|tuple): The data type is ``int32`` . Axes that `starts` and `ends` apply to. It's optional. If it is not provides, it will be treated as :math:`[0,1,...,len(starts)-1]`. starts (list|tuple|Variable): The data type is ``int32`` . If ``starts`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``starts`` is an Variable, it should be an 1-D Tensor. It represents starting indices of corresponding axis in ``axes``. ends (list|tuple|Variable): The data type is ``int32`` . If ``ends`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``ends`` is an Variable, it should be an 1-D Tensor . It represents ending indices of corresponding axis in ``axes``. strides (list|tuple|Variable): The data type is ``int32`` . If ``strides`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``strides`` is an Variable, it should be an 1-D Tensor . It represents slice step of corresponding axis in ``axes``. Returns: Variable: A ``Tensor`` or ``LoDTensor`` with the same dimension as ``input``. The data type is same as ``input``. Raises: TypeError: The type of ``starts`` must be list, tuple or Variable. TypeError: The type of ``ends`` must be list, tuple or Variable. TypeError: The type of ``strides`` must be list, tuple or Variable. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() input = fluid.data( name="input", shape=[3, 4, 5, 6], dtype='float32') # example 1: # attr starts is a list which doesn't contain tensor Variable. axes = [0, 1, 2] starts = [-3, 0, 2] ends = [3, 2, 4] strides_1 = [1, 1, 1] strides_2 = [1, 1, 2] sliced_1 = fluid.layers.strided_slice(input, axes=axes, starts=starts, ends=ends, strides=strides_1) # sliced_1 is input[:, 0:3:1, 0:2:1, 2:4:1]. # example 2: # attr starts is a list which contain tensor Variable. minus_3 = fluid.layers.fill_constant([1], "int32", -3) sliced_2 = fluid.layers.strided_slice(input, axes=axes, starts=[minus_3, 0, 2], ends=ends, strides=strides_2) # sliced_2 is input[:, 0:3:1, 0:2:1, 2:4:2]. """ helper = LayerHelper('strided_slice', **locals()) check_variable_and_dtype(input, 'input', ['bool', 'float32', 'float64', 'int32', 'int64'], 'strided_slice') check_type(axes, 'axes', (list, tuple), 'strided_slice') check_type(starts, 'starts', (list, tuple, Variable), 'strided_slice') check_type(ends, 'ends', (list, tuple, Variable), 'strided_slice') check_type(strides, 'strides', (list, tuple, Variable), 'strided_slice') def check_list_elements_dtype(list_input, input_name): if isinstance(list_input, Variable): check_dtype(list_input.dtype, input_name, ['int32'], 'strided_slice') else: for i, var in enumerate(list_input): var_name = input_name + '[' + str(i) + ']' if isinstance(var, Variable): check_dtype(var.dtype, var_name, ['int32'], 'strided_slice') check_list_elements_dtype(axes, 'axes') check_list_elements_dtype(starts, 'starts') check_list_elements_dtype(ends, 'ends') check_list_elements_dtype(strides, 'strides') def get_new_list_tensor(old_list): new_list_tensor = [] for dim in old_list: if isinstance(dim, Variable): dim.stop_gradient = True new_list_tensor.append(dim) else: assert (isinstance(dim, int)) temp_out = helper.create_variable_for_type_inference('int32') fill_constant([1], 'int32', dim, force_cpu=True, out=temp_out) new_list_tensor.append(temp_out) return new_list_tensor inputs = {'Input': input} attrs = {'axes': axes} infer_flags = list(1 for i in range(len(axes))) if in_dygraph_mode(): inputs = {'Input': input} attrs = { 'axes': axes, 'starts': starts, 'ends': ends, 'strides': strides, 'infer_flags': infer_flags } else: # starts if isinstance(starts, Variable): starts.stop_gradient = True inputs['StartsTensor'] = starts elif isinstance(starts, (list, tuple)): attrs['starts'] = [] if utils._contain_var(starts): inputs['StartsTensorList'] = get_new_list_tensor(starts) for i, dim in enumerate(starts): if isinstance(dim, Variable): attrs['starts'].append(-1) infer_flags[i] = -1 else: attrs['starts'].append(dim) else: attrs['starts'] = starts # ends if isinstance(ends, Variable): ends.stop_gradient = True inputs['EndsTensor'] = ends elif isinstance(ends, (list, tuple)): attrs['ends'] = [] if utils._contain_var(ends): inputs['EndsTensorList'] = get_new_list_tensor(ends) for i, dim in enumerate(ends): if isinstance(dim, Variable): attrs['ends'].append(-1) infer_flags[i] = -1 else: attrs['ends'].append(dim) else: attrs['ends'] = ends # strides if isinstance(strides, Variable): strides.stop_gradient = True inputs['StridesTensor'] = strides elif isinstance(strides, (list, tuple)): attrs['strides'] = [] if utils._contain_var(strides): inputs['StridesTensorList'] = get_new_list_tensor(strides) for i, dim in enumerate(strides): if isinstance(dim, Variable): attrs['strides'].append(-1) infer_flags[i] = -1 else: attrs['strides'].append(dim) else: attrs['strides'] = strides attrs['infer_flags'] = infer_flags out = helper.create_variable_for_type_inference( dtype=helper.input_dtype('input')) helper.append_op( type='strided_slice', inputs=inputs, attrs=attrs, outputs={'Out': out}) return out def shape(input): """ :alias_main: paddle.shape :alias: paddle.shape,paddle.tensor.shape,paddle.tensor.attribute.shape :old_api: paddle.fluid.layers.shape **Shape Layer** Get the shape of the input. .. code-block:: text Case1: Given N-D Tensor: input = [ [1, 2, 3, 4], [5, 6, 7, 8] ] Then: input.shape = [2, 4] Case2: Given SelectedRows: input.rows = [0, 4, 19] input.height = 20 input.value = [ [1, 2], [3, 4], [5, 6] ] # inner tensor Then: input.shape = [3, 2] Args: input (Variable): The input can be N-D Tensor or SelectedRows with data type bool, float16, float32, float64, int32, int64. If input variable is type of SelectedRows, returns the shape of it's inner tensor. Returns: Variable (Tensor): The shape of the input variable. Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle paddle.enable_static() inputs = fluid.data(name="x", shape=[3, 100, 100], dtype="float32") output = fluid.layers.shape(inputs) exe = fluid.Executor(fluid.CPUPlace()) exe.run(fluid.default_startup_program()) img = np.ones((3, 100, 100)).astype(np.float32) res = exe.run(fluid.default_main_program(), feed={'x':img}, fetch_list=[output]) print(res) # [array([ 3, 100, 100], dtype=int32)] """ if in_dygraph_mode(): out = _C_ops.shape(input) out.stop_gradient = True return out check_variable_and_dtype(input, 'input', [ 'bool', 'float16', 'float32', 'float64', 'int32', 'int64', 'complex64', 'complex128' ], 'shape') helper = LayerHelper('shape', **locals()) out = helper.create_variable_for_type_inference(dtype='int32') helper.append_op( type='shape', inputs={'Input': input}, outputs={'Out': out}, stop_gradient=True) return out def rank(input): """ The OP returns the number of dimensions for a tensor, which is a 0-D int32 Tensor. Args: input (Tensor): The input N-D tensor with shape of :math:`[N_1, N_2, ..., N_k]`, the data type is arbitrary. Returns: Tensor, the output data type is int32.: The 0-D tensor with the dimensions of the input Tensor. Examples: .. code-block:: python import paddle input = paddle.rand((3, 100, 100)) rank = paddle.rank(input) print(rank) # 3 """ check_type(input, 'input', (Variable), 'input') ndims = len(input.shape) out = assign(np.array(ndims, 'int32')) return out @deprecated(since="2.0.0", update_to="paddle.numel") def size(input): """ **Size Layer** Returns the number of elements for a tensor, which is a int64 Tensor with shape [1]. Args: input (Tensor): The input Tensor, it's data type can be bool, float16, float32, float64, int32, int64. Returns: Tensor: The number of elements for the input Tensor. Raises: TypeError: ``input`` must be a Tensor and the data type of ``input`` must be one of bool, float16, float32, float64, int32, int64. Examples: .. code-block:: python import paddle import paddle.fluid.layers as layers paddle.enable_static() input = layers.data( name="input", shape=[3, 100], dtype="float32", append_batch_size=False) rank = layers.size(input) # 300 """ if in_dygraph_mode(): return _C_ops.size(input) check_variable_and_dtype( input, 'input', ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], "size") helper = LayerHelper('size', **locals()) out = helper.create_variable_for_type_inference(dtype='int64') helper.append_op(type='size', inputs={'Input': input}, outputs={'Out': out}) return out def _elementwise_op(helper): op_type = helper.layer_type x = helper.kwargs.get('x', None) y = helper.kwargs.get('y', None) assert x is not None, 'x cannot be None in {}'.format(op_type) assert y is not None, 'y cannot be None in {}'.format(op_type) check_variable_and_dtype( x, 'x', ['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'], op_type) check_variable_and_dtype( y, 'y', ['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'], op_type) axis = helper.kwargs.get('axis', -1) use_mkldnn = helper.kwargs.get('use_mkldnn', False) name = helper.kwargs.get('name', None) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type=op_type, inputs={'X': x, 'Y': y}, outputs={'Out': out}, attrs={'axis': axis, 'use_mkldnn': use_mkldnn}) return helper.append_activation(out) def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None): """ Scale operator. Putting scale and bias to the input Tensor as following: ``bias_after_scale`` is True: .. math:: Out=scale*X+bias ``bias_after_scale`` is False: .. math:: Out=scale*(X+bias) Args: x(Tensor): Input N-D Tensor of scale operator. Data type can be float32, float64, int8, int16, int32, int64, uint8. scale(float|Tensor): The scale factor of the input, it should be a float number or a Tensor with shape [1] and data type as float32. bias(float): The bias to be put on the input. bias_after_scale(bool): Apply bias addition after or before scaling. It is useful for numeric stability in some circumstances. act(str, optional): Activation applied to the output such as tanh, softmax, sigmoid, relu. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: Output tensor of scale operator, with shape and data type same as input. Examples: .. code-block:: python # scale as a float32 number import paddle data = paddle.randn(shape=[2,3], dtype='float32') res = paddle.scale(data, scale=2.0, bias=1.0) .. code-block:: python # scale with parameter scale as a Tensor import paddle data = paddle.randn(shape=[2, 3], dtype='float32') factor = paddle.to_tensor([2], dtype='float32') res = paddle.scale(data, scale=factor, bias=1.0) """ if in_dygraph_mode(): _scale = scale.numpy().item(0) if isinstance(scale, Variable) else scale out = _C_ops.scale(x, 'scale', float(_scale), 'bias', float(bias), 'bias_after_scale', bias_after_scale) return dygraph_utils._append_activation_in_dygraph(out) check_variable_and_dtype(x, "x", [ 'float16', 'uint16', 'float32', 'float64', 'int8', 'int16', 'int32', 'int64', 'uint8' ], "scale") inputs = {'X': [x]} attrs = { 'bias': float(bias), 'bias_after_scale': bias_after_scale, } if isinstance(scale, Variable): inputs['ScaleTensor'] = [scale] else: attrs['scale'] = float(scale) helper = LayerHelper('scale', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='scale', inputs=inputs, outputs={'Out': out}, attrs=attrs) return helper.append_activation(out) def elementwise_add(x, y, axis=-1, act=None, name=None): """ Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.array([2, 3, 4]).astype('float32'), "y": np.array([1, 5, 2]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[3], dtype='float32') y = fluid.data(name="y", shape=[3], dtype='float32') z = fluid.layers.elementwise_add(x, y) # z = x + y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # [3., 8., 6.] .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.ones((2, 3, 4, 5)).astype('float32'), "y": np.zeros((3, 4)).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') y = fluid.data(name="y", shape=[3,4], dtype='float32') z = fluid.layers.elementwise_add(x, y, axis=1) # z = x + y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # z.shape=[2,3,4,5] .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.random.randint(1, 5, size=[2, 3, 4, 5]).astype('float32'), "y": np.random.randint(1, 5, size=[5]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') y = fluid.data(name="y", shape=[5], dtype='float32') z = fluid.layers.elementwise_add(x, y, axis=3) # z = x + y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # z.shape=[2,3,4,5] """ if in_dygraph_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name='elementwise_add', use_mkldnn=_global_flags()["FLAGS_use_mkldnn"]) return _elementwise_op(LayerHelper('elementwise_add', **locals())) @deprecated(since="2.0.0", update_to="paddle.divide") def elementwise_div(x, y, axis=-1, act=None, name=None): """ Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.array([2, 3, 4]).astype('float32'), "y": np.array([1, 5, 2]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[3], dtype='float32') y = fluid.data(name="y", shape=[3], dtype='float32') z = fluid.layers.elementwise_div(x, y) # z = x / y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # [2., 0.6, 2.] .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.ones((2, 3, 4, 5)).astype('float32'), "y": np.zeros((3, 4)).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') y = fluid.data(name="y", shape=[3,4], dtype='float32') z = fluid.layers.elementwise_div(x, y, axis=1) # z = x / y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # z.shape=[2,3,4,5] .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.random.randint(1, 5, size=[2, 3, 4, 5]).astype('float32'), "y": np.random.randint(1, 5, size=[5]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') y = fluid.data(name="y", shape=[5], dtype='float32') z = fluid.layers.elementwise_div(x, y, axis=3) # z = x / y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # z.shape=[2,3,4,5] """ if in_dygraph_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name='elementwise_div') return _elementwise_op(LayerHelper('elementwise_div', **locals())) def elementwise_sub(x, y, axis=-1, act=None, name=None): """ Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.array([2, 3, 4]).astype('float32'), "y": np.array([1, 5, 2]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[3], dtype='float32') y = fluid.data(name="y", shape=[3], dtype='float32') z = fluid.layers.elementwise_sub(x, y) # z = x - y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # [1., -2., 2.] .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.ones((2, 3, 4, 5)).astype('float32'), "y": np.zeros((3, 4)).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') y = fluid.data(name="y", shape=[3,4], dtype='float32') z = fluid.layers.elementwise_sub(x, y, axis=1) # z = x - y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # z.shape=[2,3,4,5] .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.random.randint(1, 5, size=[2, 3, 4, 5]).astype('float32'), "y": np.random.randint(1, 5, size=[5]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') y = fluid.data(name="y", shape=[5], dtype='float32') z = fluid.layers.elementwise_sub(x, y, axis=3) # z = x - y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # z.shape=[2,3,4,5] """ if in_dygraph_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name='elementwise_sub') return _elementwise_op(LayerHelper('elementwise_sub', **locals())) @deprecated(since="2.0.0", update_to="paddle.multiply") def elementwise_mul(x, y, axis=-1, act=None, name=None): """ Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.array([2, 3, 4]).astype('float32'), "y": np.array([1, 5, 2]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[3], dtype='float32') y = fluid.data(name="y", shape=[3], dtype='float32') z = fluid.layers.elementwise_mul(x, y) # z = x * y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # [2., 15., 8.] .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.ones((2, 3, 4, 5)).astype('float32'), "y": np.zeros((3, 4)).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') y = fluid.data(name="y", shape=[3,4], dtype='float32') z = fluid.layers.elementwise_mul(x, y, axis=1) # z = x * y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # z.shape=[2,3,4,5] .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.random.randint(1, 5, size=[2, 3, 4, 5]).astype('float32'), "y": np.random.randint(1, 5, size=[5]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') y = fluid.data(name="y", shape=[5], dtype='float32') z = fluid.layers.elementwise_mul(x, y, axis=3) # z = x * y place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) # z.shape=[2,3,4,5] """ if in_dygraph_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name='elementwise_mul') return _elementwise_op(LayerHelper('elementwise_mul', **locals())) def elementwise_max(x, y, axis=-1, act=None, name=None): """ :alias_main: paddle.elementwise_max :alias: paddle.elementwise_max,paddle.tensor.elementwise_max,paddle.tensor.math.elementwise_max :old_api: paddle.fluid.layers.elementwise_max Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.array([2, 3, 4]).astype('float32'), "y": np.array([1, 5, 2]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[3], dtype='float32') y = fluid.data(name="y", shape=[3], dtype='float32') z = fluid.layers.elementwise_max(x, y) place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) #[2, 5, 4] .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.ones((2, 3, 4, 5)).astype('float32'), "y": np.zeros((3, 4)).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') y = fluid.data(name="y", shape=[3,4], dtype='float32') z = fluid.layers.elementwise_max(x, y, axis=1) place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value)#[[[[1., 1., 1., 1., 1.] .... [1., 1., 1., 1., 1.]]]] """ if in_dygraph_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name='elementwise_max') return _elementwise_op(LayerHelper('elementwise_max', **locals())) def elementwise_min(x, y, axis=-1, act=None, name=None): """ :alias_main: paddle.elementwise_min :alias: paddle.elementwise_min,paddle.tensor.elementwise_min,paddle.tensor.math.elementwise_min :old_api: paddle.fluid.layers.elementwise_min Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.array([2, 3, 4]).astype('float32'), "y": np.array([1, 5, 2]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[3], dtype='float32') y = fluid.data(name="y", shape=[3], dtype='float32') z = fluid.layers.elementwise_min(x, y) place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) #[1, 3, 2] .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.ones((2, 3, 4, 5)).astype('float32'), "y": np.zeros((3, 4)).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') y = fluid.data(name="y", shape=[3,4], dtype='float32') z = fluid.layers.elementwise_min(x, y, axis=1) place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value)#[[[[0., 0., 0., 0., 0.] .... [0., 0., 0., 0., 0.]]]] """ if in_dygraph_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name='elementwise_min') return _elementwise_op(LayerHelper('elementwise_min', **locals())) def elementwise_pow(x, y, axis=-1, act=None, name=None): """ Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.array([2, 3, 4]).astype('float32'), "y": np.array([1, 5, 2]).astype('float32') } paddle.enable_static() x = fluid.data(name="x", shape=[3], dtype='float32') y = fluid.data(name="y", shape=[3], dtype='float32') z = fluid.layers.elementwise_pow(x, y) place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) #[2, 243, 16] """ if in_dygraph_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name='elementwise_pow') return _elementwise_op(LayerHelper('elementwise_pow', **locals())) @deprecated(since="2.0.0", update_to="paddle.remainder") def elementwise_mod(x, y, axis=-1, act=None, name=None): """ Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.array([10, 15, 8]).astype('int32'), "y": np.array([3, 6, 5]).astype('int32') } paddle.enable_static() x = fluid.data(name="x", shape=[3], dtype='int32') y = fluid.data(name="y", shape=[3], dtype='int32') z = fluid.layers.elementwise_mod(x, y) place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) #[1, 3, 3] """ if in_dygraph_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name='elementwise_mod') return _elementwise_op(LayerHelper('elementwise_mod', **locals())) @deprecated(since="2.0.0", update_to="paddle.floor_divide") def elementwise_floordiv(x, y, axis=-1, act=None, name=None): """ Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle def gen_data(): return { "x": np.array([10, 15, 8]).astype('int32'), "y": np.array([3, 7, 5]).astype('int32') } paddle.enable_static() x = fluid.data(name="x", shape=[3], dtype='int32') y = fluid.data(name="y", shape=[3], dtype='int32') z = fluid.layers.elementwise_floordiv(x, y) place = fluid.CPUPlace() exe = fluid.Executor(place) z_value = exe.run(feed=gen_data(), fetch_list=[z.name]) print(z_value) #[3, 2, 1] """ if in_dygraph_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name='elementwise_floordiv') return _elementwise_op(LayerHelper('elementwise_floordiv', **locals())) for func in [ elementwise_add, elementwise_div, elementwise_sub, elementwise_mul, elementwise_max, elementwise_pow, elementwise_min, elementwise_mod, elementwise_floordiv, ]: op_proto = OpProtoHolder.instance().get_op_proto(func.__name__) # insert the c++ doc string on top of python doc string func.__doc__ = _generate_doc_string_( op_proto, additional_args_lines=[ "axis (int32, optional): If X.dimension != Y.dimension, \ Y.dimension must be a subsequence of x.dimension. \ And axis is the start dimension index for broadcasting Y onto X. ", "act (string, optional): Activation applied to the output. \ Default is None. Details: :ref:`api_guide_activations_en` ", "name (string, optional): Name of the output. \ Default is None. It's used to print debug info for developers. Details: \ :ref:`api_guide_Name` " ], skip_attrs_set={ "x_data_format", "y_data_format", "axis", "use_quantizer", "mkldnn_data_type", "Scale_x", "Scale_y", "Scale_out" }) + """\n""" + str(func.__doc__) doc_list = func.__doc__.splitlines() for idx, val in enumerate(doc_list): if val.startswith("Warning: ") and val.endswith( " instead." ) and "and will be removed in future versions." in val: doc_list.insert(0, doc_list.pop(idx)) func.__doc__ = "\n" + "\n".join(i for i in doc_list) break for func in []: op_proto = OpProtoHolder.instance().get_op_proto(func.__name__) func.__doc__ = _generate_doc_string_( op_proto, additional_args_lines=[ "act (basestring|None): Activation applied to the output.", "name (basestring|None): Name of the output." ]) func.__doc__ = func.__doc__ + """ Examples: .. code-block:: python import paddle.fluid as fluid # example 1: shape(x) = (2, 3, 4, 5), shape(y) = (2, 3, 4, 5) x0 = fluid.layers.data(name="x0", shape=[2, 3, 4, 5], dtype='float32') y0 = fluid.layers.data(name="y0", shape=[2, 3, 4, 5], dtype='float32') z0 = fluid.layers.%s(x0, y0) # example 2: shape(X) = (2, 3, 4, 5), shape(Y) = (5) x1 = fluid.layers.data(name="x1", shape=[2, 3, 4, 5], dtype='float32') y1 = fluid.layers.data(name="y1", shape=[5], dtype='float32') z1 = fluid.layers.%s(x1, y1) # example 3: shape(X) = (2, 3, 4, 5), shape(Y) = (4, 5), with axis=-1(default) or axis=2 x2 = fluid.layers.data(name="x2", shape=[2, 3, 4, 5], dtype='float32') y2 = fluid.layers.data(name="y2", shape=[4, 5], dtype='float32') z2 = fluid.layers.%s(x2, y2, axis=2) # example 4: shape(X) = (2, 3, 4, 5), shape(Y) = (3, 4), with axis=1 x3 = fluid.layers.data(name="x3", shape=[2, 3, 4, 5], dtype='float32') y3 = fluid.layers.data(name="y3", shape=[3, 4], dtype='float32') z3 = fluid.layers.%s(x3, y3, axis=1) # example 5: shape(X) = (2, 3, 4, 5), shape(Y) = (2), with axis=0 x4 = fluid.layers.data(name="x4", shape=[2, 3, 4, 5], dtype='float32') y4 = fluid.layers.data(name="y4", shape=[2], dtype='float32') z4 = fluid.layers.%s(x4, y4, axis=0) # example 6: shape(X) = (2, 3, 4, 5), shape(Y) = (2, 1), with axis=0 x5 = fluid.layers.data(name="x5", shape=[2, 3, 4, 5], dtype='float32') y5 = fluid.layers.data(name="y5", shape=[2], dtype='float32') z5 = fluid.layers.%s(x5, y5, axis=0) """ % (func.__name__, func.__name__, func.__name__, func.__name__, func.__name__, func.__name__) def _logical_op(op_name, x, y, out=None, name=None, binary_op=True): if in_dygraph_mode(): op = getattr(_C_ops, op_name) if binary_op: return op(x, y) else: return op(x) check_variable_and_dtype(x, "x", [ "bool", "int8", "int16", "int32", "int64", "float32", "float64" ], op_name) if y is not None: check_variable_and_dtype(y, "y", [ "bool", "int8", "int16", "int32", "int64", "float32", "float64" ], op_name) if out is not None: check_type(out, "out", Variable, op_name) helper = LayerHelper(op_name, **locals()) if binary_op and x.dtype != y.dtype: raise ValueError( "(InvalidArgument) The DataType of %s Op's Variable must be consistent, but received %s and %s." % (op_name, x.dtype, y.dtype)) if out is None: out = helper.create_variable_for_type_inference(dtype=x.dtype) if binary_op: helper.append_op( type=op_name, inputs={"X": x, "Y": y}, outputs={"Out": out}) else: helper.append_op(type=op_name, inputs={"X": x}, outputs={"Out": out}) return out def logical_and(x, y, out=None, name=None): r""" ``logical_and`` operator computes element-wise logical AND on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``. Each element of ``out`` is calculated by .. math:: out = x \&\& y .. note:: ``paddle.logical_and`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. Args: x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``. Examples: .. code-block:: python import paddle x = paddle.to_tensor([True]) y = paddle.to_tensor([True, False, True, False]) res = paddle.logical_and(x, y) print(res) # [True False True False] """ return _logical_op( op_name="logical_and", x=x, y=y, name=name, out=out, binary_op=True) def logical_or(x, y, out=None, name=None): """ ``logical_or`` operator computes element-wise logical OR on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``. Each element of ``out`` is calculated by .. math:: out = x || y .. note:: ``paddle.logical_or`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. Args: x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. out(Tensor): The ``Variable`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``. Examples: .. code-block:: python import paddle import numpy as np x_data = np.array([True, False], dtype=np.bool).reshape(2, 1) y_data = np.array([True, False, True, False], dtype=np.bool).reshape(2, 2) x = paddle.to_tensor(x_data) y = paddle.to_tensor(y_data) res = paddle.logical_or(x, y) print(res) # [[ True True] [ True False]] """ return _logical_op( op_name="logical_or", x=x, y=y, name=name, out=out, binary_op=True) def logical_xor(x, y, out=None, name=None): r""" ``logical_xor`` operator computes element-wise logical XOR on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``. Each element of ``out`` is calculated by .. math:: out = (x || y) \&\& !(x \&\& y) .. note:: ``paddle.logical_xor`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. Args: x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``. Examples: .. code-block:: python import paddle import numpy as np x_data = np.array([True, False], dtype=np.bool).reshape([2, 1]) y_data = np.array([True, False, True, False], dtype=np.bool).reshape([2, 2]) x = paddle.to_tensor(x_data) y = paddle.to_tensor(y_data) res = paddle.logical_xor(x, y) print(res) # [[False, True], [ True, False]] """ return _logical_op( op_name="logical_xor", x=x, y=y, name=name, out=out, binary_op=True) @templatedoc() def logical_not(x, out=None, name=None): """ ``logical_not`` operator computes element-wise logical NOT on ``x``, and returns ``out``. ``out`` is N-dim boolean ``Variable``. Each element of ``out`` is calculated by .. math:: out = !x Args: x(Tensor): Operand of logical_not operator. Must be a Tensor of type bool, int8, int16, in32, in64, float32, or float64. out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor` will be created to save the output. name(str|None): The default value is None. Normally there is no need for users to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: ${out_comment} Examples: .. code-block:: python import paddle x = paddle.to_tensor([True, False, True, False]) res = paddle.logical_not(x) print(res) # [False True False True] """ return _logical_op( op_name="logical_not", x=x, y=None, name=name, out=out, binary_op=False) @templatedoc() def clip(x, min, max, name=None): """ :old_api: paddle.fluid.layers.clip ${comment} Args: x(${x_type}): ${x_comment} min(float): ${min_comment} max(float): ${max_comment} name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: ${out_comment} Return Type: ${out_type} Examples: .. code-block:: python import paddle.fluid as fluid input = fluid.data( name='data', shape=[1], dtype='float32') reward = fluid.layers.clip(x=input, min=-1.0, max=1.0) """ helper = LayerHelper("clip", **locals()) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'clip') if name is None: name = unique_name.generate_with_ignorable_key(".".join( [helper.name, 'tmp'])) out = helper.create_variable( type=x.type, name=name, dtype=x.dtype, persistable=False) helper.append_op( type="clip", inputs={"X": x}, attrs={"min": min, "max": max}, outputs={"Out": out}) return out @templatedoc() def clip_by_norm(x, max_norm, name=None): """ ${comment} Args: x(${x_type}): ${x_comment} max_norm(${max_norm_type}): ${max_norm_comment} name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: out(${out_type}): ${out_comment} Examples: .. code-block:: python import paddle import paddle.fluid as fluid input = paddle.to_tensor([[2.0, 2.0], [2.0, 2.0]], dtype='float32') reward = fluid.layers.clip_by_norm(x=input, max_norm=1.0) # [[0.5, 0.5], [0.5, 0.5]] """ if in_dygraph_mode(): return _C_ops.clip_by_norm(x, 'max_norm', max_norm) helper = LayerHelper("clip_by_norm", **locals()) check_variable_and_dtype(x, 'X', ['float32', 'float16'], 'clip_by_norm') check_type(max_norm, 'max_norm', (float), 'clip_by_norm') if name is None: name = unique_name.generate_with_ignorable_key(".".join( [helper.name, 'tmp'])) out = helper.create_variable( type=x.type, name=name, dtype=x.dtype, persistable=False) helper.append_op( type="clip_by_norm", inputs={"X": x}, attrs={"max_norm": max_norm}, outputs={"Out": out}) return out @deprecated(since="2.0.0", update_to="paddle.mean") @templatedoc() def mean(x, name=None): """ ${comment} Args: x(${x_type}): ${x_comment} name(basestring|None): Name of the output. Returns: out(${out_type}): ${out_comment} Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() input = fluid.layers.data( name='data', shape=[2, 3], dtype='float32') mean = fluid.layers.mean(input) """ if in_dygraph_mode(): return _C_ops.mean(x) helper = LayerHelper("mean", **locals()) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'mean') out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type="mean", inputs={"X": x}, attrs={}, outputs={"Out": out}) return out @templatedoc() def merge_selected_rows(x, name=None): """ ${comment} Args: x(${x_type}): ${x_comment} name(basestring|None): Name of the output. Returns: out(${out_type}): ${out_comment} Examples: .. code-block:: python import paddle.fluid as fluid b = fluid.default_main_program().global_block() var = b.create_var( name="X", dtype="float32", persistable=True, type=fluid.core.VarDesc.VarType.SELECTED_ROWS) y = fluid.layers.merge_selected_rows(var) """ helper = LayerHelper("merge_selected_rows", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type="merge_selected_rows", inputs={"X": x}, attrs={}, outputs={"Out": out}) return out def mul(x, y, x_num_col_dims=1, y_num_col_dims=1, name=None): """ Mul Operator. This operator is used to perform matrix multiplication for input $x$ and $y$. The equation is: .. math:: Out = x * y Both the input $x$ and $y$ can carry the LoD (Level of Details) information, or not. But the output only shares the LoD information with input $x$. Args: x (Variable): The first input Tensor/LoDTensor of mul_op. y (Variable): The second input Tensor/LoDTensor of mul_op. x_num_col_dims (int, optional): The mul_op can take tensors with more than two dimensions as its inputs. If the input $x$ is a tensor with more than two dimensions, $x$ will be flattened into a two-dimensional matrix first. The flattening rule is: the first `num_col_dims` will be flattened to form the first dimension of the final matrix (the height of the matrix), and the rest `rank(x) - num_col_dims` dimensions are flattened to form the second dimension of the final matrix (the width of the matrix). As a result, height of the flattened matrix is equal to the product of $x$'s first `x_num_col_dims` dimensions' sizes, and width of the flattened matrix is equal to the product of $x$'s last `rank(x) - num_col_dims` dimensions' size. For example, suppose $x$ is a 6-dimensional tensor with the shape [2, 3, 4, 5, 6], and `x_num_col_dims` = 3. Thus, the flattened matrix will have a shape [2 x 3 x 4, 5 x 6] = [24, 30]. Default is 1. y_num_col_dims (int, optional): The mul_op can take tensors with more than two dimensions as its inputs. If the input $y$ is a tensor with more than two dimensions, $y$ will be flattened into a two-dimensional matrix first. The attribute `y_num_col_dims` determines how $y$ is flattened. See comments of `x_num_col_dims` for more details. Default is 1. name (str, optional): Name of the output. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Default is None. Returns: Variable(Tensor/LoDTensor): The output Tensor/LoDTensor of mul op. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() dataX = fluid.layers.data(name="dataX", append_batch_size = False, shape=[2, 5], dtype="float32") dataY = fluid.layers.data(name="dataY", append_batch_size = False, shape=[5, 3], dtype="float32") output = fluid.layers.mul(dataX, dataY, x_num_col_dims = 1, y_num_col_dims = 1) """ if in_dygraph_mode(): return _C_ops.mul(x, y, 'x_num_col_dims', x_num_col_dims, 'y_num_col_dims', y_num_col_dims) inputs = {"X": [x], "Y": [y]} attrs = {"x_num_col_dims": x_num_col_dims, "y_num_col_dims": y_num_col_dims} helper = LayerHelper("mul", **locals()) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'mul') check_variable_and_dtype(y, 'y', ['float16', 'float32', 'float64'], 'mul') out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type="mul", inputs={"X": x, "Y": y}, attrs=attrs, outputs={"Out": out}) return out @deprecated(since="2.0.0", update_to="paddle.nn.functional.maxout") @templatedoc() def maxout(x, groups, name=None, axis=1): """ ${comment} Args: x(${x_type}): ${x_comment} groups(int): ${groups_comment} axis(int, optional): ${axis_comment} name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Variable: ${out_comment} Raises: ValueError: If `axis` is not 1, -1 or 3. ValueError: If the number of input channels can not be divisible by `groups`. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() input = fluid.data( name='data', shape=[None, 256, 32, 32], dtype='float32') out = fluid.layers.maxout(input, groups=2) """ return paddle.nn.functional.maxout(**locals()) def space_to_depth(x, blocksize, name=None): r""" Gives a blocksize to space_to_depth the input LoDtensor with Layout: [batch, channel, height, width] This op rearranges blocks of spatial data, into depth. More specifically, this op outputs a copy of \ theinput LoDtensor where values from the height and width dimensions are moved to the channel \ dimension. The attr blocksize indicates the input block size. space_to_depth will reorganize the elements of input with shape[batch, channel, height, width] \ according to blocksize to construct output with shape \ [batch, channel * blocksize * blocksize, height/blocksize, width/blocksize]: - Non-overlapping blocks of size block_size x block size are rearranged into depth at each location. - The Y, X coordinates within each block of the input become the high order component of the output channel index - channel should be divisible by square of blocksize - height, width should be divsible by blocksize This OP is useful for resizing the activations between convolutions \ (but keeping all data) .. code-block:: text Given the input x with the shape [1, 1, 4, 4]: x.data = [[[[1, 2, 5, 6], [3, 4, 7, 8], [9, 10, 13, 14], [11, 12, 15, 16]]]] blocksize = 2 then get the output with the shape [1, 4, 2, 2]: out.data = [[[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]], [[13, 14], [15, 16]]]] Args: x (Variable): The input, which should be 4 dims Tensor or LodTensor, with the shape \ [batch, channel, height, width] blocksize (int): The blocksize to select the element on each feature map should be > 2 name(str, optional): For detailed information, please refer \ to :ref:`api_guide_Name`. Usually name is no need to set and \ None by default. Returns: The output, which should be 4 dims Tensor or LodTensor, with the shape \ [batch, channel * blocksize * blocksize, height/blocksize, width/blocksize] Return Type: Variable Raises: TypeError: blocksize type must be int64. Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import numpy as np import paddle paddle.enable_static() data = fluid.data( name='data', shape=[1, 4, 2, 2], dtype='float32') space_to_depthed = fluid.layers.space_to_depth( x=data, blocksize=2) exe = fluid.Executor(fluid.CPUPlace()) data_np = np.arange(0,16).reshape((1,4,2,2)).astype('float32') print(data_np) #array([[[[ 0., 1.], [ 2., 3.]], # [[ 4., 5.], [ 6., 7.]], # [[ 8., 9.], [10., 11.]], # [[12., 13.], [14., 15.]]]], dtype=float32) out_main = exe.run(fluid.default_main_program(), feed={'data': data_np}, fetch_list=[space_to_depthed]) print(out_main) #[array([[[[ 0.]], [[ 4.]], [[ 1.]], [[ 5.]], # [[ 8.]], [[12.]], [[ 9.]], [[13.]], # [[ 2.]], [[ 6.]], [[ 3.]], [[ 7.]], # [[10.]], [[14.]], [[11.]], [[15.]]]], dtype=float32)] """ helper = LayerHelper("space_to_depth", **locals()) if not (isinstance(blocksize, int)): raise ValueError("blocksize must be a python Int") check_variable_and_dtype(x, 'x', \ ['float16', 'float32', 'float64', 'int32', 'int64'], 'space_to_depth') out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type="space_to_depth", inputs={"X": x}, attrs={"blocksize": blocksize}, outputs={"Out": out}) return out def affine_channel(x, scale=None, bias=None, data_layout='NCHW', name=None, act=None): """ Applies a separate affine transformation to each channel of the input. Useful for replacing spatial batch norm with its equivalent fixed transformation. The input also can be 2D tensor and applies a affine transformation in second dimension. Args: x (Variable): Feature map input can be a 4D tensor with order NCHW or NHWC. It also can be a 2D tensor and the affine transformation is applied in the second dimension.The data type is float32 or float64. scale (Variable): 1D input of shape (C), the c-th element is the scale factor of the affine transformation for the c-th channel of the input.The data type is float32 or float64. bias (Variable): 1D input of shape (C), the c-th element is the bias of the affine transformation for the c-th channel of the input. The data type is float32 or float64. data_layout (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. If input is 2D Tensor, you can ignore data_layout. name (str, default None): The name of this layer. For more information, please refer to :ref:`api_guide_Name` . act (str, default None): Activation to be applied to the output of this layer. Returns: Variable: A tensor which has the same shape, data layout and data type with x. Examples: .. code-block:: python import numpy as np import paddle.fluid as fluid import paddle.fluid as fluid import paddle paddle.enable_static() use_gpu = False place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace() exe = fluid.Executor(place) data = fluid.data(name='data', shape=[None, 1, 2, 2], dtype='float32') input_scale = fluid.layers.create_parameter(shape=[1], dtype="float32", default_initializer=fluid.initializer.Constant(2.0)) input_bias = fluid.layers.create_parameter(shape=[1],dtype="float32", default_initializer=fluid.initializer.Constant(0.5)) out = fluid.layers.affine_channel(data,scale=input_scale, bias=input_bias) exe.run(fluid.default_startup_program()) test_program = fluid.default_main_program().clone(for_test=True) [out_array] = exe.run(test_program, fetch_list=out, feed={'data': np.ones([1,1,2,2]).astype('float32')}) # out_array is [[[[2.5, 2.5], # [2.5, 2.5]]]] with shape: [1, 1, 2, 2] """ helper = LayerHelper("affine_channel", **locals()) check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'affine_channel') check_type(scale, 'scale', (Variable, type(None)), 'affine_channel') check_type(bias, 'bias', (Variable, type(None)), 'affine_channel') out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type="affine_channel", inputs={"X": x, 'Scale': scale, 'Bias': bias}, attrs={"data_layout": data_layout}, outputs={"Out": out}) return helper.append_activation(out) def similarity_focus(input, axis, indexes, name=None): r""" SimilarityFocus Operator Generate a similarity focus mask with the same shape of input using the following method: 1. Extract the 3-D tensor(here the first dimension is BatchSize) corresponding to the axis according to the indexes. For example, if axis=1 and indexes=[a], it will get the matrix T=X[:, a, :, :]. In this case, if the shape of input X is (BatchSize, A, B, C), the shape of tensor T is (BatchSize, B, C). 2. For each index, find the largest numbers in the tensor T, so that the same row and same column has at most one number(what it means is that if the largest number has been found in the i-th row and the j-th column, then the numbers in the i-th row or j-th column will be skipped. And then the next largest number will be selected from the remaining numbers. Obviously there will be min(B, C) numbers), and mark the corresponding position of the 3-D similarity focus mask as 1, otherwise as 0. Do elementwise-or for each index. 3. Broadcast the 3-D similarity focus mask to the same shape of input X. Refer to `Similarity Focus Layer <http://www.aclweb.org/anthology/N16-1108>`_ .. code-block:: text * Example : Given a 4-D tensor x with the shape (BatchSize, C, A, B), where C is the number of channels and the shape of feature map is (A, B): x.shape = (2, 3, 2, 2) x.data = [[[[0.8, 0.1], [0.4, 0.5]], [[0.9, 0.7], [0.9, 0.9]], [[0.8, 0.9], [0.1, 0.2]]], [[[0.2, 0.5], [0.3, 0.4]], [[0.9, 0.7], [0.8, 0.4]], [[0.0, 0.2], [0.4, 0.7]]]] Given axis: 1 (the axis of the channel) Given indexes: [0] then we get a 4-D tensor out with the same shape of input x: out.shape = (2, 3, 2, 2) out.data = [[[[1.0, 0.0], [0.0, 1.0]], [[1.0, 0.0], [0.0, 1.0]], [[1.0, 0.0], [0.0, 1.0]]], [[[0.0, 1.0], [1.0, 0.0]], [[0.0, 1.0], [1.0, 0.0]], [[0.0, 1.0], [1.0, 0.0]]]] Args: input(Variable): The input tensor variable(default float). It should be a 4-D tensor with shape [BatchSize, A, B, C]. Data type is float32 or float64. axis(int): Indicating the dimension to be selected. It can only be 1, 2 or 3. indexes(list): Indicating the indexes of the selected dimension. Returns: Variable: A tensor variable with the same shape and same type \ as the input. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() data = fluid.data( name='data', shape=[-1, 3, 2, 2], dtype='float32') fluid.layers.similarity_focus(input=data, axis=1, indexes=[0]) """ helper = LayerHelper('similarity_focus', **locals()) # check attrs check_variable_and_dtype(input, 'input', ['float32', 'float64'], "similarity_focus") check_type(axis, 'axis', int, "similarity_focus") check_type(indexes, 'indexes', list, "similarity_focus") if axis != 1 and axis != 2 and axis != 3: raise ValueError("axis must be 1, 2 or 3.") if len(indexes) == 0: raise ValueError("indexes can not be empty.") out = helper.create_variable_for_type_inference(dtype=input.dtype) helper.append_op( type='similarity_focus', inputs={'X': input}, outputs={'Out': out}, attrs={"axis": axis, "indexes": indexes}) return out def hash(input, hash_size, num_hash=1, name=None): """ This OP hash the input to an integer less than the hash_size. The hash algorithm we used was xxHash - Extremely fast hash algorithm (https://github.com/Cyan4973/xxHash/tree/v0.6.5) Args: input(Variable): A **Two-Dimensional** LoDTensor with type int32, int64. **Only support LoDTensor**. num_hash(int, optional): The times of hash, default is 1. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Variable: A LoDTensor with the same data type as input. Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np import paddle paddle.enable_static() place = fluid.core.CPUPlace() x = fluid.data(name="x", shape=[2,2], dtype="int32", lod_level=1) res = fluid.layers.hash(name="res", input=x, hash_size=1000, num_hash=4) exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) in1 = np.array([[1,2],[3,4]]).astype("int32") print(in1) x_i = fluid.create_lod_tensor(in1, [[0, 2]], place) res = exe.run(fluid.default_main_program(), feed={'x':x_i}, fetch_list=[res], return_numpy=False) print(np.array(res[0])) # [[[722] # [407] # [337] # [395]] # [[603] # [590] # [386] # [901]]] """ check_variable_and_dtype(input, 'input', ['int32', 'int64'], 'hash') check_type(hash_size, 'hash_size', int, 'hash') check_type(num_hash, 'num_hash', int, 'hash') helper = LayerHelper('hash', **locals()) out = helper.create_variable_for_type_inference( helper.input_dtype(), stop_gradient=True) helper.append_op( type='hash', inputs={'X': input}, outputs={'Out': out}, attrs={'num_hash': num_hash, 'mod_by': hash_size}) return out @templatedoc() def grid_sampler(x, grid, name=None): """ This operation samples input X by using bilinear interpolation based on flow field grid, which is usually generated by :code:`affine_grid` . The grid of shape [N, H, W, 2] is the concatenation of (x, y) coordinates with shape [N, H, W] each, where x is indexing the 4th dimension (in width dimension) of input data x and y is indexing the 3rd dimension (in height dimension), finally results is the bilinear interpolation value of 4 nearest corner points. The output tensor shape will be [N, C, H, W]. .. code-block:: text Step 1: Get (x, y) grid coordinates and scale to [0, H-1/W-1]. .. code-block:: text grid_x = 0.5 * (grid[:, :, :, 0] + 1) * (W - 1) grid_y = 0.5 * (grid[:, :, :, 1] + 1) * (H - 1) Step 2: Indices input data X with grid (x, y) in each [H, W] area, and bilinear interpolate point value by 4 nearest points. wn ------- y_n ------- en | | | | d_n | | | | x_w --d_w-- grid--d_e-- x_e | | | | d_s | | | | ws ------- y_s ------- wn x_w = floor(x) // west side x coord x_e = x_w + 1 // east side x coord y_n = floor(y) // north side y coord y_s = y_s + 1 // south side y coord d_w = grid_x - x_w // distance to west side d_e = x_e - grid_x // distance to east side d_n = grid_y - y_n // distance to north side d_s = y_s - grid_y // distance to south side wn = X[:, :, y_n, x_w] // north-west point value en = X[:, :, y_n, x_e] // north-east point value ws = X[:, :, y_s, x_w] // south-east point value es = X[:, :, y_s, x_w] // north-east point value output = wn * d_e * d_s + en * d_w * d_s + ws * d_e * d_n + es * d_w * d_n Args: x(Variable): The input tensor, which is a 4-D tensor with shape [N, C, H, W], N is the batch size, C is the channel number, H and W is the feature height and width. The data type is float32 or float64. grid(Variable): Input grid tensor of shape [N, H, W, 2]. The data type is float32 or float64. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Variable: Output of shape [N, C, H, W] data samples input X using bilnear interpolation based on input grid. The data type is same as input tensor. Examples: .. code-block:: python import paddle.fluid as fluid import paddle.fluid as fluid import paddle paddle.enable_static() # use with affine_grid x = fluid.data(name='x', shape=[None, 10, 32, 32], dtype='float32') theta = fluid.layers.data(name='theta', shape=[2, 3], dtype='float32') grid = fluid.layers.affine_grid(theta=theta, out_shape=[3, 10, 32, 32]) out = fluid.layers.grid_sampler(x=x, grid=grid) """ helper = LayerHelper("grid_sampler", **locals()) check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'grid_sampler') check_variable_and_dtype(grid, 'grid', ['float32', 'float64'], 'grid_sampler') if not isinstance(x, Variable): return ValueError("The x should be a Variable") if not isinstance(grid, Variable): return ValueError("The grid should be a Variable") out = helper.create_variable_for_type_inference(x.dtype) ipts = {'X': x, 'Grid': grid} attrs = {'use_cudnn': False} if core.is_compiled_with_rocm() else {} helper.append_op( type='grid_sampler', inputs=ipts, outputs={'Output': out}, attrs=attrs) return out def log_loss(input, label, epsilon=1e-4, name=None): r""" **Negative Log Loss Layer** This layer accepts input predictions and target label and returns the negative log loss. .. math:: Out = -label * \log{(input + \epsilon)} - (1 - label) * \log{(1 - input + \epsilon)} Args: input (Tensor|list): A 2-D tensor with shape [N x 1], where N is the batch size. This input is a probability computed by the previous operator. Data type float32. label (Tensor|list): The ground truth which is a 2-D tensor with shape [N x 1], where N is the batch size. Data type float32. epsilon (float, optional): A small number for numerical stability. Default 1e-4. name(str|None): For detailed information, please refer to :ref:`api_guide_Name` . Usually name is no need to set and None by default. Returns: Tensor, which shape is [N x 1], data type is float32. Examples: .. code-block:: python import paddle import paddle.nn.functional as F label = paddle.randn((10,1)) prob = paddle.randn((10,1)) cost = F.log_loss(input=prob, label=label) """ helper = LayerHelper('log_loss', **locals()) check_variable_and_dtype(input, 'input', ['float32'], 'log_loss') check_variable_and_dtype(label, 'label', ['float32'], 'log_loss') loss = helper.create_variable_for_type_inference(dtype=input.dtype) helper.append_op( type='log_loss', inputs={'Predicted': [input], 'Labels': [label]}, outputs={'Loss': [loss]}, attrs={'epsilon': epsilon}) return loss def add_position_encoding(input, alpha, beta, name=None): r""" This operator performs weighted sum of input feature at each position (position in the sequence) and the corresponding position encoding. For more details of position encoding, please refer to `Attention Is All You Need <http://arxiv.org/pdf/1706.03762.pdf>`_ . The formula is as follows: .. math:: PE(pos, 2i) &= \\sin{(pos / 10000^{2i / P})} \\\\ PE(pos, 2i + 1) &= \\cos{(pos / 10000^{2i / P})} \\\\ Out(:, pos, i) &= \\alpha * input(:, pos, i) + \\beta * PE(pos, i) Where: - :math:`PE(pos, 2i)` : the value at even index `2i` for encoding of position `pos`. - :math:`PE(pos, 2i + 1)` : the value at odd index `2i+1` for encoding of position `pos` Args: input(Variable): A Tensor or LoDTensor (lod level is 1). If it is a Tensor, the shape should be `[N, M, P]`, where `N` stands for batch size, `M` for sequence length, `P` for the size of feature dimension. If it is a LoDTensor, the shape should be `[N, P]`, where `N` stands for the total sequence lengths in this mini-batch, `P` for the size of feature. The data type should be float32 or float64. alpha(float): Indicate the weight coefficient for `input` when performing weighted sum. beta(float): Indicate the weight coefficient for position encoding when performing weighted sum. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Variable: A Tensor or LoDTensor. It has the same shape, data type and lod as `input`. Examples: .. code-block:: python import paddle tensor = paddle.randn([16, 32, 64]) position_tensor = paddle.fluid.layers.add_position_encoding( input=tensor, alpha=1.0, beta=1.0) """ if in_dygraph_mode(): return _C_ops.add_position_encoding(input, "alpha", alpha, "beta", beta) helper = LayerHelper('add_position_encoding', **locals()) check_variable_and_dtype(input, 'input', ['float32', 'float64'], "add_position_encoding") dtype = helper.input_dtype() out = helper.create_variable_for_type_inference(dtype=dtype) helper.append_op( type="add_position_encoding", inputs={"X": input}, outputs={"Out": out}, attrs={"alpha": alpha, "beta": beta}) return out def bilinear_tensor_product(x, y, size, act=None, name=None, param_attr=None, bias_attr=None): r""" :api_attr: Static Graph **Bilinear Tensor Product Layer** This layer performs bilinear tensor product on two inputs. For example: .. math:: out_{i} = x * W_{i} * {y^\mathrm{T}}, i=0,1,...,size-1 In this formula: - :math:`x`: the first input contains M elements, shape is [batch_size, M]. - :math:`y`: the second input contains N elements, shape is [batch_size, N]. - :math:`W_{i}`: the i-th learned weight, shape is [M, N]. - :math:`out_{i}`: the i-th element of out, shape is [batch_size, size]. - :math:`y^\mathrm{T}`: the transpose of :math:`y_{2}`. Args: x (Variable): 2-D input tensor with shape [batch_size, M]. Data type is float32 or float64. y (Variable): 2-D input tensor with shape [batch_size, N]. Data type should be same as **x**. size (int): The dimension of this layer. act (str|None): Activation to be applied to the output of this layer. Default None. name(str|None): For detailed information, please refer to :ref:`api_guide_Name` . Usually name is no need to set and None by default. param_attr (ParamAttr|None): To specify the weight parameter attribute. Default: None, which means the default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . bias_attr (ParamAttr|None): To specify the bias parameter attribute. Default: None, which means the default bias parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . Returns: Variable: A 2-D Tensor of shape [batch_size, size]. Data type is the same as input **x**. Examples: .. code-block:: python import paddle paddle.enable_static() layer1 = paddle.static.data("t1", shape=[-1, 5], dtype="float32") layer2 = paddle.static.data("t2", shape=[-1, 4], dtype="float32") tensor = paddle.static.nn.bilinear_tensor_product(x=layer1, y=layer2, size=1000) """ helper = LayerHelper('bilinear_tensor_product', **locals()) dtype = helper.input_dtype('x') param_shape = [size, x.shape[1], y.shape[1]] w = helper.create_parameter( attr=helper.param_attr, shape=param_shape, dtype=dtype, is_bias=False) out = helper.create_variable_for_type_inference(dtype=dtype) inputs = {"X": x, "Y": y, "Weight": w} if helper.bias_attr: bias_size = [1, size] bias = helper.create_parameter( attr=helper.bias_attr, shape=bias_size, dtype=dtype, is_bias=True) inputs["Bias"] = bias helper.append_op( type="bilinear_tensor_product", inputs=inputs, outputs={"Out": out}) # add activation return helper.append_activation(out) @templatedoc() def get_tensor_from_selected_rows(x, name=None): """ This operator gets tensor data from input with SelectedRows type, and outputs a LoDTensor. .. code-block:: text input x is SelectedRows: x.rows = [0, 5, 5, 4, 19] x.height = 20 x.value = [[1, 1] [2, 2] [2, 2] [3, 3] [6, 6]] Ouput is LoDTensor: out.shape = [5, 2] out.data = [[1, 1], [2, 2], [2, 2], [3, 3], [6, 6]] Args: x(SelectedRows): Input with SelectedRows type. The data type is float32, float64, int32 or int64. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Variable: LoDTensor transformed from SelectedRows. The data type is same with input. Examples: .. code-block:: python import paddle.fluid as fluid b = fluid.default_main_program().global_block() input = b.create_var(name="X", dtype="float32", persistable=True, type=fluid.core.VarDesc.VarType.SELECTED_ROWS) out = fluid.layers.get_tensor_from_selected_rows(input) """ check_type(x, 'x', Variable, 'get_tensor_from_selected_rows') if x.type != core.VarDesc.VarType.SELECTED_ROWS: raise TypeError( "The type of 'x' in get_tensor_from_selected_rows must be SELECTED_ROWS." ) helper = LayerHelper('get_tensor_from_selected_rows', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='get_tensor_from_selected_rows', inputs={'X': x}, outputs={'Out': out}, attrs={}) return out def shuffle_channel(x, group, name=None): """ This operator shuffles the channels of input x. It divide the input channels in each group into :attr:`group` subgroups, and obtain a new order by selecting element from every subgroup one by one. Please refer to the paper https://arxiv.org/pdf/1707.01083.pdf .. code-block:: text Given a 4-D tensor input with the shape (N, C, H, W): input.shape = (1, 4, 2, 2) input.data =[[[[0.1, 0.2], [0.2, 0.3]], [[0.3, 0.4], [0.4, 0.5]], [[0.5, 0.6], [0.6, 0.7]], [[0.7, 0.8], [0.8, 0.9]]]] Given group: 2 then we get a 4-D tensor out with the same shape of input: out.shape = (1, 4, 2, 2) out.data = [[[[0.1, 0.2], [0.2, 0.3]], [[0.5, 0.6], [0.6, 0.7]], [[0.3, 0.4], [0.4, 0.5]], [[0.7, 0.8], [0.8, 0.9]]]] Args: x(Variable): The input tensor variable. It should be a 4-D tensor with shape [N, C, H, W] group(int): Indicating the counts of subgroups, It should divide the number of channels. Returns: out(Variable): the channels shuffling result is a tensor variable with the same shape and same type as the input. Raises: ValueError: If group is not an int type variable. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() input = fluid.data(name='input', shape=[None,4,2,2], dtype='float32') out = fluid.layers.shuffle_channel(x=input, group=2) """ helper = LayerHelper("shuffle_channel", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) if not isinstance(group, int): raise TypeError("group must be int type") helper.append_op( type="shuffle_channel", inputs={"X": x}, outputs={"Out": out}, attrs={"group": group}) return out @templatedoc() def temporal_shift(x, seg_num, shift_ratio=0.25, name=None, data_format="NCHW"): """ **Temporal Shift Operator** ${comment} Args: x(Tensor): ${x_comment} seg_num(int): ${seg_num_comment} shift_ratio(float): ${shift_ratio_comment} name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. data_format(str, optional): Data format that specifies the layout of input. It can be "NCHW" or "NHWC". Default: "NCHW". Returns: out(Tensor): The temporal shifting result is a tensor with the same shape and same data type as the input. Raises: TypeError: seg_num must be int type. Examples: .. code-block:: python import paddle import paddle.nn.functional as F input = paddle.randn([6, 4, 2, 2]) out = F.temporal_shift(x=input, seg_num=2, shift_ratio=0.2) """ if data_format not in ["NCHW", "NHWC"]: raise ValueError("Attr(data_format) should be 'NCHW' or 'NHWC'. " "Received Attr(data_format): {}.".format(data_format)) if in_dygraph_mode(): return _C_ops.temporal_shift(x, 'seg_num', seg_num, 'shift_ratio', shift_ratio, 'data_format', data_format) helper = LayerHelper("temporal_shift", **locals()) check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'temporal_shift') check_type(seg_num, 'seg_num', int, 'temporal_shift') check_type(shift_ratio, 'shift_ratio', float, 'temporal_shift') out = helper.create_variable_for_type_inference(dtype=x.dtype) if not isinstance(seg_num, int): raise TypeError("seg_num must be int type.") helper.append_op( type="temporal_shift", inputs={"X": x}, outputs={"Out": out}, attrs={ "seg_num": seg_num, "shift_ratio": shift_ratio, "data_format": data_format }) return out class PyFuncRegistry(object): _register_funcs = [] def __init__(self, func): if func is None or not callable(func): raise TypeError('func must be a Python function') self._func = func # find named args using reflection args = inspect.getargspec(self._func) if len(args[0]) == 0 and args[1] is None and args[2] is None: # Function with no inputs self._named_args = None else: self._named_args = args[0] self._id = core._append_python_callable_object_and_return_id(self) ''' Why record self here? 1. For debug usage. Users can call :code:`py_func.registered_func(idx)` method to find the registered function corresponding to :code:`idx`. 2. For increasing reference count of self. It seems that to release Python object whose reference count is 1 would cause segmentation fault error in C++ side. May be lack of Python GC in C++ side? ''' PyFuncRegistry._register_funcs.append(self) @classmethod def registered_func(cls, idx): return cls._register_funcs[idx]._func @classmethod def registered_func_num(cls): return len(cls._register_funcs) @property def id(self): return self._id def __call__(self, *args): if self._named_args is None: func_ret = self._func() else: kwargs = dict() idx = 0 for arg in self._named_args: kwargs[arg] = args[idx] idx += 1 func_ret = self._func(*args[idx:], **kwargs) if not isinstance(func_ret, (list, tuple)): func_ret = (func_ret, ) ret = [] for each_ret in func_ret: if each_ret is None or isinstance(each_ret, core.LoDTensor): ret.append(each_ret) continue if not isinstance(each_ret, np.ndarray): each_ret = np.array(each_ret) tensor = core.LoDTensor() tensor.set(each_ret, core.CPUPlace()) ret.append(tensor) return tuple(ret) @static_only @templatedoc() def py_func(func, x, out, backward_func=None, skip_vars_in_backward_input=None): """ :api_attr: Static Graph This OP is used to register customized Python OP to Paddle. The design principe of py_func is that Tensor and numpy array can be converted to each other easily. So you can use Python and numpy API to register a python OP. The forward function of the registered OP is ``func`` and the backward function of that is ``backward_func``. Paddle will call ``func`` at forward runtime and call ``backward_func`` at backward runtime(if ``backward_func`` is not None). ``x`` is the input of ``func``, whose type must be Tensor; ``out`` is the output of ``func``, whose type can be either Tensor or numpy array. The input of the backward function ``backward_func`` is ``x``, ``out`` and the gradient of ``out``. If ``out`` have no gradient, the relevant input of ``backward_func`` is None. If ``x`` do not have a gradient, the user should return None in ``backward_func``. The data type and shape of ``out`` should also be set correctly before this API is called, and the data type and shape of the gradient of ``out`` and ``x`` will be inferred automatically. This API can also be used to debug the neural network by setting the ``func`` as a function that only print variables. Args: func (callable): The forward function of the registered OP. When the network is running, the forward output ``out`` will be calculated according to this function and the forward input ``x``. In ``func`` , it's suggested that we actively convert Tensor into a numpy array, so that we can use Python and numpy API arbitrarily. If not, some operations of numpy may not be compatible. x (Tensor|tuple(Tensor)|list[Tensor]): The input of the forward function ``func``. It can be Tensor|tuple(Tensor)|list[Tensor]. In addition, Multiple Tensor should be passed in the form of tuple(Tensor) or list[Tensor]. out (T|tuple(T)|list[T]): The output of the forward function ``func``, it can be T|tuple(T)|list[T], where T can be either Tensor or numpy array. Since Paddle cannot automatically infer the shape and type of ``out``, you must create ``out`` in advance. backward_func (callable, optional): The backward function of the registered OP. Its default value is None, which means there is no reverse calculation. If it is not None, ``backward_func`` is called to calculate the gradient of ``x`` when the network is at backward runtime. skip_vars_in_backward_input (Tensor, optional): It's used to limit the input list of ``backward_func``, and it can be Tensor|tuple(Tensor)|list[Tensor]. It must belong to either ``x`` or ``out``. The default value is None, which means that no tensors need to be removed from ``x`` and ``out``. If it is not None, these tensors will not be the input of ``backward_func``. This parameter is only useful when ``backward_func`` is not None. Returns: Tensor|tuple(Tensor)|list[Tensor]: The output ``out`` of the forward function ``func``. Examples: .. code-block:: python # example 1: import paddle import six import numpy as np paddle.enable_static() # Creates a forward function, Tensor can be input directly without # being converted into numpy array. def tanh(x): return np.tanh(x) # Skip x in backward function and return the gradient of x # Tensor must be actively converted to numpy array, otherwise, # operations such as +/- can't be used. def tanh_grad(y, dy): return np.array(dy) * (1 - np.square(np.array(y))) # Creates a forward function for debugging running networks(print value) def debug_func(x): print(x) def create_tmp_var(name, dtype, shape): return paddle.static.default_main_program().current_block().create_var( name=name, dtype=dtype, shape=shape) def simple_net(img, label): hidden = img for idx in six.moves.range(4): hidden = paddle.static.nn.fc(hidden, size=200) new_hidden = create_tmp_var(name='hidden_{}'.format(idx), dtype=hidden.dtype, shape=hidden.shape) # User-defined forward and backward hidden = paddle.static.py_func(func=tanh, x=hidden, out=new_hidden, backward_func=tanh_grad, skip_vars_in_backward_input=hidden) # User-defined debug functions that print out the input Tensor paddle.static.py_func(func=debug_func, x=hidden, out=None) prediction = paddle.static.nn.fc(hidden, size=10, activation='softmax') ce_loss = paddle.nn.loss.CrossEntropyLoss() return ce_loss(prediction, label) x = paddle.static.data(name='x', shape=[1,4], dtype='float32') y = paddle.static.data(name='y', shape=[1,10], dtype='int64') res = simple_net(x, y) exe = paddle.static.Executor(paddle.CPUPlace()) exe.run(paddle.static.default_startup_program()) input1 = np.random.random(size=[1,4]).astype('float32') input2 = np.random.randint(1, 10, size=[1,10], dtype='int64') out = exe.run(paddle.static.default_main_program(), feed={'x':input1, 'y':input2}, fetch_list=[res.name]) print(out) .. code-block:: python # example 2: # This example shows how to turn Tensor into numpy array and # use numpy API to register an Python OP import paddle import numpy as np paddle.enable_static() def element_wise_add(x, y): # Tensor must be actively converted to numpy array, otherwise, # numpy.shape can't be used. x = np.array(x) y = np.array(y) if x.shape != y.shape: raise AssertionError("the shape of inputs must be the same!") result = np.zeros(x.shape, dtype='int32') for i in range(len(x)): for j in range(len(x[0])): result[i][j] = x[i][j] + y[i][j] return result def create_tmp_var(name, dtype, shape): return paddle.static.default_main_program().current_block().create_var( name=name, dtype=dtype, shape=shape) def py_func_demo(): start_program = paddle.static.default_startup_program() main_program = paddle.static.default_main_program() # Input of the forward function x = paddle.static.data(name='x', shape=[2,3], dtype='int32') y = paddle.static.data(name='y', shape=[2,3], dtype='int32') # Output of the forward function, name/dtype/shape must be specified output = create_tmp_var('output','int32', [3,1]) # Multiple Variable should be passed in the form of tuple(Variale) or list[Variale] paddle.static.py_func(func=element_wise_add, x=[x,y], out=output) exe=paddle.static.Executor(paddle.CPUPlace()) exe.run(start_program) # Feed numpy array to main_program input1 = np.random.randint(1, 10, size=[2,3], dtype='int32') input2 = np.random.randint(1, 10, size=[2,3], dtype='int32') out = exe.run(main_program, feed={'x':input1, 'y':input2}, fetch_list=[output.name]) print("{0} + {1} = {2}".format(input1, input2, out)) py_func_demo() # Reference output: # [[5, 9, 9] + [[7, 8, 4] = [array([[12, 17, 13] # [7, 5, 2]] [1, 3, 3]] [8, 8, 5]], dtype=int32)] """ helper = LayerHelper('py_func', **locals()) check_type(x, 'X', (list, tuple, Variable, type(None)), 'py_func') if x is None: x = [] elif isinstance(x, Variable): x = [x] elif isinstance(x, tuple): x = list(x) elif not isinstance(x, (list, tuple, Variable)): raise TypeError('Input must be Variable/list(Variable)/tuple(Variable)') check_type(out, 'Out', (list, tuple, Variable, type(None)), 'py_func') if out is None: out_list = [] elif isinstance(out, Variable): out_list = [out] elif isinstance(out, tuple): out_list = list(out) elif isinstance(out, list): out_list = out else: raise TypeError( 'Output must be Variable/list(Variable)/tuple(Variable)') fwd_func_id = PyFuncRegistry(func).id bwd_func_id = PyFuncRegistry( backward_func).id if backward_func is not None else -1 for each_out in out_list: if len(each_out.shape) == 0: raise ValueError( 'Output shapes of py_func op should be provided by users manually' ) backward_skip_vars = set() if backward_func is not None and skip_vars_in_backward_input is not None: if isinstance(skip_vars_in_backward_input, Variable): skip_vars_in_backward_input = [skip_vars_in_backward_input] fwd_in_out = [v.name for v in x] fwd_in_out.extend([v.name for v in out_list]) fwd_in_out = set(fwd_in_out) backward_skip_vars = set() for v in skip_vars_in_backward_input: if not v.name in fwd_in_out: raise ValueError( 'Variable {} is not found in forward inputs and outputs' .format(v.name)) backward_skip_vars.add(v.name) helper.append_op( type='py_func', inputs={'X': x}, outputs={'Out': out_list}, attrs={ 'forward_callable_id': fwd_func_id, 'backward_callable_id': bwd_func_id, 'backward_skip_vars': list(backward_skip_vars) }) return out # For debug usage py_func.registered_func = PyFuncRegistry.registered_func py_func.registered_func_num = PyFuncRegistry.registered_func_num @templatedoc() def psroi_pool(input, rois, output_channels, spatial_scale, pooled_height, pooled_width, name=None): """ ${comment} Parameters: input (Variable): ${x_comment} rois (Variable): LoDTensor, ROIs (Regions of Interest) to pool over.It should be a 2-D LoDTensor of shape (num_rois, 4), the lod level is 1. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates. The data type is the same as `input` output_channels (int): ${output_channels_comment} spatial_scale (float): ${spatial_scale_comment} Default: 1.0 pooled_height (int): ${pooled_height_comment} Default: 1 pooled_width (int): ${pooled_width_comment} Default: 1 name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: ${out_comment}. Return Type: Variable Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() x = fluid.data(name='x', shape=[100, 490, 28, 28], dtype='float32') rois = fluid.data(name='rois', shape=[None, 4], lod_level=1, dtype='float32') pool_out = fluid.layers.psroi_pool(x, rois, 10, 1.0, 7, 7) """ helper = LayerHelper('psroi_pool', **locals()) # check attrs if not isinstance(output_channels, int): raise TypeError("output_channels must be int type") if not isinstance(spatial_scale, float): raise TypeError("spatial_scale must be float type") if not isinstance(pooled_height, int): raise TypeError("pooled_height must be int type") if not isinstance(pooled_width, int): raise TypeError("pooled_width must be int type") dtype = helper.input_dtype() out = helper.create_variable_for_type_inference(dtype) helper.append_op( type='psroi_pool', inputs={'X': input, 'ROIs': rois}, outputs={'Out': out}, attrs={ 'output_channels': output_channels, 'spatial_scale': spatial_scale, 'pooled_height': pooled_height, 'pooled_width': pooled_width }) return out @templatedoc() def prroi_pool(input, rois, spatial_scale=1.0, pooled_height=1, pooled_width=1, batch_roi_nums=None, name=None): """ The precise roi pooling implementation for paddle. Reference: https://arxiv.org/pdf/1807.11590.pdf Args: input (Variable):The input of precise roi pooliing.The shape of input tensor is [N,C,H,W]. Where N is batch size,C is number of input channels,H is height of the feature, and W is the width of the feature. rois (Variable): ROIs (Regions of Interest) to pool over.It should be a 2-D LoDTensor or Tensor of shape (num_rois, 4), the lod level is 1 when it is LoDTensor. The LoD include the rois's batch index information. If rois is Tensor, its batch index information should be provided by batch_index. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates. spatial_scale (float): Ratio of input feature map height (or width) to raw image height (or width). Equals the reciprocal of total stride in convolutional layers, Default: 1.0. pooled_height (integer): The pooled output height. Default: 1. pooled_width (integer): The pooled output width. Default: 1. batch_roi_nums (Variable): The number of roi for each image in batch. It should be 1-D Tensor, with shape [N] and dtype int64, where N is the batch size. Default: None. Be note: The lod of input should be empty when batch_roi_nums has values; name (str, default None): The name of this operation. Returns: Variable(Tensor):The shape of the returned Tensor is (N, C, pooled_height, pooled_width), with value type float32,float16. N, C denote batch_size and channels of input respectively. Examples: .. code-block:: python ## prroi_pool without batch_roi_num import paddle.fluid as fluid x = fluid.data(name='x', shape=[None, 490, 28, 28], dtype='float32') rois = fluid.data(name='rois', shape=[None, 4], lod_level=1, dtype='float32') pool_out = fluid.layers.prroi_pool(x, rois, 1.0, 7, 7) ## prroi_pool with batch_roi_num batchsize=4 x2 = fluid.data(name='x2', shape=[batchsize, 490, 28, 28], dtype='float32') rois2 = fluid.data(name='rois2', shape=[batchsize, 4], dtype='float32') batch_rois_num = fluid.data(name='rois_nums', shape=[batchsize], dtype='int64') pool_out2 = fluid.layers.prroi_pool(x2, rois2, 1.0, 7, 7, batch_roi_nums=batch_rois_num) """ check_variable_and_dtype(input, 'input', ['float32'], 'prroi_pool') check_variable_and_dtype(rois, 'rois', ['float32'], 'prroi_pool') helper = LayerHelper('prroi_pool', **locals()) # check attrs if not isinstance(spatial_scale, float): raise TypeError("spatial_scale must be float type") if not isinstance(pooled_height, int): raise TypeError("pooled_height must be int type") if not isinstance(pooled_width, int): raise TypeError("pooled_width must be int type") dtype = helper.input_dtype() out = helper.create_variable_for_type_inference(dtype) inputs_op = {'X': input, 'ROIs': rois} if batch_roi_nums is not None: inputs_op['BatchRoINums'] = batch_roi_nums helper.append_op( type='prroi_pool', inputs=inputs_op, outputs={'Out': out}, attrs={ 'spatial_scale': spatial_scale, 'pooled_height': pooled_height, 'pooled_width': pooled_width }) return out def pixel_shuffle(x, upscale_factor): """ This op rearranges elements in a tensor of shape [N, C, H, W] to a tensor of shape [N, C/r**2, H*r, W*r]. This is useful for implementing efficient sub-pixel convolution with a stride of 1/r. Please refer to the paper: `Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network <https://arxiv.org/abs/1609.05158v2>`_ . by Shi et. al (2016) for more details. Parameters: x(Variable): 4-D tensor, the data type should be float32 or float64. upscale_factor(int): factor to increase spatial resolution. Returns: Out(Variable): Reshaped tensor according to the new dimension. Raises: ValueError: If the square of upscale_factor cannot divide the channels of input. Examples: .. code-block:: python # declarative mode import paddle.fluid as fluid import numpy as np input = fluid.data(name="input", shape=[2,9,4,4]) output = fluid.layers.pixel_shuffle(x=input, upscale_factor=3) place = fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) input_data = np.random.rand(2,9,4,4).astype("float32") output_data = exe.run(fluid.default_main_program(), feed={"input":input_data}, fetch_list=[output], return_numpy=True) # print(output.shape) # (2L, 1L, 12L, 12L) """ check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'pixel_shuffle') helper = LayerHelper("pixel_shuffle", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) if not isinstance(upscale_factor, int): raise TypeError("upscale factor must be int type") helper.append_op( type="pixel_shuffle", inputs={"X": x}, outputs={"Out": out}, attrs={"upscale_factor": upscale_factor}) return out def fsp_matrix(x, y): """ **FSP matrix op** This op is used to calculate the flow of solution procedure (FSP) matrix of two 4-D Tensor feature maps. Given feature map x with shape [x_channel, h, w] and feature map y with shape [y_channel, h, w], we can get the fsp matrix of x and y in two steps: 1. reshape x into matrix with shape [x_channel, h * w] and reshape and transpose y into matrix with shape [h * w, y_channel]. 2. multiply x and y to get fsp matrix with shape [x_channel, y_channel]. The output is a batch of fsp matrices. Args: x (Variable): A 4-D Tensor feature map with shape [batch_size, x_channel, height, width]. A Tensor with type float32, float64. y (Variable): A 4-D Tensor feature map with shape [batch_size, y_channel, height, width]. The y_channel can be different with the x_channel of Input(X) while the other dimensions must be the same with Input(X)'s. A Tensor with type float32, float64. Returns: fsp matrix (Variable): The output of FSP op with shape [batch_size, x_channel, y_channel]. The x_channel is the channel of x and the y_channel is the channel of y. A Tensor with type float32, float64. Examples: .. code-block:: python import paddle.fluid as fluid data = fluid.data(name='data', shape=[None, 3, 32, 32]) feature_map_0 = fluid.layers.conv2d(data, num_filters=2, filter_size=3) feature_map_1 = fluid.layers.conv2d(feature_map_0, num_filters=2, filter_size=1) loss = fluid.layers.fsp_matrix(feature_map_0, feature_map_1) """ check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'fsp_matrix') check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'fsp_matrix') helper = LayerHelper('fsp_matrix', **locals()) out = helper.create_variable_for_type_inference(dtype=helper.input_dtype( input_param_name='x')) helper.append_op(type='fsp', inputs={'X': x, 'Y': y}, outputs={'Out': out}) return out def continuous_value_model(input, cvm, use_cvm=True): r""" **continuous_value_model layers** Now, this OP is used in CTR project to remove or dispose show and click value in :attr:`input`. :attr:`input` is an embedding vector including show and click value, whose shape is :math:`[N, D]` (N is batch size. D is `2 + embedding dim` ). Show and click at first two dims of embedding vector D. If :attr:`use_cvm` is True, it will calculate :math:`log(show)` and :math:`log(click)` , and output shape is :math:`[N, D]` . If :attr:`use_cvm` is False, it will remove show and click from :attr:`input` , and output shape is :math:`[N, D - 2]` . :attr:`cvm` is show_click info, whose shape is :math:`[N, 2]` . Args: input (Variable): The input variable. A 2-D LoDTensor with shape :math:`[N, D]` , where N is the batch size, D is `2 + the embedding dim` . `lod level = 1` . A Tensor with type float32, float64. cvm (Variable): Show and click variable. A 2-D Tensor with shape :math:`[N, 2]` , where N is the batch size, 2 is show and click. A Tensor with type float32, float64. use_cvm (bool): Use show_click or not. if use, the output dim is the same as input. if not use, the output dim is `input dim - 2` (remove show and click) Returns: Variable: A 2-D LodTensor with shape :math:`[N, M]` . if :attr:`use_cvm` = True, M is equal to input dim D. if False, M is equal to `D - 2`. \ A Tensor with same type as input. Examples: .. code-block:: python import paddle.fluid as fluid input = fluid.data(name="input", shape=[64, 1], dtype="int64") label = fluid.data(name="label", shape=[64, 1], dtype="int64") embed = fluid.layers.embedding( input=input, size=[100, 11], dtype='float32') ones = fluid.layers.fill_constant_batch_size_like(input=label, shape=[-1, 1], dtype="int64", value=1) show_clk = fluid.layers.cast(fluid.layers.concat([ones, label], axis=1), dtype='float32') show_clk.stop_gradient = True input_with_cvm = fluid.layers.continuous_value_model(embed, show_clk, True) """ helper = LayerHelper('cvm', **locals()) out = helper.create_variable(dtype=input.dtype) check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'], 'cvm') helper.append_op( type='cvm', inputs={'X': [input], 'CVM': [cvm]}, outputs={'Y': [out]}, attrs={"use_cvm": use_cvm}) return out def where(condition): """ Return an int64 tensor with rank 2, specifying the coordinate of true element in `condition`. Args: condition(Variable): A bool tensor with rank at least 1, the data type is bool. Returns: Variable, the output data type is int64. : The tensor variable storing a 2-D tensor, which involves all coordinate. Examples: .. code-block:: python import paddle.fluid as fluid import paddle.fluid.layers as layers import numpy as np # condition is a tensor [True, False, True] condition = layers.assign(np.array([1, 0, 1], dtype='int32')) condition = layers.cast(condition, 'bool') out = layers.where(condition) # [[0], [2]] # condition is a tensor [[True, False], [False, True]] condition = layers.assign(np.array([[1, 0], [0, 1]], dtype='int32')) condition = layers.cast(condition, 'bool') out = layers.where(condition) # [[0, 0], [1, 1]] # condition is a tensor [False, False, False] condition = layers.assign(np.array([0, 0, 0], dtype='int32')) condition = layers.cast(condition, 'bool') out = layers.where(condition) # [[]] """ if in_dygraph_mode(): return _C_ops.where_index(condition) helper = LayerHelper("where_index", **locals()) out = helper.create_variable_for_type_inference( dtype=core.VarDesc.VarType.INT64) helper.append_op( type='where_index', inputs={'Condition': condition}, outputs={'Out': [out]}) return out @deprecated(since="2.0.0", update_to="paddle.sign") def sign(x): r""" This OP returns sign of every element in `x`: 1 for positive, -1 for negative and 0 for zero. Args: x(Variable|numpy.ndarray): The input variable could be N-D tensor or N-D numpy array, \ the input data type is float32 or float64. Returns: Variable, the output data type is the same as input data type. : The output sign tensor with identical shape to input :attr:`x`. Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np # [1.0, 0.0, -1.0] data = fluid.layers.sign(np.array([3.0, 0.0, -2.0], dtype='float32')) """ helper = LayerHelper("sign", **locals()) check_type(x, 'x', (Variable, np.ndarray), 'sign') if isinstance(x, np.ndarray): x = assign(x) check_dtype(x.dtype, 'x', ['float16', 'float32', 'float64'], 'sign') out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op(type='sign', inputs={'X': [x]}, outputs={'Out': [out]}) return out def unique(x, dtype='int32'): r""" Return a unique tensor for `x` and an index tensor pointing to this unique tensor. Args: x(Tensor): A 1-D input tensor, it's data type should be float32, float64, int32, int64. dtype(np.dtype|str, optional): The type of index tensor: int32, int64. Default: int32. Returns: tuple: (out, index). `out` is the unique tensor for `x`, with identical dtype to `x`, and \ `index` is an index tensor pointing to `out`, by which user can recover the original `x` tensor. Examples: .. code-block:: python import numpy as np import paddle.fluid as fluid x = fluid.layers.assign(np.array([2, 3, 3, 1, 5, 3], dtype='int32')) out, index = fluid.layers.unique(x) # out is [2, 3, 1, 5]; index is [0, 1, 1, 2, 3, 1] """ check_variable_and_dtype(x, "x", ['float32', 'float64', 'int32', 'int64'], "unique") helper = LayerHelper("unique", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) index = helper.create_variable_for_type_inference(dtype) helper.append_op( type='unique', inputs={'X': x}, attrs={'dtype': convert_np_dtype_to_dtype_(dtype)}, outputs={'Out': [out], 'Index': [index]}) return out, index def unique_with_counts(x, dtype='int32'): r""" This OP return a unique tensor for `x` , and count tensor that the count of unique result in raw input, \ and an index tensor pointing to this unique tensor. **NOTICE**: This op support the variable type of Tensor only. Args: x(Variable): A 1-D input tensor with input shape of :math:`[N]` , the input data type is float32, float64, int32, int64. dtype(np.dtype|core.VarDesc.VarType|str): The type of count and index tensor, it could be int32, int64. Defalut value is int32. Returns: tuple, the variable type in tuple is Tensor, the output :attr:`out` data type is the same as input :attr:`x`, \ and data type of output :attr:`index` and :attr:`count` will be int32 or int64.: The :attr:`out` is unique tensor for input :attr:`x`,\ the data shape is :math:`[K]`, the `K` may be different to the `N` in shape of :attr:`x`. :attr:`index` is an index tensor pointing\ to :attr:`out`, the data shape is :math:`[N]` , the data shape is the same as input :attr:`x`. :attr:`count` is count of unique element in\ the :attr:`x`, the data shape is :math:`[K]`, the data shape is the same as output :attr:`out`. Examples: .. code-block:: python import numpy as np import paddle.fluid as fluid x = fluid.layers.assign(np.array([2, 3, 3, 1, 5, 3], dtype='int32')) out, index, count = fluid.layers.unique_with_counts(x) # out is [2, 3, 1, 5]; index is [0, 1, 1, 2, 3, 1] # count is [1, 3, 1, 1] # x.shape=(6,) out.shape=(4,), index.shape=(6,), count.shape=(4,) """ check_variable_and_dtype(x, "x", ['float32', 'float64', 'int32', 'int64'], "unique_with_counts") if not (dtype == 'int32' or dtype == 'int64'): raise TypeError( "Op unique_with_counts, index dtype must be int32 or int64") if x is None or len(x.shape) != 1: raise ValueError( "Op unique_with_counts, x must not be null and size of dim must be 1" ) helper = LayerHelper("unique_with_counts", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) index = helper.create_variable_for_type_inference(dtype) count = helper.create_variable_for_type_inference(dtype) helper.append_op( type='unique_with_counts', inputs={'X': x}, attrs={'dtype': convert_np_dtype_to_dtype_(dtype)}, outputs={'Out': [out], 'Index': [index], 'Count': [count]}) return out, index, count def deformable_conv(input, offset, mask, num_filters, filter_size, stride=1, padding=0, dilation=1, groups=None, deformable_groups=None, im2col_step=None, param_attr=None, bias_attr=None, modulated=True, name=None): r""" :api_attr: Static Graph **Deformable Convolution op** Compute 2-D deformable convolution on 4-D input. Given input image x, output feature map y, the deformable convolution operation can be expressed as follow: Deformable Convolution v2: .. math:: y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k) * \Delta m_k} Deformable Convolution v1: .. math:: y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k)} Where :math:`\Delta p_k` and :math:`\Delta m_k` are the learnable offset and modulation scalar for the k-th location, Which :math:`\Delta m_k` is one in deformable convolution v1. Please refer to `Deformable ConvNets v2: More Deformable, Better Results <https://arxiv.org/abs/1811.11168v2>`_ and `Deformable Convolutional Networks <https://arxiv.org/abs/1703.06211>`_. Example: - Input: Input shape: :math:`(N, C_{in}, H_{in}, W_{in})` Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)` Offset shape: :math:`(N, 2 * deformable\_groups * H_f * H_w, H_{in}, W_{in})` Mask shape: :math:`(N, deformable\_groups * H_f * H_w, H_{in}, W_{in})` - Output: Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` Where .. math:: H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\ W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1 Args: input (Variable): The input image with [N, C, H, W] format. A Tensor with type float32, float64. offset (Variable): The input coordinate offset of deformable convolution layer. A Tensor with type float32, float64. Mask (Variable, Optional): The input mask of deformable convolution layer. A Tensor with type float32, float64. It should be None when you use deformable convolution v1. num_filters(int): The number of filter. It is as same as the output image channel. filter_size (int|tuple): The filter size. If filter_size is a tuple, it must contain two integers, (filter_size_H, filter_size_W). Otherwise, the filter will be a square. stride (int|tuple): The stride size. If stride is a tuple, it must contain two integers, (stride_H, stride_W). Otherwise, the stride_H = stride_W = stride. Default: stride = 1. padding (int|tuple): The padding size. If padding is a tuple, it must contain two integers, (padding_H, padding_W). Otherwise, the padding_H = padding_W = padding. Default: padding = 0. dilation (int|tuple): The dilation size. If dilation is a tuple, it must contain two integers, (dilation_H, dilation_W). Otherwise, the dilation_H = dilation_W = dilation. Default: dilation = 1. groups (int): The groups number of the deformable conv layer. According to grouped convolution in Alex Krizhevsky's Deep CNN paper: when group=2, the first half of the filters is only connected to the first half of the input channels, while the second half of the filters is only connected to the second half of the input channels. Default: groups=1. deformable_groups (int): The number of deformable group partitions. Default: deformable_groups = 1. im2col_step (int): Maximum number of images per im2col computation; The total batch size should be devisable by this value or smaller than this value; if you face out of memory problem, you can try to use a smaller value here. Default: im2col_step = 64. param_attr (ParamAttr, Optional): The parameter attribute for learnable parameters/weights of deformable conv. If it is set to None or one attribute of ParamAttr, deformable conv will create ParamAttr as param_attr. If the Initializer of the param_attr is not set, the parameter is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None. bias_attr (ParamAttr|bool, Optional): The parameter attribute for the bias of deformable conv layer. If it is set to False, no bias will be added to the output units. If it is set to None or one attribute of ParamAttr, conv2d will create ParamAttr as bias_attr. If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. modulated (bool): Make sure which version should be used between v1 and v2, where v2 is \ used while True. Default: True. name(str, Optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. Returns: Variable: The tensor variable storing the deformable convolution \ result. A Tensor with type float32, float64. Raises: ValueError: If the shapes of input, filter_size, stride, padding and groups mismatch. Examples: .. code-block:: python #deformable conv v2: import paddle.fluid as fluid import paddle paddle.enable_static() C_in, H_in, W_in = 3, 32, 32 filter_size, deformable_groups = 3, 1 data = fluid.data(name='data', shape=[None, C_in, H_in, W_in], dtype='float32') offset = fluid.data(name='offset', shape=[None, 2*deformable_groups*filter_size**2, H_in, W_in], dtype='float32') mask = fluid.data(name='mask', shape=[None, deformable_groups*filter_size**2, H_in, W_in], dtype='float32') out = fluid.layers.deformable_conv(input=data, offset=offset, mask=mask, num_filters=2, filter_size=filter_size, padding=1, modulated=True) #deformable conv v1: import paddle.fluid as fluid C_in, H_in, W_in = 3, 32, 32 filter_size, deformable_groups = 3, 1 data = fluid.data(name='data', shape=[None, C_in, H_in, W_in], dtype='float32') offset = fluid.data(name='offset', shape=[None, 2*deformable_groups*filter_size**2, H_in, W_in], dtype='float32') out = fluid.layers.deformable_conv(input=data, offset=offset, mask=None, num_filters=2, filter_size=filter_size, padding=1, modulated=False) """ check_variable_and_dtype(input, "input", ['float32', 'float64'], 'deformable_conv') check_variable_and_dtype(offset, "offset", ['float32', 'float64'], 'deformable_conv') check_type(mask, 'mask', (Variable, type(None)), 'deformable_conv') num_channels = input.shape[1] assert param_attr is not False, "param_attr should not be False here." helper = LayerHelper('deformable_conv', **locals()) dtype = helper.input_dtype() if not isinstance(input, Variable): raise TypeError("Input of deformable_conv must be Variable") if not isinstance(offset, Variable): raise TypeError("Input Offset of deformable_conv must be Variable") if groups is None: num_filter_channels = num_channels else: if num_channels % groups != 0: raise ValueError("num_channels must be divisible by groups.") num_filter_channels = num_channels // groups filter_size = utils.convert_to_list(filter_size, 2, 'filter_size') stride = utils.convert_to_list(stride, 2, 'stride') padding = utils.convert_to_list(padding, 2, 'padding') dilation = utils.convert_to_list(dilation, 2, 'dilation') input_shape = input.shape filter_shape = [num_filters, int(num_filter_channels)] + filter_size def _get_default_param_initializer(): filter_elem_num = filter_size[0] * filter_size[1] * num_channels if filter_elem_num <= 0: raise ValueError( "Invalid filter number, excepted number is larger than 0, but" " received {}, please check the input shape and " "filter size.".format(filter_elem_num)) std = (2.0 / filter_elem_num)**0.5 return Normal(0.0, std, 0) filter_param = helper.create_parameter( attr=helper.param_attr, shape=filter_shape, dtype=dtype, default_initializer=_get_default_param_initializer()) pre_bias = helper.create_variable_for_type_inference(dtype) if modulated: helper.append_op( type='deformable_conv', inputs={ 'Input': input, 'Filter': filter_param, 'Offset': offset, 'Mask': mask, }, outputs={"Output": pre_bias}, attrs={ 'strides': stride, 'paddings': padding, 'dilations': dilation, 'groups': groups, 'deformable_groups': deformable_groups, 'im2col_step': im2col_step, }) else: helper.append_op( type='deformable_conv_v1', inputs={ 'Input': input, 'Filter': filter_param, 'Offset': offset, }, outputs={"Output": pre_bias}, attrs={ 'strides': stride, 'paddings': padding, 'dilations': dilation, 'groups': groups, 'deformable_groups': deformable_groups, 'im2col_step': im2col_step, }) output = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2) return output def unfold(x, kernel_sizes, strides=1, paddings=0, dilations=1, name=None): r""" This op returns a col buffer of sliding local blocks of input x, also known as im2col for batched 2D image tensors. For each block under the convolution filter, all element will be rearranged as a column. While the convolution filter sliding over the input feature map, a series of such columns will be formed. For each input :math:`x` with shape [N, C, H, W], the output shape [N, Cout, Lout] can be calculated as following. .. math:: dkernel[0] &= dilations[0] \times (kernel\_sizes[0] - 1) + 1 dkernel[1] &= dilations[1] \times (kernel\_sizes[1] - 1) + 1 hout &= \frac{H + paddings[0] + paddings[2] - dkernel[0]}{strides[0]} + 1 wout &= \frac{W + paddings[1] + paddings[3] - dkernel[1]}{strides[1]} + 1 Cout &= C \times kernel\_sizes[0] \times kernel\_sizes[1] Lout &= hout \times wout Parameters: x(Tensor): 4-D Tensor, input tensor of format [N, C, H, W], data type can be float32 or float64 kernel_sizes(int|list): The size of convolution kernel, should be [k_h, k_w] or an integer k treated as [k, k]. strides(int|list): The strides, should be [stride_h, stride_w] or an integer stride treated as [sride, stride]. For default, strides will be [1, 1]. paddings(int|list): The paddings of each dimension, should be [padding_top, padding_left, padding_bottom, padding_right] or [padding_h, padding_w] or an integer padding. If [padding_h, padding_w] was given, it will expanded to [padding_h, padding_w, padding_h, padding_w]. If an integer padding was given, [padding, padding, padding, padding] will be used. For default, paddings will be [0, 0, 0, 0] dilations(int|list): the dilations of convolution kernel, should be [dilation_h, dilation_w], or an integer dilation treated as [dilation, dilation]. For default, it will be [1, 1]. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: The tensor corresponding to the sliding local blocks. The output shape is [N, Cout, Lout] as decriabled above. Cout is the total number of values within each block, and Lout is the total number of such blocks. The data type of output is the same as the input :math:`x` Return Type: Tensor Examples: .. code-block:: python import paddle import paddle.nn.functional as F x = paddle.randn((100,3,224,224)) y = F.unfold(x, [3, 3], 1, 1, 1) """ helper = LayerHelper("unfold", **locals()) check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'unfold') assert len(x.shape) == 4, \ "input should be the format of [N, C, H, W]" if isinstance(kernel_sizes, int): kernel_sizes = [kernel_sizes, kernel_sizes] else: assert isinstance(kernel_sizes, list) and (len(kernel_sizes) == 2), \ "kernel_sizes should either be an integer or a list of two integers" if isinstance(strides, int): strides = [strides, strides] else: assert isinstance(strides, list) and (len(strides) == 2), \ "strides should either be an integer or a list of two integers" if isinstance(dilations, int): dilations = [dilations, dilations] else: assert isinstance(dilations, list) and (len(dilations) == 2), \ "dilations should either be an integer or a list of two integers" if isinstance(paddings, int): paddings = [paddings] * 4 elif isinstance(paddings, list): if len(paddings) == 2: paddings = paddings * 2 elif len(paddings) == 4: pass else: raise ValueError( "paddings should either be an integer or a list of 2 or 4 integers" ) else: raise ValueError( "Unexpected type of paddings, it should be either an integer or a list" "of 2 or 4 integers") out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type="unfold", inputs={"X": x}, outputs={"Y": out}, attrs={ "kernel_sizes": kernel_sizes, "strides": strides, "paddings": paddings, "dilations": dilations }) return out def deformable_roi_pooling(input, rois, trans, no_trans=False, spatial_scale=1.0, group_size=[1, 1], pooled_height=1, pooled_width=1, part_size=None, sample_per_part=1, trans_std=0.1, position_sensitive=False, name=None): r""" Deformable ROI Pooling Layer Performs deformable region-of-interest pooling on inputs. As described in `Deformable Convolutional Networks <https://arxiv.org/abs/1703.06211>`_, it will get offset for each bin after roi pooling so that pooling at correct region. Batch_size will change to the number of region bounding boxes after deformable_roi_pooling. The operation has three steps: 1. Dividing each region proposal into equal-sized sections with the pooled_width and pooled_height. 2. Add offset to pixel in ROI to get new location and the new value which are computed directly through bilinear interpolation with four nearest pixel. 3. Sample several points in each bin to get average values as output. Args: input (Variable):The input of deformable roi pooling and it is tensor which value type is float32. The shape of input is [N, C, H, W]. Where N is batch size, C is number of input channels, H is height of the feature, and W is the width of the feature. rois (Variable): ROIs (Regions of Interest) with type float32 to pool over. It should be a 2-D LoDTensor of shape (num_rois, 4), and the lod level is 1. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates, which value type is float32. trans (Variable): Offset of features on ROIs while pooling which value type is float32. The format is [N, C, H, W], where N is number of ROIs, C is number of channels, which indicate the offset distance in the x and y directions, H is pooled height, and W is pooled width. no_trans (bool): Whether to add offset to get new value or not while roi pooling, which value with type bool is True or False. If value is True, no offset will be added in operation. Default: False. spatial_scale (float): Ratio of input feature map height (or width) to raw image height (or width), which value type is float32. Equals the reciprocal of total stride in convolutional layers, Default: 1.0. group_size (list|tuple): The number of groups which input channels are divided and the input is list or tuple, which value type is int32. (eg.number of input channels is k1 * k2 * (C + 1), which k1 and k2 are group width and height and C+1 is number of output channels.) eg.(4, 6), which 4 is height of group and 6 is width of group. Default: [1, 1]. pooled_height (int): The pooled output height which value type is int32. Default: 1. pooled_width (int): The pooled output width which value type is int32. Default: 1. part_size (list|tuple): The height and width of offset which values in list or tuple is int32, eg.(4, 6), which height is 4 and width is 6, and values always equal to pooled_height \ and pooled_width. Default: if None, default value is [pooled_height, pooled_width]. sample_per_part (int): The number of samples in each bin which value type is int32. If value is bigger, it will consume more performance. Default: 1. trans_std (float): Coefficient of offset which value type is float32. It controls weight of offset. Default: 0.1. position_sensitive (bool): Whether to choose deformable psroi pooling mode or not, and value type is bool(True or False). If value is False, input dimension equals to output dimension. \ If value is True, input dimension should be output dimension * pooled_height * pooled_width. Default: False. name (str|None): Name of layer. Default: None. Returns: Variable: Output of deformable roi pooling is that, if position sensitive is False, input dimension equals to output dimension. If position sensitive is True,\ input dimension should be the result of output dimension divided by pooled height and pooled width. Examples: .. code-block:: python # position_sensitive=True import paddle.fluid as fluid input = fluid.data(name="input", shape=[2, 192, 64, 64], dtype='float32') rois = fluid.data(name="rois", shape=[-1, 4], dtype='float32', lod_level=1) trans = fluid.data(name="trans", shape=[2, 384, 64, 64], dtype='float32') x = fluid.layers.deformable_roi_pooling(input=input, rois=rois, trans=trans, no_trans=False, spatial_scale=1.0, group_size=(1, 1), pooled_height=8, pooled_width=8, part_size=(8, 8), sample_per_part=4, trans_std=0.1, position_sensitive=True) # position_sensitive=False import paddle.fluid as fluid input = fluid.data(name="input", shape=[2, 192, 64, 64], dtype='float32') rois = fluid.data(name="rois", shape=[-1, 4], dtype='float32', lod_level=1) trans = fluid.data(name="trans", shape=[2, 384, 64, 64], dtype='float32') x = fluid.layers.deformable_roi_pooling(input=input, rois=rois, trans=trans, no_trans=False, spatial_scale=1.0, group_size=(1, 1), pooled_height=8, pooled_width=8, part_size=(8, 8), sample_per_part=4, trans_std=0.1, position_sensitive=False) """ check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'deformable_roi_pooling') check_variable_and_dtype(rois, 'rois', ['float32', 'float64'], 'deformable_roi_pooling') check_variable_and_dtype(trans, 'trans', ['float32', 'float64'], 'deformable_roi_pooling') check_type(group_size, 'group_size', (list, tuple), 'deformable_roi_pooling') if part_size is not None: check_type(part_size, 'part_size', (list, tuple), 'deformable_roi_pooling') input_channels = input.shape[1] if position_sensitive == False: output_channels = input_channels else: output_channels = input_channels / pooled_height / pooled_width if part_size is None: part_height = pooled_height part_width = pooled_width part_size = [part_height, part_width] part_size = utils.convert_to_list(part_size, 2, 'part_size') group_size = utils.convert_to_list(group_size, 2, 'group_size') helper = LayerHelper('deformable_psroi_pooling', **locals()) dtype = helper.input_dtype() output = helper.create_variable_for_type_inference(dtype) top_count = helper.create_variable_for_type_inference(dtype='int32') helper.append_op( type="deformable_psroi_pooling", inputs={"Input": input, "ROIs": rois, "Trans": trans}, outputs={"Output": output, "TopCount": top_count}, attrs={ "no_trans": no_trans, "spatial_scale": spatial_scale, "output_dim": output_channels, "group_size": group_size, "pooled_height": pooled_height, "pooled_width": pooled_width, "part_size": part_size, "sample_per_part": sample_per_part, "trans_std": trans_std }) return output @deprecated(since="2.0.0", update_to="paddle.shard_index") def shard_index(input, index_num, nshards, shard_id, ignore_value=-1): """ Reset the values of `input` according to the shard it beloning to. Every value in `input` must be a non-negative integer, and the parameter `index_num` represents the integer above the maximum value of `input`. Thus, all values in `input` must be in the range [0, index_num) and each value can be regarded as the offset to the beginning of the range. The range is further split into multiple shards. Specifically, we first compute the `shard_size` according to the following formula, which represents the number of integers each shard can hold. So for the i'th shard, it can hold values in the range [i*shard_size, (i+1)*shard_size). :: shard_size = (index_num + nshards - 1) // nshards For each value `v` in `input`, we reset it to a new value according to the following formula: :: v = v - shard_id * shard_size if shard_id * shard_size <= v < (shard_id+1) * shard_size else ignore_value That is, the value `v` is set to the new offset within the range represented by the shard `shard_id` if it in the range. Otherwise, we reset it to be `ignore_value`. Args: input (Tensor): Input tensor with data type int64 or int32. It's last dimension must be 1. index_num (int): An integer represents the integer above the maximum value of `input`. nshards (int): The number of shards. shard_id (int): The index of the current shard. ignore_value (int): An integer value out of sharded index range. Returns: Tensor. Examples: .. code-block:: python import paddle label = paddle.to_tensor([[16], [1]], "int64") shard_label = paddle.shard_index(input=label, index_num=20, nshards=2, shard_id=0) print(shard_label) # [[-1], [1]] """ check_variable_and_dtype(input, 'input', ['int64', 'int32'], 'shard_index') op_type = 'shard_index' helper = LayerHelper(op_type, **locals()) if shard_id < 0 or shard_id >= nshards: raise ValueError('The shard_id(%d) should be in [0, %d)' % (shard_id, nshards)) out = helper.create_variable_for_type_inference(dtype=input.dtype) helper.append_op( type=op_type, inputs={'X': [input]}, outputs={'Out': out}, attrs={ 'index_num': index_num, 'nshards': nshards, 'shard_id': shard_id, 'ignore_value': ignore_value }, stop_gradient=True) return out @templatedoc() def hard_swish(x, threshold=6.0, scale=6.0, offset=3.0, name=None): r""" This operator implements the hard_swish activation function. Hard_swish is proposed in MobileNetV3, and performs better in computational stability and efficiency compared to swish function. For more details please refer to: https://arxiv.org/pdf/1905.02244.pdf The formula is as follows: .. math:: out = \\frac{x * (min(max(0, x+offset), threshold))}{scale} In the above equation: ``threshold`` and ``scale`` should be positive, ``offset`` can be positive or negative. It is recommended to use default parameters. Args: x (Variable): Input feature, multi-dimensional Tensor. The data type should be float32 or float64. threshold (float, optional): The threshold in Relu function. Default: 6.0 scale (float, optional): The scale factor. Default: 6.0 offset (float, optional): The offset factor. Default: 3.0 name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Variable: The output tensor with the same shape and data type as input. Examples: .. code-block:: python import paddle.fluid as fluid import paddle import numpy as np paddle.enable_static() DATATYPE='float32' x_data = np.array([i for i in range(1,5)]).reshape([1,1,4]).astype(DATATYPE) x = fluid.data(name="x", shape=[None,1,4], dtype=DATATYPE) y = fluid.layers.hard_swish(x) place = fluid.CPUPlace() #place = fluid.CUDAPlace(0) exe = fluid.Executor(place) out, = exe.run(feed={'x':x_data}, fetch_list=[y.name]) print(out) # [[0.66666667, 1.66666667,3., 4.]] """ if in_dygraph_mode(): return _C_ops.hard_swish(x, 'threshold', threshold, 'scale', scale, 'offset', offset) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'hard_swish') helper = LayerHelper('hard_swish', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='hard_swish', inputs={'X': x}, outputs={'Out': out}, attrs={'threshold': threshold, 'scale': scale, 'offset': offset}) return out @templatedoc() def mish(x, threshold=20, name=None): r""" This operator implements the mish activation function. Refer to `Mish: A Self Regularized Non-Monotonic Neural Activation Function <https://arxiv.org/abs/1908.08681>`_ The formula is as follows if :attr:`threshold` is :code:`None` or negative: .. math:: out = x * \\tanh(\\ln(1 + e^{x})) The formula is as follows if :attr:`threshold` is set as positive value: .. math:: out = \\begin{cases} x \\ast \\tanh(x), \\text{if } x > \\text{threshold} \\\\ x \\ast \\tanh(e^{x}), \\text{if } x < -\\text{threshold} \\\\ x \\ast \\tanh(\\ln(1 + e^{x})), \\text{otherwise} \\end{cases} Args: x (Variable): Input feature, multi-dimensional Tensor. The data type should be float16, float32 or float64. threshold (float|None): threshold for softplus in Mish operator. Approximate value of softplus will be used if absolute value of input is greater than :attr:threshold and :attr:threshold is set as positive value. For none or negative threshold, approximate value is not used. Default 20. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Variable: The output tensor with the same shape and data type as input. Examples: .. code-block:: python import paddle.fluid as fluid import numpy as np DATATYPE='float32' x_data = np.array([i for i in range(1,5)]).reshape([1,1,4]).astype(DATATYPE) x = fluid.data(name="x", shape=[None,1,4], dtype=DATATYPE) y = fluid.layers.mish(x) place = fluid.CPUPlace() # place = fluid.CUDAPlace(0) exe = fluid.Executor(place) out, = exe.run(feed={'x':x_data}, fetch_list=[y.name]) print(out) # [[0.66666667, 1.66666667, 3., 4.]] """ check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'mish') check_type(threshold, 'threshold', (float, int), 'mish') assert threshold > 0, "threshold of mish should be greater than 0, " \ "but got {}".format(threshold) helper = LayerHelper('mish', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='mish', inputs={'X': x}, outputs={'Out': out}, attrs={'threshold': threshold or -1}) return out def gather_tree(ids, parents): r""" To be used after beam search. After beam search, we get selected ids at each time step and the corresponding parents in the search tree. Both ids and parents have the layout :attr:`[max_time, batch_size, beam_size]`. Then :attr:`gather_tree` is used to backtrace from the last time step and generate the full sequences by collecting selected ids. Here is an example: .. code-block:: text Given: ids = [[[2 2] [6 1]] [[3 9] [6 1]] [[0 1] [9 0]]] parents = [[[0 0] [1 1]] [[1 0] [1 0]] [[0 0] [0 1]]] Then: gather_tree(ids, parents) = [[[2 2] [1 6]] [[3 3] [6 1]] [[0 1] [9 0]]] Args: ids(Tensor): A Tensor with shape :attr:`[length, batch_size, beam_size]` and data type :attr:`int32` or :attr:`int64`. It contains the selected ids of all time steps. parents(Tensor): A Tensor with the same shape and data type as :attr:`ids`, It contains the parents corresponding to selected ids when searching among beams. Returns: A Tensor with the same shape and data type as :attr:`ids`. \ It contains the full sequences. The sequences are collected from \ :attr:`ids` by backtracing according to :attr:`parents`. Examples: .. code-block:: python import paddle ids = paddle.to_tensor([[[2, 2], [6, 1]], [[3, 9], [6, 1]], [[0, 1], [9, 0]]]) parents = paddle.to_tensor([[[0, 0], [1, 1]], [[1, 0], [1, 0]], [[0, 0], [0, 1]]]) final_sequences = paddle.nn.functional.gather_tree(ids, parents) # [[[2, 2], [1, 6]], [[3, 3], [6, 1]], [[0, 1], [9, 0]]] """ if in_dygraph_mode(): return _C_ops.gather_tree(ids, parents) else: helper = LayerHelper('gather_tree', **locals()) check_variable_and_dtype(ids, 'ids', ['int32', 'int64'], 'gather_tree') check_variable_and_dtype(parents, 'parents', ['int32', 'int64'], 'gather_tree') out = helper.create_variable_for_type_inference(dtype=ids.dtype) helper.append_op( type="gather_tree", inputs={"Ids": ids, "Parents": parents}, outputs={"Out": out}) return out @deprecated(since="2.0.0", update_to="paddle.uniform") @templatedoc() def uniform_random(shape, dtype='float32', min=-1.0, max=1.0, seed=0, name=None): """ This OP returns a Tensor filled with random values sampled from a uniform distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``. Examples: :: Input: shape = [1, 2] Output: result=[[0.8505902, 0.8397286]] Args: shape(list|tuple|Tensor): The shape of the output Tensor. If ``shape`` is a list or tuple, the elements of it should be integers or Tensors (with the shape [1], and the data type int32 or int64). If ``shape`` is a Tensor, it should be a 1-D Tensor(with the data type int32 or int64). dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of the output Tensor. Supported data types: float32, float64. Default is float32. min(float|int, optional): The lower bound on the range of random values to generate, ``min`` is included in the range. Default is -1.0. max(float|int, optional): The upper bound on the range of random values to generate, ``max`` is excluded in the range. Default is 1.0. seed(int, optional): Random seed used for generating samples. 0 means use a seed generated by the system. Note that if seed is not 0, this operator will always generate the same random numbers every time. Default is 0. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: A Tensor filled with random values sampled from a uniform distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``. Raises: TypeError: If ``shape`` is not list, tuple, Tensor. TypeError: If ``dtype`` is not float32, float64. Examples: .. code-block:: python import paddle import paddle.fluid as fluid paddle.enable_static() # example 1: # attr shape is a list which doesn't contain Tensor. result_1 = fluid.layers.uniform_random(shape=[3, 4]) # [[ 0.84524226, 0.6921872, 0.56528175, 0.71690357], # [-0.34646994, -0.45116323, -0.09902662, -0.11397249], # [ 0.433519, 0.39483607, -0.8660099, 0.83664286]] # example 2: # attr shape is a list which contains Tensor. dim_1 = fluid.layers.fill_constant([1], "int64", 2) dim_2 = fluid.layers.fill_constant([1], "int32", 3) result_2 = fluid.layers.uniform_random(shape=[dim_1, dim_2]) # [[-0.9951253, 0.30757582, 0.9899647 ], # [ 0.5864527, 0.6607096, -0.8886161 ]] # example 3: # attr shape is a Tensor, the data type must be int64 or int32. var_shape = fluid.data(name='var_shape', shape=[2], dtype="int64") result_3 = fluid.layers.uniform_random(var_shape) # if var_shape's value is [2, 3] # result_3 is: # [[-0.8517412, -0.4006908, 0.2551912 ], # [ 0.3364414, 0.36278176, -0.16085452]] """ if not isinstance(dtype, core.VarDesc.VarType): dtype = convert_np_dtype_to_dtype_(dtype) if in_dygraph_mode(): shape = utils.convert_shape_to_list(shape) return _C_ops.uniform_random('shape', shape, 'min', float(min), 'max', float(max), 'seed', seed, 'dtype', dtype) check_type(shape, 'shape', (list, tuple, Variable), 'uniform_random/rand') check_dtype(dtype, 'dtype', ('float32', 'float64', 'uint16'), 'uniform_random/rand') inputs = dict() attrs = {'seed': seed, 'min': min, 'max': max, 'dtype': dtype} utils.get_shape_tensor_inputs( inputs=inputs, attrs=attrs, shape=shape, op_type='uniform_random/rand') helper = LayerHelper("uniform_random", **locals()) out = helper.create_variable_for_type_inference(dtype) helper.append_op( type="uniform_random", inputs=inputs, attrs=attrs, outputs={"Out": out}) utils.try_set_static_shape_tensor(out, shape) return out def unbind(input, axis=0): """ Removes a tensor dimension, then split the input tensor into multiple sub-Tensors. Args: input (Variable): The input variable which is an N-D Tensor, data type being float32, float64, int32 or int64. axis (int32|int64, optional): A scalar with type ``int32|int64`` shape [1]. The dimension along which to unbind. If :math:`axis < 0`, the dimension to unbind along is :math:`rank(input) + axis`. Default is 0. Returns: list(Variable): The list of segmented Tensor variables. Example: .. code-block:: python import paddle # input is a variable which shape is [3, 4, 5] input = paddle.fluid.data( name="input", shape=[3, 4, 5], dtype="float32") [x0, x1, x2] = paddle.tensor.unbind(input, axis=0) # x0.shape [4, 5] # x1.shape [4, 5] # x2.shape [4, 5] [x0, x1, x2, x3] = paddle.tensor.unbind(input, axis=1) # x0.shape [3, 5] # x1.shape [3, 5] # x2.shape [3, 5] # x3.shape [3, 5] """ helper = LayerHelper("unbind", **locals()) check_type(input, 'input', (Variable), 'unbind') dtype = helper.input_dtype() check_dtype(dtype, 'unbind', ['float32', 'float64', 'int32', 'int64'], 'unbind') if not isinstance(axis, (int)): raise TypeError("The type of 'axis' must be int, but received %s." % (type(axis))) if isinstance(axis, np.generic): axis = np.asscalar(axis) input_shape = input.shape axis_ = axis if axis >= 0 else len(input_shape) + axis num = input_shape[axis_] outs = [ helper.create_variable_for_type_inference(dtype=helper.input_dtype()) for i in range(num) ] helper.append_op( type="unbind", inputs={"X": input}, outputs={"Out": outs}, attrs={"axis": axis}) return outs
39.681446
946
0.577419
bc4dcd5793fe1750cd4e4b4c8d15b513771e8ffd
7,473
py
Python
mod/parts.py
wtfsystems/ppms
b8c900496cfa263a5c2b7cdfe256174b484f109b
[ "MIT" ]
5
2020-07-29T01:22:30.000Z
2021-08-25T13:41:18.000Z
mod/parts.py
wtfsystems/ppms
b8c900496cfa263a5c2b7cdfe256174b484f109b
[ "MIT" ]
null
null
null
mod/parts.py
wtfsystems/ppms
b8c900496cfa263a5c2b7cdfe256174b484f109b
[ "MIT" ]
null
null
null
################################################################## # # Python Polyphonic MIDI Synthesizer # ################################################################## # # ~~~~~~~[]=¤ԅ(ˊᗜˋ* )੭ # # Filename: parts.py # By: Matthew Evans # https://www.wtfsystems.net/ # # See LICENSE.md for copyright information. # See README.md for usage information. # # This file implements the various parts used for ppms # ################################################################## import math import numpy as np from typing import Final from scipy import signal from abc import ABCMeta, abstractmethod ## Algorithms for use by ppms. # Store some lambda expressions for use elsewhere. class ppms_algs(object): # Define the A440 algorithm A440 = lambda note: math.pow(2, (note - 69) / 12) * 440 ## Generates samples of different waveforms. class oscillator(object): ## Initialize and store sample rate. # @param self Object pointer # @param rate Sample rate def __init__(self, rate): ## Store the sample rate self.__sample_rate: Final = rate ## Calculate sample data. # @param self Object pointer # @param frame_size Amount to generate # @param time_data Position in time # @return Generated sample data def __calc_sample_data(self, frame_size, time_data): t = ((time_data + np.arange(frame_size)) / self.__sample_rate).reshape(-1, 1) return t.reshape(-1, 1) ## Calculate pitch bend. # @param self Object pointer # @param note_freq Note frequency # @param pich_bend Pitch bend amount # @return The note frequency with pitch bend factored def __calc_pitch_bend(self, note_freq, pitch_bend): if pitch_bend != 0: note_freq = note_freq * pitch_bend return note_freq ## Calculate phase shift data for oscillator. # This just cleans up the other function calls a bit. # @param self Object pointer # @param note Note to play # @param pitch_bend Pitch bend data # @param frame_size Amount of data to generate # @param time_data Position in waveform # @return Generated phase shift data def __OSCFUNC(self, note, pitch_bend, frame_size, time_data): return (2 * np.pi * self.__calc_pitch_bend(ppms_algs.A440(note), pitch_bend) * self.__calc_sample_data(frame_size, time_data)) ## Return a sawtooth wave sample. # @param self Object pointer # @param note Note to play # @param pitch_bend Pitch bend data # @param frame_size Amount of data to generate # @param time_data Position in waveform # @return Sawtooth sample def sawtooth(self, note, pitch_bend, frame_size, time_data): return signal.sawtooth(self.__OSCFUNC(note, pitch_bend, frame_size, time_data)) ## Return a triangle wave sample. # @param self Object pointer # @param note Note to play # @param pitch_bend Pitch bend data # @param frame_size Amount of data to generate # @param time_data Position in waveform # @return Triangle sample def triangle(self, note, pitch_bend, frame_size, time_data): return signal.sawtooth(self.__OSCFUNC(note, pitch_bend, frame_size, time_data), 0.5) ## Return a square wave sample. # @param self Object pointer # @param note Note to play # @param pitch_bend Pitch bend data # @param frame_size Amount of data to generate # @param time_data Position in waveform # @return Square sample def square(self, note, pitch_bend, frame_size, time_data): return signal.square(self.__OSCFUNC(note, pitch_bend, frame_size, time_data)) ## Return a sine wave sample. # @param self Object pointer # @param note Note to play # @param pitch_bend Pitch bend data # @param frame_size Amount of data to generate # @param time_data Position in waveform # @return Sine sample def sine(self, note, pitch_bend, frame_size, time_data): return np.sin(self.__OSCFUNC(note, pitch_bend, frame_size, time_data)) ## Creates "patches" of "synth modules" to process the signal. # The main ppms application sets this up from its configuration file. class patchboard(object): ## Initialize patchboard. # @param self Object pointer def __init__(self): self.__patches = list() ## Add a module to the patchboard. # These will be processed in order loaded. # @param self Object pointer # @param mod Synth module to add def add_module(self, mod): try: self.__patches.append(mod) except: raise RuntimeError("Error adding module to patchboard") ## Clear all loaded modules. # @param self Object pointer def clear_modules(self): self.__patches.clear() ## Get a module by name. # @param self Object pointer # @param name Name of module to search for # @return Module object if found, else raise not found exception def get_module(self, name): for module in self.__patches: if(name == module.__name__): return module raise IndexError("Module not found") ## Save all module data. # @param self Object pointer # @return List of all module save data def save_data(self): data = [] for module in self.__patches: try: data += module.save_data(module) except: pass return data ## Process modules in order. # @param self Object pointer # @param signal Signal data to modify # @return Modified signal data def patch(self, note, signal): for module in self.__patches: try: signal = module.process(module, note, signal) except NotImplementedError as e: raise except: pass return signal ## Synth module base class. # Extend this object to create a usable synth module. class synthmod(metaclass=ABCMeta): ## Flag to check if valid synth module IS_SYNTHMOD: Final = True ## Midi control minimum value MIDI_MIN: Final = 0 ## Midi control maximum value MIDI_MAX: Final = 127 ## Synth module process member for modifying signal. # Override this to implement a custom process method. # Raises not implemented error if not overridden. # @param self Object pointer # @param note Note to be played # @param signal Audio signal @abstractmethod def process(self, note, signal): raise NotImplementedError("Must override process method in synth module", self.__name__) ## Mod wheel control part. # Lets a synth module read in the mod wheel value. # Extend this and call self.get_mod_value() to read. class mod_control(metaclass=ABCMeta): ## Store the mod wheel value. __MOD_VALUE = 0 ## Set the mod wheel value. # This is set within the ppms input coroutine. # @param cls Object pointer # @param value Value to set mod wheel to @classmethod def set_mod_value(cls, value): cls.__MOD_VALUE = value ## Get the mod wheel value. # Called within a synth module. # @param cls Object pointer # @return Current mod wheel value @classmethod def get_mod_value(cls): return cls.__MOD_VALUE
36.632353
97
0.633882
e6273b510f5f189e8460d82599751fafd4347163
6,814
py
Python
models/wrf_hydro/hydro_dart_py/hydrodartpy/tests/conftest.py
fairaque1999/DART
7490f75cf9800cc841b66d87840ad96c5751b809
[ "Apache-2.0" ]
65
2019-10-16T13:31:06.000Z
2022-03-14T11:52:58.000Z
models/wrf_hydro/hydro_dart_py/hydrodartpy/tests/conftest.py
fairaque1999/DART
7490f75cf9800cc841b66d87840ad96c5751b809
[ "Apache-2.0" ]
283
2019-09-23T15:48:34.000Z
2022-03-31T21:44:41.000Z
models/wrf_hydro/hydro_dart_py/hydrodartpy/tests/conftest.py
fairaque1999/DART
7490f75cf9800cc841b66d87840ad96c5751b809
[ "Apache-2.0" ]
67
2019-09-19T22:13:24.000Z
2022-03-20T15:58:26.000Z
from boltons.iterutils import remap import hydrodartpy import os import pathlib import pytest import shlex import shutil import subprocess import yaml import hydrodartpy.core.setup_experiment_tools as hdp_tools repo_dir = hdp_tools.repo_dir def if_e_rm(path: pathlib.Path): if path.is_file(): _ = path.unlink() elif path.is_dir(): _ = shutil.rmtree(str(path)) else: return 1 return 0 def pytest_addoption(parser): parser.addoption( "--exp_yaml", required=True, type=str, nargs=1, action='store', help=("The path to the YAML file for the experiment.")) parser.addoption( "--exp_answer_file", type=str, nargs=1, required=True, action='store', help=("The directory where expected experiment outputs live.")) parser.addoption( "--scratch_dir", type=str, nargs=1, required=False, default=['None'], action='store', help=("The local scratch where experiment output will go.")) parser.addoption( "--use_existing_build", required=False, default=False, action='store_true', help=("Use existing dart and wrfhydro builds?")) # Could also use existing obs and/or initial ensemble @pytest.fixture(scope="session") def test_dir(): return pathlib.Path(os.getcwd()).resolve() @pytest.fixture(scope="session") def answer_file(request, test_dir): exp_answer_file = test_dir / ( request.config.getoption("--exp_answer_file")[0]) return exp_answer_file @pytest.fixture(scope="session") def config_file(request, test_dir): exp_yaml = test_dir / ( request.config.getoption("--exp_yaml")[0]) scratch_dir = request.config.getoption("--scratch_dir")[0] use_existing_build = request.config.getoption("--use_existing_build") # scratch guessing if scratch_dir == 'None': tmp_dir = os.getenv('TMPDIR') if tmp_dir == '': raise ValueError('TMPDIR environment variable not found, ' 'you must specify --scratch_dir') tmp_dir = pathlib.Path(tmp_dir) if not tmp_dir.exists(): raise ValueError('The tmp_dir does not exist', str(tmp_dir)) scratch_dir = tmp_dir # read the yaml exp_config = hdp_tools.establish_config(exp_yaml) ## check the yaml compiler matches the current modules module_list = subprocess.run( 'module list', shell=True, stderr=subprocess.PIPE) the_compiler = exp_config['wrf_hydro']['compiler'] wrong_compiler_msg = ( 'The current compiler does not appear to match the compiler in the ' 'YAML file: ' + the_compiler+ '. Please quit python and change ' 'your modules or change the YAML:' + exp_config['wrf_hydro']['compiler']) if the_compiler == 'ifort': assert 'intel' in module_list.stderr.decode('utf-8'), wrong_compiler_msg elif the_compiler == 'gfort': assert 'intel' in module_list.stderr.decode('utf-8'), wrong_compiler_msg else: raise ValueError("What compiler are you using???") out_dir = scratch_dir / ('hydrodartpy_tests/' + exp_yaml.parent.name) # alter the config values exp_dir = out_dir / 'experiment' exp_config['experiment']['experiment_dir'] = str(exp_dir) run_dir = out_dir / 'run' exp_config['experiment']['run_dir'] = str(run_dir) ini_dir = out_dir / 'initial_ensemble' exp_config['initial_ens']['path'] = str(ini_dir) all_obs_dir = out_dir / 'obs_seqs' exp_config['observation_preparation']['all_obs_dir'] = str(all_obs_dir) ## Some semi-hard-coded patches if 'USGS_daily' in exp_config['observation_preparation'].keys(): exp_config['observation_preparation']['USGS_daily']['output_dir'] = str( all_obs_dir / 'USGS_daily') if ('noise_function_files' in exp_config['run_experiment']['perturb_forcing'].keys()): pf = exp_config['run_experiment']['perturb_forcing'] nffs = pf['noise_function_files'] nffs = [str(repo_dir.joinpath(nff)) for nff in nffs] pf['noise_function_files'] = nffs test_dir = pathlib.Path(os.getcwd()) exp_config['dart']['dart_src'] = str( test_dir.parent.parent.parent.parent.parent) ## could clone/update a model repo here wrf_hydro_src = test_dir / 'data/wrf_hydro_nwm_public' exp_config['wrf_hydro']['wrf_hydro_src'] = str(wrf_hydro_src) print('\n\n' '**********************************\n' 'WRF-Hydro repository information:\n') if use_existing_build: if not wrf_hydro_src.exists(): raise ValueError('Repository missing, unfortunately cant ' 'use existing build for this test.') elif not wrf_hydro_src.exists(): clone_cmd = 'git clone https://github.com/NCAR/wrf_hydro_nwm_public.git' clone_result = subprocess.run( shlex.split(clone_cmd), cwd=wrf_hydro_src.parent) # else: # I have Decided against continuous integration. #update_cmd = 'git pull origin master' #update_result = subprocess.run( # shlex.split(update_cmd), cwd=wrf_hydro_src) checkout_cmd = 'git checkout -f nwm-v2.1-beta3' sub_result = subprocess.run(shlex.split(checkout_cmd), cwd=wrf_hydro_src) commit_cmd = 'git --no-pager log -n 1 --pretty=oneline' sub_result = subprocess.run(shlex.split(commit_cmd), cwd=wrf_hydro_src) print('\n\n' '**********************************\n') exp_config['ensemble']['constructor'] = str(exp_yaml.parent / 'constructor.py') test_yaml = out_dir / 'test.yaml' # Set up test directories exp_config['dart']['use_existing_build'] = use_existing_build exp_config['wrf_hydro']['use_existing_build'] = use_existing_build if not use_existing_build: if out_dir.exists(): _ = shutil.rmtree(str(out_dir)) _ = out_dir.mkdir(parents=True) else: _ = if_e_rm(test_yaml) _ = if_e_rm(run_dir) _ = if_e_rm(ini_dir) _ = if_e_rm(all_obs_dir) exp_dir_files = exp_dir.glob('*') builds_keep = [ exp_config['dart']['build_dir'], exp_config['wrf_hydro']['build_dir']] _ = [if_e_rm(path) for path in exp_dir_files if path.name not in builds_keep] strify = hdp_tools.visit_abs_paths_to_str exp_config_out = remap(exp_config, strify) with open(test_yaml, 'w') as out_file: _ = yaml.dump(exp_config_out, out_file) return test_yaml @pytest.fixture(scope="session") def config_dict(config_file): return hdp_tools.establish_config(config_file)
33.566502
84
0.636924
a36ef29e203b07efb73d96dec77659759d7c7b2f
2,100
py
Python
jdcloud_sdk/services/cdn/apis/QueryPurgeTaskRequest.py
Tanc009/jdcloud-sdk-python
8b045c99bc5b73ca7348e950b6f01e03a27982f5
[ "Apache-2.0" ]
14
2018-04-19T09:53:56.000Z
2022-01-27T06:05:48.000Z
jdcloud_sdk/services/cdn/apis/QueryPurgeTaskRequest.py
Tanc009/jdcloud-sdk-python
8b045c99bc5b73ca7348e950b6f01e03a27982f5
[ "Apache-2.0" ]
15
2018-09-11T05:39:54.000Z
2021-07-02T12:38:02.000Z
jdcloud_sdk/services/cdn/apis/QueryPurgeTaskRequest.py
Tanc009/jdcloud-sdk-python
8b045c99bc5b73ca7348e950b6f01e03a27982f5
[ "Apache-2.0" ]
33
2018-04-20T05:29:16.000Z
2022-02-17T09:10:05.000Z
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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. # # NOTE: This class is auto generated by the jdcloud code generator program. from jdcloud_sdk.core.jdcloudrequest import JDCloudRequest class QueryPurgeTaskRequest(JDCloudRequest): """ 查询刷新任务接口 """ def __init__(self, parameters, header=None, version="v1"): super(QueryPurgeTaskRequest, self).__init__( '/purgeTask:query', 'POST', header, version) self.parameters = parameters class QueryPurgeTaskParameters(object): def __init__(self, ): """ """ self.url = None self.status = None self.fileId = None self.pageNumber = None self.pageSize = None self.domain = None def setUrl(self, url): """ :param url: (Optional) url """ self.url = url def setStatus(self, status): """ :param status: (Optional) 查询状态 1:进行中 2:已完成 """ self.status = status def setFileId(self, fileId): """ :param fileId: (Optional) 同url,系统内部url对应id(url和file_id同时存在时以url为准) """ self.fileId = fileId def setPageNumber(self, pageNumber): """ :param pageNumber: (Optional) 页码数,最小为1 """ self.pageNumber = pageNumber def setPageSize(self, pageSize): """ :param pageSize: (Optional) 每页大小,默认10 """ self.pageSize = pageSize def setDomain(self, domain): """ :param domain: (Optional) 域名 """ self.domain = domain
25.609756
75
0.62381
5df4c0ba005460d8167247ff37c458aca45d8ff7
1,278
py
Python
project_backend/views.py
MichaelDoctor/Portfolio
41d9104ef6d34f8eb146230b19038b445351c713
[ "MIT" ]
null
null
null
project_backend/views.py
MichaelDoctor/Portfolio
41d9104ef6d34f8eb146230b19038b445351c713
[ "MIT" ]
4
2021-06-09T18:02:18.000Z
2022-01-13T03:06:24.000Z
project_backend/views.py
MichaelDoctor/Portfolio
41d9104ef6d34f8eb146230b19038b445351c713
[ "MIT" ]
null
null
null
from rest_framework.views import APIView from rest_framework import permissions from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication, \ BasicAuthentication from django.contrib.auth.models import User class CurrentUser(APIView): permission_classes = (permissions.AllowAny,) authentication_classes = (SessionAuthentication, BasicAuthentication,) def get(self, request): if str(request.user.id) != "None": content = { 'pk': int(str(request.user.id)), 'username': str(request.user), 'first_name': str(request.user.first_name), 'last_name': str(request.user.last_name) } return Response(content) else: return Response({'pk': 'None'}) class GetUsername(APIView): permission_classes = (permissions.AllowAny,) lookup_field = 'pk' def get(self, request, pk): try: data = User.objects.filter(id=pk).values()[0] content = { 'pk': data['id'], 'username': data['username'] } return Response(content) except Exception: return Response({'pk': pk, 'username': '404'})
31.95
74
0.607199
371f9dd5617b720d67b3f6eb236249fbdffd89a0
2,234
py
Python
19_wod/wod.py
bilbatez/tiny_python_projects
4ab831dbaf1b15aa427e70ae8abfa924cd7ecc38
[ "MIT" ]
null
null
null
19_wod/wod.py
bilbatez/tiny_python_projects
4ab831dbaf1b15aa427e70ae8abfa924cd7ecc38
[ "MIT" ]
null
null
null
19_wod/wod.py
bilbatez/tiny_python_projects
4ab831dbaf1b15aa427e70ae8abfa924cd7ecc38
[ "MIT" ]
null
null
null
#! /usr/bin/env python3 """ Author: Albert Julian Tannady Purpose: Chapter 19 - Workout of the Day """ import re import csv import sys import random import argparse from tabulate import tabulate SPLITTER = re.compile(r"(\d+)-(\d+)") def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Create Workout of (the) Day (WOD)", ) parser.add_argument( "-f", "--file", metavar="FILE", type=argparse.FileType("rt"), default="inputs/exercises.csv", help="CSV input file of exercises", ) parser.add_argument( "-s", "--seed", type=int, metavar="seed", default=None, help="Random seed" ) parser.add_argument( "-n", "--num", type=int, metavar="exercises", default=4, help="Number of exercises", ) parser.add_argument( "-e", "--easy", action="store_true", help="Halve the reps", ) args = parser.parse_args() if args.num < 1: sys.exit(f'--num "{args.num}" must be greater than 0') return args def main(): """Main Program""" args = get_args() random.seed(args.seed) exercises = read_csv(args.file) if not exercises: sys.exit(f'No usable data in --file "{args.file.name}"') l_exercises = len(exercises) if args.num > l_exercises: sys.exit(f'--num "{args.num}" > exercises "{l_exercises}"') result = [] for exercise in random.sample(exercises, k=args.num): reps = random.randint(exercise[1], exercise[2]) result.append((exercise[0], int(reps / 2) if args.easy else reps)) print(tabulate(result, headers=("Exercise", "Reps"))) def read_csv(fh): """Read the CSV input""" exercises = [] for rec in csv.DictReader(fh, delimiter=","): name, reps = rec.get("exercise"), rec.get("reps") if name and reps: match = SPLITTER.match(reps) if match: low, high = map(int, match.groups()) exercises.append((name, low, high)) return exercises if __name__ == "__main__": main()
25.101124
82
0.582811
dc26a8f886c5010318fa6ee8b946e1531b6ec75b
1,115
py
Python
oeGPIO.py
octopusengine/simple3dscanner
4c62e0ba1bd4b1217106d81ce9ac0a2c6851244a
[ "MIT" ]
33
2016-04-26T07:26:53.000Z
2022-03-14T15:14:20.000Z
oeGPIO.py
octopusengine/simple3dscanner
4c62e0ba1bd4b1217106d81ce9ac0a2c6851244a
[ "MIT" ]
2
2016-09-02T09:48:35.000Z
2016-10-19T08:01:47.000Z
oeGPIO.py
octopusengine/simple3dscanner
4c62e0ba1bd4b1217106d81ce9ac0a2c6851244a
[ "MIT" ]
16
2016-04-25T18:21:20.000Z
2020-03-23T08:16:37.000Z
#!/usr/bin/python # Filename : oeGPIO.py #----------------------------------- ## simple 3d scanner ##---------------------------------- import time from time import sleep import RPi.GPIO as GPIO # for step motor EN2 = 22 DIR2 = 27 STEP2 = 17 dStep=0.00001 #--------------------------------- def oeSetupGPIO(): global EN2,DIR2,STEP2 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) #GPIO.setup(END2, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(EN2, GPIO.OUT) GPIO.setup(DIR2, GPIO.OUT) GPIO.setup(STEP2, GPIO.OUT) #--------------------------------- def oeMotCCWs(steps,speed): global EN2,DIR2,STEP2, dStep #step motor - count clock wise nas=2 #1600/ot #8=400 #16=200 for 360 GPIO.output(EN2, False) GPIO.output(DIR2, False) for tx in range(steps*nas): time.sleep(dStep*speed) GPIO.output(STEP2, True) time.sleep(dStep*speed) GPIO.output(STEP2, False) GPIO.output(EN2, True) #aret. #--------------------------------- def oeMotOff(): GPIO.output(EN2, True) #motor switch off #---end---
22.755102
59
0.536323
bd12e83e2e413501e9619d823b6ac2364a4a9411
17,038
py
Python
Savethemblobs/PythonistaKit.framework/pylib/textwrap.py
iApeiron/Savethemblobs_app
38184facf78b55ba89a727be7b1fc08d6085f20c
[ "MIT" ]
19
2017-05-17T16:48:02.000Z
2020-08-18T18:21:45.000Z
Savethemblobs/PythonistaKit.framework/pylib/textwrap.py
iApeiron/Savethemblobs_app
38184facf78b55ba89a727be7b1fc08d6085f20c
[ "MIT" ]
2
2017-05-17T06:41:47.000Z
2017-05-17T17:27:13.000Z
Savethemblobs/PythonistaKit.framework/pylib/textwrap.py
iApeiron/Savethemblobs_app
38184facf78b55ba89a727be7b1fc08d6085f20c
[ "MIT" ]
4
2017-05-17T03:56:25.000Z
2018-11-09T00:00:20.000Z
"""Text wrapping and filling. """ # Copyright (C) 1999-2001 Gregory P. Ward. # Copyright (C) 2002, 2003 Python Software Foundation. # Written by Greg Ward <gward@python.net> __revision__ = "$Id$" import string, re try: _unicode = unicode except NameError: # If Python is built without Unicode support, the unicode type # will not exist. Fake one. class _unicode(object): pass # Do the right thing with boolean values for all known Python versions # (so this module can be copied to projects that don't depend on Python # 2.3, e.g. Optik and Docutils) by uncommenting the block of code below. #try: # True, False #except NameError: # (True, False) = (1, 0) __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent'] # Hardcode the recognized whitespace characters to the US-ASCII # whitespace characters. The main reason for doing this is that in # ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales # that character winds up in string.whitespace. Respecting # string.whitespace in those cases would 1) make textwrap treat 0xa0 the # same as any other whitespace char, which is clearly wrong (it's a # *non-breaking* space), 2) possibly cause problems with Unicode, # since 0xa0 is not in range(128). _whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: """ Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you'll probably have to override _wrap_chunks(). Several instance attributes control various aspects of wrapping: width (default: 70) the maximum width of wrapped lines (unless break_long_words is false) initial_indent (default: "") string that will be prepended to the first line of wrapped output. Counts towards the line's width. subsequent_indent (default: "") string that will be prepended to all lines save the first of wrapped output; also counts towards each line's width. expand_tabs (default: true) Expand tabs in input text to spaces before further processing. Each tab will become 1 .. 8 spaces, depending on its position in its line. If false, each tab is treated as a single character. replace_whitespace (default: true) Replace all whitespace characters in the input text by spaces after tab expansion. Note that if expand_tabs is false and replace_whitespace is true, every tab will be converted to a single space! fix_sentence_endings (default: false) Ensure that sentence-ending punctuation is always followed by two spaces. Off by default because the algorithm is (unavoidably) imperfect. break_long_words (default: true) Break words longer than 'width'. If false, those words will not be broken, and some lines might be longer than 'width'. break_on_hyphens (default: true) Allow breaking hyphenated words. If true, wrapping will occur preferably on whitespaces and right after hyphens part of compound words. drop_whitespace (default: true) Drop leading and trailing whitespace from lines. """ whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace)) unicode_whitespace_trans = {} uspace = ord(u' ') for x in map(ord, _whitespace): unicode_whitespace_trans[x] = uspace # This funky little regex is just the trick for splitting # text up into word-wrappable chunks. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! # (after stripping out empty strings). wordsep_re = re.compile( r'(\s+|' # any whitespace r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|' # hyphenated words r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash # This less funky little regex just split on recognized spaces. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ wordsep_simple_re = re.compile(r'(\s+)') # XXX this is not locale- or charset-aware -- string.lowercase # is US-ASCII only (and therefore English-only) sentence_end_re = re.compile(r'[%s]' # lowercase letter r'[\.\!\?]' # sentence-ending punct. r'[\"\']?' # optional end-of-quote r'\Z' # end of chunk % string.lowercase) def __init__(self, width=70, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True): self.width = width self.initial_indent = initial_indent self.subsequent_indent = subsequent_indent self.expand_tabs = expand_tabs self.replace_whitespace = replace_whitespace self.fix_sentence_endings = fix_sentence_endings self.break_long_words = break_long_words self.drop_whitespace = drop_whitespace self.break_on_hyphens = break_on_hyphens # recompile the regexes for Unicode mode -- done in this clumsy way for # backwards compatibility because it's rather common to monkey-patch # the TextWrapper class' wordsep_re attribute. self.wordsep_re_uni = re.compile(self.wordsep_re.pattern, re.U) self.wordsep_simple_re_uni = re.compile( self.wordsep_simple_re.pattern, re.U) # -- Private methods ----------------------------------------------- # (possibly useful for subclasses to override) def _munge_whitespace(self, text): """_munge_whitespace(text : string) -> string Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" becomes " foo bar baz". """ if self.expand_tabs: text = text.expandtabs() if self.replace_whitespace: if isinstance(text, str): text = text.translate(self.whitespace_trans) elif isinstance(text, _unicode): text = text.translate(self.unicode_whitespace_trans) return text def _split(self, text): """_split(text : string) -> [string] Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see _wrap_chunks() for full details. As an example, the text Look, goof-ball -- use the -b option! breaks into the following chunks: 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', 'option!' if break_on_hyphens is True, or in: 'Look,', ' ', 'goof-ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', option!' otherwise. """ if isinstance(text, _unicode): if self.break_on_hyphens: pat = self.wordsep_re_uni else: pat = self.wordsep_simple_re_uni else: if self.break_on_hyphens: pat = self.wordsep_re else: pat = self.wordsep_simple_re chunks = pat.split(text) chunks = filter(None, chunks) # remove empty chunks return chunks def _fix_sentence_endings(self, chunks): """_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\nBar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two. """ i = 0 patsearch = self.sentence_end_re.search while i < len(chunks)-1: if chunks[i+1] == " " and patsearch(chunks[i]): chunks[i+1] = " " i += 2 else: i += 1 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long to fit in any line. """ # Figure out when indent is larger than the specified width, and make # sure at least one character is stripped off on every pass if width < 1: space_left = 1 else: space_left = width - cur_len # If we're allowed to break long words, then do so: put as much # of the next chunk onto the current line as will fit. if self.break_long_words: cur_line.append(reversed_chunks[-1][:space_left]) reversed_chunks[-1] = reversed_chunks[-1][space_left:] # Otherwise, we have to preserve the long word intact. Only add # it to the current line if there's nothing already there -- # that minimizes how much we violate the width constraint. elif not cur_line: cur_line.append(reversed_chunks.pop()) # If we're not allowed to break long words, and there's already # text on the current line, do nothing. Next time through the # main loop of _wrap_chunks(), we'll wind up here again, but # cur_len will be zero, so the next line will be entirely # devoted to the long word that we can't handle right now. def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo 'break_long_words'), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a "word". Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved. """ lines = [] if self.width <= 0: raise ValueError("invalid width %r (must be > 0)" % self.width) # Arrange in reverse order so items can be efficiently popped # from a stack of chucks. chunks.reverse() while chunks: # Start the list of chunks that will make up the current line. # cur_len is just the length of all the chunks in cur_line. cur_line = [] cur_len = 0 # Figure out which static string will prefix this line. if lines: indent = self.subsequent_indent else: indent = self.initial_indent # Maximum width for this line. width = self.width - len(indent) # First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (ie. no lines started yet). if self.drop_whitespace and chunks[-1].strip() == '' and lines: del chunks[-1] while chunks: l = len(chunks[-1]) # Can at least squeeze this chunk onto the current line. if cur_len + l <= width: cur_line.append(chunks.pop()) cur_len += l # Nope, this line is full. else: break # The current line is full, and the next chunk is too big to # fit on *any* line (not just this one). if chunks and len(chunks[-1]) > width: self._handle_long_word(chunks, cur_line, cur_len, width) # If the last chunk on this line is all whitespace, drop it. if self.drop_whitespace and cur_line and cur_line[-1].strip() == '': del cur_line[-1] # Convert current line back to a string and store it in list # of all lines (return value). if cur_line: lines.append(indent + ''.join(cur_line)) return lines # -- Public interface ---------------------------------------------- def wrap(self, text): """wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. """ text = self._munge_whitespace(text) chunks = self._split(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) return self._wrap_chunks(chunks) def fill(self, text): """fill(text : string) -> string Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string containing the entire wrapped paragraph. """ return "\n".join(self.wrap(text)) # -- Convenience interface --------------------------------------------- def wrap(text, width=70, **kwargs): """Wrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By default, tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.wrap(text) def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.fill(text) # -- Loosely related functionality ------------------------------------- _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE) _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE) def dedent(text): """Remove any common leading whitespace from every line in `text`. This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form. Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines " hello" and "\thello" are considered to have no common leading whitespace. (This behaviour is new in Python 2.5; older versions of this module incorrectly expanded tabs before searching for common leading whitespace.) """ # Look for the longest leading string of spaces and tabs common to # all lines. margin = None text = _whitespace_only_re.sub('', text) indents = _leading_whitespace_re.findall(text) for indent in indents: if margin is None: margin = indent # Current line more deeply indented than previous winner: # no change (previous winner is still on top). elif indent.startswith(margin): pass # Current line consistent with and no deeper than previous winner: # it's the new winner. elif margin.startswith(indent): margin = indent # Current line and previous winner have no common whitespace: # there is no margin. else: margin = "" break # sanity check (testing/debugging only) if 0 and margin: for line in text.split("\n"): assert not line or line.startswith(margin), \ "line = %r, margin = %r" % (line, margin) if margin: text = re.sub(r'(?m)^' + margin, '', text) return text if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") print dedent("Hello there.\n This is indented.")
39.901639
80
0.605881
6c94c793278ad48da061aa3d0b54d874790512bc
5,128
py
Python
pytorch_projects/common_pytorch/blocks/resnet_direct_regression.py
NiteshBharadwaj/structured_aleatoric_uncertainty_for_human_pose
c74fb7384be562f0a0f1966b3fadf19e13a235f2
[ "MIT" ]
null
null
null
pytorch_projects/common_pytorch/blocks/resnet_direct_regression.py
NiteshBharadwaj/structured_aleatoric_uncertainty_for_human_pose
c74fb7384be562f0a0f1966b3fadf19e13a235f2
[ "MIT" ]
null
null
null
pytorch_projects/common_pytorch/blocks/resnet_direct_regression.py
NiteshBharadwaj/structured_aleatoric_uncertainty_for_human_pose
c74fb7384be562f0a0f1966b3fadf19e13a235f2
[ "MIT" ]
null
null
null
import os from easydict import EasyDict as edict import torch import torch.nn as nn from torchvision.models.resnet import model_zoo, model_urls from common_pytorch.base_modules.resnet import resnet_spec, ResNetBackbone from common_pytorch.base_modules.avg_pool_head import AvgPoolHead, AvgPoolHead2 def get_default_network_config(): config = edict() config.from_model_zoo = True config.pretrained = '' config.num_layers = 50 config.fea_map_size = 0 return config class ResPoseNet(nn.Module): def __init__(self, backbone, head): super(ResPoseNet, self).__init__() self.backbone = backbone self.head = head def forward(self, x): x = self.backbone(x) x = self.head(x) return x class ResPoseNet_U(nn.Module): def __init__(self, backbone, head, head2, head3): super(ResPoseNet_U, self).__init__() self.backbone = backbone self.head = head self.head2 = head2 self.avgpool = nn.AvgPool2d(8, stride=1) self.head3 = head3 def forward(self, x): enc = self.backbone(x) enc_lat = self.avgpool(enc) x = self.head(enc) y = self.head2(enc) z = self.head3(enc) return x, y, z def get_pose_net(cfg, num_joints, is_cov = False): block_type, layers, channels, name = resnet_spec[cfg.num_layers] backbone_net = ResNetBackbone(block_type, layers) head_net = AvgPoolHead(channels[-1], num_joints * 3, cfg.fea_map_size) n_outs_cov = 1128 if is_cov else 174 head_net_2 = AvgPoolHead( channels[-1], num_joints * 3, cfg.fea_map_size) head_net_3 = AvgPoolHead2( channels[-1], n_outs_cov, cfg.fea_map_size) pose_net = ResPoseNet_U(backbone_net, head_net, head_net_2, head_net_3) return pose_net def init_pose_net(pose_net, cfg): if cfg.from_model_zoo and (cfg.pretrained is None or cfg.pretrained=='None'): print('Initializing network with resnet weights') _, _, _, name = resnet_spec[cfg.num_layers] org_resnet = model_zoo.load_url(model_urls[name]) # drop orginal resnet fc layer, add 'None' in case of no fc layer, that will raise error org_resnet.pop('fc.weight', None) org_resnet.pop('fc.bias', None) pose_net.backbone.load_state_dict(org_resnet) # print('Loading pretrained model from {}'.format(os.path.join(cfg.pretrained, model_file))) else: if os.path.exists(cfg.pretrained): model = torch.load(cfg.pretrained) transfer_partial_weights(model['network'], pose_net, prefix='module') print("Init Network from pretrained", cfg.pretrained) def transfer_partial_weights(state_dict_other, obj, submodule=0, prefix=None, add_prefix=''): own_state = obj.state_dict() copyCount = 0 skipCount = 0 paramCount = len(own_state) copied_param_names = [] skipped_param_names = [] for name_raw, param in state_dict_other.items(): if isinstance(param, torch.nn.Parameter): # backwards compatibility for serialized parameters param = param.data # print('.data conversion for ',name) if prefix is not None and not name_raw.startswith(prefix): print("skipping {} because of prefix {}".format(name_raw, prefix)) continue # remove the path of the submodule from which we load name = ''.join(name_raw.split(prefix+'.')[1:]) if name in own_state: if hasattr(own_state[name], 'copy_'): # isinstance(own_state[name], torch.Tensor): # print('copy_ ',name) if own_state[name].size() == param.size(): own_state[name].copy_(param) copyCount += 1 copied_param_names.append(name) else: print('Invalid param size(own={} vs. source={}), skipping {}'.format(own_state[name].size(), param.size(), name)) skipCount += 1 skipped_param_names.append(name) elif hasattr(own_state[name], 'copy'): own_state[name] = param.copy() copyCount += 1 copied_param_names.append(name) else: print('training.utils: Warning, unhandled element type for name={}, name_raw={}'.format(name, name_raw)) print(type(own_state[name])) skipCount += 1 skipped_param_names.append(name) IPython.embed() else: skipCount += 1 print('Warning, no match for {}, ignoring'.format(name)) skipped_param_names.append(name) # print(' since own_state.keys() = ',own_state.keys()) print('Copied {} elements, {} skipped, and {} target params without source'.format(copyCount, skipCount, paramCount - copyCount)) return copied_param_names, skipped_param_names
39.751938
120
0.607839
da2f2b613fce29ecdb4107b77005b88cf7f1b4c7
1,503
py
Python
Algorithms_easy/1170. Compare Strings by Frequency of the Smallest Character.py
VinceW0/Leetcode_Python_solutions
09e9720afce21632372431606ebec4129eb79734
[ "Xnet", "X11" ]
4
2020-08-11T20:45:15.000Z
2021-03-12T00:33:34.000Z
Algorithms_easy/1170. Compare Strings by Frequency of the Smallest Character.py
VinceW0/Leetcode_Python_solutions
09e9720afce21632372431606ebec4129eb79734
[ "Xnet", "X11" ]
null
null
null
Algorithms_easy/1170. Compare Strings by Frequency of the Smallest Character.py
VinceW0/Leetcode_Python_solutions
09e9720afce21632372431606ebec4129eb79734
[ "Xnet", "X11" ]
null
null
null
""" 1170. Compare Strings by Frequency of the Smallest Character Easy Let's define a function f(s) over a non-empty string s, which calculates the frequency of the smallest character in s. For example, if s = "dcce" then f(s) = 2 because the smallest character is "c" and its frequency is 2. Now, given string arrays queries and words, return an integer array answer, where each answer[i] is the number of words such that f(queries[i]) < f(W), where W is a word in words. Example 1: Input: queries = ["cbd"], words = ["zaaaz"] Output: [1] Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz"). Example 2: Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"] Output: [1,2] Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc"). Constraints: 1 <= queries.length <= 2000 1 <= words.length <= 2000 1 <= queries[i].length, words[i].length <= 10 queries[i][j], words[i][j] are English lowercase letters. """ class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: def helper(s): t = sorted(list(s))[0] return s.count(t) query = [helper(x) for x in queries] word = [helper(x) for x in words] m = [] for x in query: cnt = 0 for y in word: if y > x: cnt += 1 m.append(cnt) return m
35.785714
221
0.600798
841277ffb7b889e7631853e62b1e76a5ccd0bcfc
18,325
py
Python
test/functional/feature_bip68_sequence.py
durgeshkmr/Libra-Coin
c40293ac5c8f289e4c06b46d0c7f3ca76ff591a6
[ "MIT" ]
null
null
null
test/functional/feature_bip68_sequence.py
durgeshkmr/Libra-Coin
c40293ac5c8f289e4c06b46d0c7f3ca76ff591a6
[ "MIT" ]
null
null
null
test/functional/feature_bip68_sequence.py
durgeshkmr/Libra-Coin
c40293ac5c8f289e4c06b46d0c7f3ca76ff591a6
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Libra Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test BIP68 implementation.""" import time from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment from test_framework.messages import COIN, COutPoint, CTransaction, CTxIn, CTxOut, FromHex, ToHex from test_framework.script import CScript from test_framework.test_framework import LibraTestFramework from test_framework.util import assert_equal, assert_greater_than, assert_raises_rpc_error, bytes_to_hex_str, get_bip9_status, satoshi_round, sync_blocks SEQUENCE_LOCKTIME_DISABLE_FLAG = (1<<31) SEQUENCE_LOCKTIME_TYPE_FLAG = (1<<22) # this means use time (0 means height) SEQUENCE_LOCKTIME_GRANULARITY = 9 # this is a bit-shift SEQUENCE_LOCKTIME_MASK = 0x0000ffff # RPC error for non-BIP68 final transactions NOT_FINAL_ERROR = "non-BIP68-final (code 64)" class BIP68Test(LibraTestFramework): def set_test_params(self): self.num_nodes = 2 self.extra_args = [[], ["-acceptnonstdtxn=0"]] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): self.relayfee = self.nodes[0].getnetworkinfo()["relayfee"] # Generate some coins self.nodes[0].generate(110) self.log.info("Running test disable flag") self.test_disable_flag() self.log.info("Running test sequence-lock-confirmed-inputs") self.test_sequence_lock_confirmed_inputs() self.log.info("Running test sequence-lock-unconfirmed-inputs") self.test_sequence_lock_unconfirmed_inputs() self.log.info("Running test BIP68 not consensus before versionbits activation") self.test_bip68_not_consensus() self.log.info("Activating BIP68 (and 112/113)") self.activateCSV() self.log.info("Verifying nVersion=2 transactions are standard.") self.log.info("Note that nVersion=2 transactions are always standard (independent of BIP68 activation status).") self.test_version2_relay() self.log.info("Passed") # Test that BIP68 is not in effect if tx version is 1, or if # the first sequence bit is set. def test_disable_flag(self): # Create some unconfirmed inputs new_addr = self.nodes[0].getnewaddress() self.nodes[0].sendtoaddress(new_addr, 2) # send 2 LIBRA utxos = self.nodes[0].listunspent(0, 0) assert(len(utxos) > 0) utxo = utxos[0] tx1 = CTransaction() value = int(satoshi_round(utxo["amount"] - self.relayfee)*COIN) # Check that the disable flag disables relative locktime. # If sequence locks were used, this would require 1 block for the # input to mature. sequence_value = SEQUENCE_LOCKTIME_DISABLE_FLAG | 1 tx1.vin = [CTxIn(COutPoint(int(utxo["txid"], 16), utxo["vout"]), nSequence=sequence_value)] tx1.vout = [CTxOut(value, CScript([b'a']))] tx1_signed = self.nodes[0].signrawtransactionwithwallet(ToHex(tx1))["hex"] tx1_id = self.nodes[0].sendrawtransaction(tx1_signed) tx1_id = int(tx1_id, 16) # This transaction will enable sequence-locks, so this transaction should # fail tx2 = CTransaction() tx2.nVersion = 2 sequence_value = sequence_value & 0x7fffffff tx2.vin = [CTxIn(COutPoint(tx1_id, 0), nSequence=sequence_value)] tx2.vout = [CTxOut(int(value - self.relayfee * COIN), CScript([b'a' * 35]))] tx2.rehash() assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx2)) # Setting the version back down to 1 should disable the sequence lock, # so this should be accepted. tx2.nVersion = 1 self.nodes[0].sendrawtransaction(ToHex(tx2)) # Calculate the median time past of a prior block ("confirmations" before # the current tip). def get_median_time_past(self, confirmations): block_hash = self.nodes[0].getblockhash(self.nodes[0].getblockcount()-confirmations) return self.nodes[0].getblockheader(block_hash)["mediantime"] # Test that sequence locks are respected for transactions spending confirmed inputs. def test_sequence_lock_confirmed_inputs(self): # Create lots of confirmed utxos, and use them to generate lots of random # transactions. max_outputs = 50 addresses = [] while len(addresses) < max_outputs: addresses.append(self.nodes[0].getnewaddress()) while len(self.nodes[0].listunspent()) < 200: import random random.shuffle(addresses) num_outputs = random.randint(1, max_outputs) outputs = {} for i in range(num_outputs): outputs[addresses[i]] = random.randint(1, 20)*0.01 self.nodes[0].sendmany("", outputs) self.nodes[0].generate(1) utxos = self.nodes[0].listunspent() # Try creating a lot of random transactions. # Each time, choose a random number of inputs, and randomly set # some of those inputs to be sequence locked (and randomly choose # between height/time locking). Small random chance of making the locks # all pass. for i in range(400): # Randomly choose up to 10 inputs num_inputs = random.randint(1, 10) random.shuffle(utxos) # Track whether any sequence locks used should fail should_pass = True # Track whether this transaction was built with sequence locks using_sequence_locks = False tx = CTransaction() tx.nVersion = 2 value = 0 for j in range(num_inputs): sequence_value = 0xfffffffe # this disables sequence locks # 50% chance we enable sequence locks if random.randint(0,1): using_sequence_locks = True # 10% of the time, make the input sequence value pass input_will_pass = (random.randint(1,10) == 1) sequence_value = utxos[j]["confirmations"] if not input_will_pass: sequence_value += 1 should_pass = False # Figure out what the median-time-past was for the confirmed input # Note that if an input has N confirmations, we're going back N blocks # from the tip so that we're looking up MTP of the block # PRIOR to the one the input appears in, as per the BIP68 spec. orig_time = self.get_median_time_past(utxos[j]["confirmations"]) cur_time = self.get_median_time_past(0) # MTP of the tip # can only timelock this input if it's not too old -- otherwise use height can_time_lock = True if ((cur_time - orig_time) >> SEQUENCE_LOCKTIME_GRANULARITY) >= SEQUENCE_LOCKTIME_MASK: can_time_lock = False # if time-lockable, then 50% chance we make this a time lock if random.randint(0,1) and can_time_lock: # Find first time-lock value that fails, or latest one that succeeds time_delta = sequence_value << SEQUENCE_LOCKTIME_GRANULARITY if input_will_pass and time_delta > cur_time - orig_time: sequence_value = ((cur_time - orig_time) >> SEQUENCE_LOCKTIME_GRANULARITY) elif (not input_will_pass and time_delta <= cur_time - orig_time): sequence_value = ((cur_time - orig_time) >> SEQUENCE_LOCKTIME_GRANULARITY)+1 sequence_value |= SEQUENCE_LOCKTIME_TYPE_FLAG tx.vin.append(CTxIn(COutPoint(int(utxos[j]["txid"], 16), utxos[j]["vout"]), nSequence=sequence_value)) value += utxos[j]["amount"]*COIN # Overestimate the size of the tx - signatures should be less than 120 bytes, and leave 50 for the output tx_size = len(ToHex(tx))//2 + 120*num_inputs + 50 tx.vout.append(CTxOut(int(value-self.relayfee*tx_size*COIN/1000), CScript([b'a']))) rawtx = self.nodes[0].signrawtransactionwithwallet(ToHex(tx))["hex"] if (using_sequence_locks and not should_pass): # This transaction should be rejected assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, rawtx) else: # This raw transaction should be accepted self.nodes[0].sendrawtransaction(rawtx) utxos = self.nodes[0].listunspent() # Test that sequence locks on unconfirmed inputs must have nSequence # height or time of 0 to be accepted. # Then test that BIP68-invalid transactions are removed from the mempool # after a reorg. def test_sequence_lock_unconfirmed_inputs(self): # Store height so we can easily reset the chain at the end of the test cur_height = self.nodes[0].getblockcount() # Create a mempool tx. txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 2) tx1 = FromHex(CTransaction(), self.nodes[0].getrawtransaction(txid)) tx1.rehash() # Anyone-can-spend mempool tx. # Sequence lock of 0 should pass. tx2 = CTransaction() tx2.nVersion = 2 tx2.vin = [CTxIn(COutPoint(tx1.sha256, 0), nSequence=0)] tx2.vout = [CTxOut(int(tx1.vout[0].nValue - self.relayfee*COIN), CScript([b'a']))] tx2_raw = self.nodes[0].signrawtransactionwithwallet(ToHex(tx2))["hex"] tx2 = FromHex(tx2, tx2_raw) tx2.rehash() self.nodes[0].sendrawtransaction(tx2_raw) # Create a spend of the 0th output of orig_tx with a sequence lock # of 1, and test what happens when submitting. # orig_tx.vout[0] must be an anyone-can-spend output def test_nonzero_locks(orig_tx, node, relayfee, use_height_lock): sequence_value = 1 if not use_height_lock: sequence_value |= SEQUENCE_LOCKTIME_TYPE_FLAG tx = CTransaction() tx.nVersion = 2 tx.vin = [CTxIn(COutPoint(orig_tx.sha256, 0), nSequence=sequence_value)] tx.vout = [CTxOut(int(orig_tx.vout[0].nValue - relayfee * COIN), CScript([b'a' * 35]))] tx.rehash() if (orig_tx.hash in node.getrawmempool()): # sendrawtransaction should fail if the tx is in the mempool assert_raises_rpc_error(-26, NOT_FINAL_ERROR, node.sendrawtransaction, ToHex(tx)) else: # sendrawtransaction should succeed if the tx is not in the mempool node.sendrawtransaction(ToHex(tx)) return tx test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=True) test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False) # Now mine some blocks, but make sure tx2 doesn't get mined. # Use prioritisetransaction to lower the effective feerate to 0 self.nodes[0].prioritisetransaction(txid=tx2.hash, fee_delta=int(-self.relayfee*COIN)) cur_time = int(time.time()) for i in range(10): self.nodes[0].setmocktime(cur_time + 600) self.nodes[0].generate(1) cur_time += 600 assert(tx2.hash in self.nodes[0].getrawmempool()) test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=True) test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False) # Mine tx2, and then try again self.nodes[0].prioritisetransaction(txid=tx2.hash, fee_delta=int(self.relayfee*COIN)) # Advance the time on the node so that we can test timelocks self.nodes[0].setmocktime(cur_time+600) self.nodes[0].generate(1) assert(tx2.hash not in self.nodes[0].getrawmempool()) # Now that tx2 is not in the mempool, a sequence locked spend should # succeed tx3 = test_nonzero_locks(tx2, self.nodes[0], self.relayfee, use_height_lock=False) assert(tx3.hash in self.nodes[0].getrawmempool()) self.nodes[0].generate(1) assert(tx3.hash not in self.nodes[0].getrawmempool()) # One more test, this time using height locks tx4 = test_nonzero_locks(tx3, self.nodes[0], self.relayfee, use_height_lock=True) assert(tx4.hash in self.nodes[0].getrawmempool()) # Now try combining confirmed and unconfirmed inputs tx5 = test_nonzero_locks(tx4, self.nodes[0], self.relayfee, use_height_lock=True) assert(tx5.hash not in self.nodes[0].getrawmempool()) utxos = self.nodes[0].listunspent() tx5.vin.append(CTxIn(COutPoint(int(utxos[0]["txid"], 16), utxos[0]["vout"]), nSequence=1)) tx5.vout[0].nValue += int(utxos[0]["amount"]*COIN) raw_tx5 = self.nodes[0].signrawtransactionwithwallet(ToHex(tx5))["hex"] assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, raw_tx5) # Test mempool-BIP68 consistency after reorg # # State of the transactions in the last blocks: # ... -> [ tx2 ] -> [ tx3 ] # tip-1 tip # And currently tx4 is in the mempool. # # If we invalidate the tip, tx3 should get added to the mempool, causing # tx4 to be removed (fails sequence-lock). self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) assert(tx4.hash not in self.nodes[0].getrawmempool()) assert(tx3.hash in self.nodes[0].getrawmempool()) # Now mine 2 empty blocks to reorg out the current tip (labeled tip-1 in # diagram above). # This would cause tx2 to be added back to the mempool, which in turn causes # tx3 to be removed. tip = int(self.nodes[0].getblockhash(self.nodes[0].getblockcount()-1), 16) height = self.nodes[0].getblockcount() for i in range(2): block = create_block(tip, create_coinbase(height), cur_time) block.nVersion = 3 block.rehash() block.solve() tip = block.sha256 height += 1 self.nodes[0].submitblock(ToHex(block)) cur_time += 1 mempool = self.nodes[0].getrawmempool() assert(tx3.hash not in mempool) assert(tx2.hash in mempool) # Reset the chain and get rid of the mocktimed-blocks self.nodes[0].setmocktime(0) self.nodes[0].invalidateblock(self.nodes[0].getblockhash(cur_height+1)) self.nodes[0].generate(10) # Make sure that BIP68 isn't being used to validate blocks, prior to # versionbits activation. If more blocks are mined prior to this test # being run, then it's possible the test has activated the soft fork, and # this test should be moved to run earlier, or deleted. def test_bip68_not_consensus(self): assert(get_bip9_status(self.nodes[0], 'csv')['status'] != 'active') txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 2) tx1 = FromHex(CTransaction(), self.nodes[0].getrawtransaction(txid)) tx1.rehash() # Make an anyone-can-spend transaction tx2 = CTransaction() tx2.nVersion = 1 tx2.vin = [CTxIn(COutPoint(tx1.sha256, 0), nSequence=0)] tx2.vout = [CTxOut(int(tx1.vout[0].nValue - self.relayfee*COIN), CScript([b'a']))] # sign tx2 tx2_raw = self.nodes[0].signrawtransactionwithwallet(ToHex(tx2))["hex"] tx2 = FromHex(tx2, tx2_raw) tx2.rehash() self.nodes[0].sendrawtransaction(ToHex(tx2)) # Now make an invalid spend of tx2 according to BIP68 sequence_value = 100 # 100 block relative locktime tx3 = CTransaction() tx3.nVersion = 2 tx3.vin = [CTxIn(COutPoint(tx2.sha256, 0), nSequence=sequence_value)] tx3.vout = [CTxOut(int(tx2.vout[0].nValue - self.relayfee * COIN), CScript([b'a' * 35]))] tx3.rehash() assert_raises_rpc_error(-26, NOT_FINAL_ERROR, self.nodes[0].sendrawtransaction, ToHex(tx3)) # make a block that violates bip68; ensure that the tip updates tip = int(self.nodes[0].getbestblockhash(), 16) block = create_block(tip, create_coinbase(self.nodes[0].getblockcount()+1)) block.nVersion = 3 block.vtx.extend([tx1, tx2, tx3]) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() add_witness_commitment(block) block.solve() self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert_equal(self.nodes[0].getbestblockhash(), block.hash) def activateCSV(self): # activation should happen at block height 432 (3 periods) # getblockchaininfo will show CSV as active at block 431 (144 * 3 -1) since it's returning whether CSV is active for the next block. min_activation_height = 432 height = self.nodes[0].getblockcount() assert_greater_than(min_activation_height - height, 2) self.nodes[0].generate(min_activation_height - height - 2) assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], "locked_in") self.nodes[0].generate(1) assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], "active") sync_blocks(self.nodes) # Use self.nodes[1] to test that version 2 transactions are standard. def test_version2_relay(self): inputs = [ ] outputs = { self.nodes[1].getnewaddress() : 1.0 } rawtx = self.nodes[1].createrawtransaction(inputs, outputs) rawtxfund = self.nodes[1].fundrawtransaction(rawtx)['hex'] tx = FromHex(CTransaction(), rawtxfund) tx.nVersion = 2 tx_signed = self.nodes[1].signrawtransactionwithwallet(ToHex(tx))["hex"] self.nodes[1].sendrawtransaction(tx_signed) if __name__ == '__main__': BIP68Test().main()
45.471464
153
0.639291
ef8a8e2f16bb3a627216a078f7b0c96859b5f665
2,657
py
Python
ciscoisesdk/models/validators/v3_0_0/jsd_b14d63c641e95ac0a8c2da2fb65909c7.py
oianson/ciscoisesdk
c8fe9d80416048dd0ff2241209c4f78ab78c1a4a
[ "MIT" ]
null
null
null
ciscoisesdk/models/validators/v3_0_0/jsd_b14d63c641e95ac0a8c2da2fb65909c7.py
oianson/ciscoisesdk
c8fe9d80416048dd0ff2241209c4f78ab78c1a4a
[ "MIT" ]
null
null
null
ciscoisesdk/models/validators/v3_0_0/jsd_b14d63c641e95ac0a8c2da2fb65909c7.py
oianson/ciscoisesdk
c8fe9d80416048dd0ff2241209c4f78ab78c1a4a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """Identity Services Engine createEndpointGroup data model. Copyright (c) 2021 Cisco and/or its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import fastjsonschema import json from ciscoisesdk.exceptions import MalformedRequest from builtins import * class JSONSchemaValidatorB14D63C641E95Ac0A8C2Da2Fb65909C7(object): """createEndpointGroup request schema definition.""" def __init__(self): super(JSONSchemaValidatorB14D63C641E95Ac0A8C2Da2Fb65909C7, self).__init__() self._validator = fastjsonschema.compile(json.loads( '''{ "$schema": "http://json-schema.org/draft-04/schema#", "properties": { "EndPointGroup": { "properties": { "description": { "type": "string" }, "id": { "type": "string" }, "name": { "type": "string" }, "systemDefined": { "type": "boolean" } }, "type": "object" } }, "type": "object" }'''.replace("\n" + ' ' * 16, '') )) def validate(self, request): try: self._validator(request) except fastjsonschema.exceptions.JsonSchemaException as e: raise MalformedRequest( '{} is invalid. Reason: {}'.format(request, e.message) )
34.064103
83
0.619872
a95b5a21c242fa06d26a0dd668881ddb4d056abf
551
py
Python
manage.py
veshitala/DatadiscussForum
8ebe56db680b084093bf9b5bf1d5cff737aa3e3a
[ "MIT" ]
null
null
null
manage.py
veshitala/DatadiscussForum
8ebe56db680b084093bf9b5bf1d5cff737aa3e3a
[ "MIT" ]
38
2019-04-15T13:08:33.000Z
2021-08-23T01:10:19.000Z
manage.py
veshitala/DatadiscussForum
8ebe56db680b084093bf9b5bf1d5cff737aa3e3a
[ "MIT" ]
null
null
null
#!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_simple_forum.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
34.4375
83
0.693285
824145efa851c0bd6bce92a60bcaedd88ebbd042
4,885
py
Python
app/main.py
VadymHutei/claims
0b5522e844b1e3862b71044d3e63acf649e5ceeb
[ "MIT" ]
null
null
null
app/main.py
VadymHutei/claims
0b5522e844b1e3862b71044d3e63acf649e5ceeb
[ "MIT" ]
null
null
null
app/main.py
VadymHutei/claims
0b5522e844b1e3862b71044d3e63acf649e5ceeb
[ "MIT" ]
null
null
null
import datetime from random import choice from flask import Flask, render_template, request, redirect, url_for, make_response from claims_model import Model import conf # Variables tokens = [] app = Flask(__name__) model = Model() # Functions def createRandomString(n=8): abc = 'abcdefghijklmnopqrstuvwxyz0123456789' return ''.join([choice(abc) for _ in range(n)]) def isAuth(): cookie = request.cookies.get('cat') return cookie is not None and cookie in tokens def auth(): password = request.form['password'] return password == conf.ACP_CURRENT_CONFIG['password'] def createToken(): token = createRandomString(16) tokens.append(token) return token def createStoreId(): store_id = createRandomString(8) return store_id def login(): model.addAdminSession(request.headers.get('User-Agent', 'Unknown User-Agent')) token = createToken() expire_date = datetime.datetime.now() expire_date = expire_date + datetime.timedelta(**conf.ACP_CURRENT_CONFIG['cookie_lifetime']) response = make_response(redirect(url_for('acp'))) response.set_cookie('cat', token, expires=expire_date) return response def auth_decorator(func): def wrap(): if not isAuth(): return redirect(url_for('acp_login')) return func() wrap.__name__ = func.__name__ return wrap # App @app.route('/', methods=['GET']) def main(): return render_template('main.html') # ACP @app.route('/acp/', methods=['GET']) @auth_decorator def acp(): return render_template('acp/main.html') # Авторизация @app.route('/acp/login', methods=['GET']) def acp_login(): return render_template('acp/login.html') @app.route('/acp/auth', methods=['POST']) def acp_auth(): if auth(): return login() return redirect(url_for('acp_login')) # Магазины @app.route('/acp/stores/', methods=['GET']) @auth_decorator def acp_stores(): sort = request.args.get('sort', 'city') stores, sorted_stores_ids = model.getStores(sort) managers = model.getManagers() return render_template('acp/stores.html', stores=stores, sorted_stores_ids=sorted_stores_ids, managers=managers) @app.route('/acp/stores/<path:store_id>', methods=['GET']) @auth_decorator def acp_store(store_id): store = model.getStore(store_id) manager = model.getManager(store['manager_id']) claims = model.getClaims(store_id) return render_template('acp/store.html', store=store, manager=manager, claims=claims) @app.route('/acp/stores/add/', methods=['GET']) @auth_decorator def acp_store_add(): new_store_id = createStoreId() managers = model.getManagers() return render_template('acp/add_store.html', managers=managers, new_store_id=new_store_id) @app.route('/acp/stores/insert', methods=['POST']) @auth_decorator def acp_store_insert(): model.insertStore(request.form.to_dict()) return redirect(url_for('acp_stores')) @app.route('/acp/stores/delete/<path:store_id>', methods=['GET']) @auth_decorator def acp_store_delete(store_id): model.deleteStore(store_id) return redirect(url_for('acp_stores')) @app.route('/acp/stores/edit/<path:store_id>', methods=['GET']) @auth_decorator def acp_store_edit(store_id): store = model.getStore(store_id) managers = model.getManagers() return render_template('acp/edit_store.html', store=store, managers=managers) @app.route('/acp/stores/update', methods=['POST']) @auth_decorator def acp_store_update(): model.updateStore(request.form.to_dict()) return redirect(url_for('acp_store_edit', store_id=request.form['id'])) # Менеджеры @app.route('/acp/managers/', methods=['GET']) @auth_decorator def acp_managers(): managers = model.getManagers() return render_template('acp/managers.html', managers=managers) @app.route('/acp/managers/add/', methods=['GET']) @auth_decorator def acp_manager_add(): managers = model.getManagers() return render_template('acp/add_manager.html') @app.route('/acp/managers/insert', methods=['POST']) @auth_decorator def acp_manager_insert(): model.insertManager(request.form.to_dict()) return redirect(url_for('acp_managers')) @app.route('/acp/managers/delete/<path:manager_id>', methods=['GET']) @auth_decorator def acp_manager_delete(manager_id): model.deleteManager(manager_id) return redirect(url_for('acp_managers')) @app.route('/acp/managers/edit/<path:manager_id>', methods=['GET']) @auth_decorator def acp_manager_edit(manager_id): managers = model.getManagers() return render_template('acp/edit_manager.html', manager=managers[int(manager_id)]) @app.route('/acp/managers/update', methods=['POST']) @auth_decorator def acp_manager_update(): model.updateМanager(request.form.to_dict()) return redirect(url_for('acp_manager_edit', manager_id=request.form['id'])) if __name__ == '__main__': app.run(**conf.APP_CURRENT_PARAMS)
29.077381
116
0.719754
7b719f9de38fc7f9d5f12198e40e3da3ba8da0e4
5,687
py
Python
lib3to2/fixes/fix_unpacking.py
hajs/lib3to2_fork
4a2c734398493c5ff72857f3b849895aecdfc3f7
[ "Apache-2.0" ]
3
2021-03-29T19:21:08.000Z
2021-12-31T09:30:11.000Z
VisionAPI/lib/python3.8/site-packages/lib3to2/fixes/fix_unpacking.py
aniruddhakj/AnswerScriptEvaluation
7b039b84355ecda1d55dc037ccfc4a4d661ad5e3
[ "BSD-3-Clause" ]
1
2019-05-07T11:15:34.000Z
2019-05-07T11:15:34.000Z
env/lib/python2.7/site-packages/lib3to2/fixes/fix_unpacking.py
Eric-Muthemba/qontroverse
1f12d0e3bbdee628a88bac77dc53426ded220755
[ "MIT" ]
2
2019-01-22T01:05:22.000Z
2019-09-27T12:32:22.000Z
""" Fixer for: (a,)* *b (,c)* [,] = s for (a,)* *b (,c)* [,] in d: ... """ from lib2to3 import fixer_base from itertools import count from ..fixer_util import Assign, Comma, Call, Newline, Name, Number, indentation, suitify, commatize, token, syms, Node, Leaf def assignment_source(num_pre, num_post, LISTNAME, ITERNAME): """ Accepts num_pre and num_post, which are counts of values before and after the starg (not including the starg) Returns a source fit for Assign() from fixer_util """ children = [] pre = str(num_pre) post = str(num_post) # This code builds the assignment source from lib2to3 tree primitives. # It's not very readable, but it seems like the most correct way to do it. if num_pre > 0: pre_part = Node(syms.power, [Name(LISTNAME), Node(syms.trailer, [Leaf(token.LSQB, "["), Node(syms.subscript, [Leaf(token.COLON, ":"), Number(pre)]), Leaf(token.RSQB, "]")])]) children.append(pre_part) children.append(Leaf(token.PLUS, "+", prefix=" ")) main_part = Node(syms.power, [Leaf(token.LSQB, "[", prefix=" "), Name(LISTNAME), Node(syms.trailer, [Leaf(token.LSQB, "["), Node(syms.subscript, [Number(pre) if num_pre > 0 else Leaf(1, ""), Leaf(token.COLON, ":"), Node(syms.factor, [Leaf(token.MINUS, "-"), Number(post)]) if num_post > 0 else Leaf(1, "")]), Leaf(token.RSQB, "]"), Leaf(token.RSQB, "]")])]) children.append(main_part) if num_post > 0: children.append(Leaf(token.PLUS, "+", prefix=" ")) post_part = Node(syms.power, [Name(LISTNAME, prefix=" "), Node(syms.trailer, [Leaf(token.LSQB, "["), Node(syms.subscript, [Node(syms.factor, [Leaf(token.MINUS, "-"), Number(post)]), Leaf(token.COLON, ":")]), Leaf(token.RSQB, "]")])]) children.append(post_part) source = Node(syms.arith_expr, children) return source class FixUnpacking(fixer_base.BaseFix): PATTERN = """ expl=expr_stmt< testlist_star_expr< pre=(any ',')* star_expr< '*' name=NAME > post=(',' any)* [','] > '=' source=any > | impl=for_stmt< 'for' lst=exprlist< pre=(any ',')* star_expr< '*' name=NAME > post=(',' any)* [','] > 'in' it=any ':' suite=any>""" def fix_explicit_context(self, node, results): pre, name, post, source = (results.get(n) for n in ("pre", "name", "post", "source")) pre = [n.clone() for n in pre if n.type == token.NAME] name.prefix = " " post = [n.clone() for n in post if n.type == token.NAME] target = [n.clone() for n in commatize(pre + [name.clone()] + post)] # to make the special-case fix for "*z, = ..." correct with the least # amount of modification, make the left-side into a guaranteed tuple target.append(Comma()) source.prefix = "" setup_line = Assign(Name(self.LISTNAME), Call(Name("list"), [source.clone()])) power_line = Assign(target, assignment_source(len(pre), len(post), self.LISTNAME, self.ITERNAME)) return setup_line, power_line def fix_implicit_context(self, node, results): """ Only example of the implicit context is a for loop, so only fix that. """ pre, name, post, it = (results.get(n) for n in ("pre", "name", "post", "it")) pre = [n.clone() for n in pre if n.type == token.NAME] name.prefix = " " post = [n.clone() for n in post if n.type == token.NAME] target = [n.clone() for n in commatize(pre + [name.clone()] + post)] # to make the special-case fix for "*z, = ..." correct with the least # amount of modification, make the left-side into a guaranteed tuple target.append(Comma()) source = it.clone() source.prefix = "" setup_line = Assign(Name(self.LISTNAME), Call(Name("list"), [Name(self.ITERNAME)])) power_line = Assign(target, assignment_source(len(pre), len(post), self.LISTNAME, self.ITERNAME)) return setup_line, power_line def transform(self, node, results): """ a,b,c,d,e,f,*g,h,i = range(100) changes to _3to2list = list(range(100)) a,b,c,d,e,f,g,h,i, = _3to2list[:6] + [_3to2list[6:-2]] + _3to2list[-2:] and for a,b,*c,d,e in iter_of_iters: do_stuff changes to for _3to2iter in iter_of_iters: _3to2list = list(_3to2iter) a,b,c,d,e, = _3to2list[:2] + [_3to2list[2:-2]] + _3to2list[-2:] do_stuff """ self.LISTNAME = self.new_name("_3to2list") self.ITERNAME = self.new_name("_3to2iter") expl, impl = results.get("expl"), results.get("impl") if expl is not None: setup_line, power_line = self.fix_explicit_context(node, results) setup_line.prefix = expl.prefix power_line.prefix = indentation(expl.parent) setup_line.append_child(Newline()) parent = node.parent i = node.remove() parent.insert_child(i, power_line) parent.insert_child(i, setup_line) elif impl is not None: setup_line, power_line = self.fix_implicit_context(node, results) suitify(node) suite = [k for k in node.children if k.type == syms.suite][0] setup_line.prefix = "" power_line.prefix = suite.children[1].value suite.children[2].prefix = indentation(suite.children[2]) suite.insert_child(2, Newline()) suite.insert_child(2, power_line) suite.insert_child(2, Newline()) suite.insert_child(2, setup_line) results.get("lst").replace(Name(self.ITERNAME, prefix=" "))
48.194915
361
0.596976
2a4deec7a8bf5b8445793105ce1500d86ea17af4
79,898
py
Python
stubs/micropython-v1_18-docstubs/pyb.py
mattytrentini/micropython-stubs
4d596273823b69e9e5bcf5fa67f249c374ee0bbc
[ "MIT" ]
null
null
null
stubs/micropython-v1_18-docstubs/pyb.py
mattytrentini/micropython-stubs
4d596273823b69e9e5bcf5fa67f249c374ee0bbc
[ "MIT" ]
null
null
null
stubs/micropython-v1_18-docstubs/pyb.py
mattytrentini/micropython-stubs
4d596273823b69e9e5bcf5fa67f249c374ee0bbc
[ "MIT" ]
null
null
null
""" functions related to the board. See: https://docs.micropython.org/en/v1.18/library/pyb.html The ``pyb`` module contains specific functions related to the board. """ # source version: v1_18 # origin module:: micropython/docs/library/pyb.rst # + module: pyb.Accel.rst # + module: pyb.ADC.rst # + module: pyb.CAN.rst # + module: pyb.DAC.rst # + module: pyb.ExtInt.rst # + module: pyb.Flash.rst # + module: pyb.I2C.rst # + module: pyb.LCD.rst # + module: pyb.LED.rst # + module: pyb.Pin.rst # + module: pyb.RTC.rst # + module: pyb.Servo.rst # + module: pyb.SPI.rst # + module: pyb.Switch.rst # + module: pyb.Timer.rst # + module: pyb.UART.rst # + module: pyb.USB_HID.rst # + module: pyb.USB_VCP.rst from typing import Any, List, NoReturn, Optional, Tuple class Accel: """ Create and return an accelerometer object. """ def __init__(self) -> None: ... def filtered_xyz(self) -> Tuple: """ Get a 3-tuple of filtered x, y and z values. Implementation note: this method is currently implemented as taking the sum of 4 samples, sampled from the 3 previous calls to this function along with the sample from the current call. Returned values are therefore 4 times the size of what they would be from the raw x(), y() and z() calls. """ ... def tilt(self) -> Any: """ Get the tilt register. """ ... def x(self) -> Any: """ Get the x-axis value. """ ... def y(self) -> Any: """ Get the y-axis value. """ ... def z(self) -> Any: """ Get the z-axis value. """ ... class ADC: """ Create an ADC object associated with the given pin. This allows you to then read analog values on that pin. """ def __init__(self, pin) -> None: ... def read(self) -> Any: """ Read the value on the analog pin and return it. The returned value will be between 0 and 4095. """ ... def read_timed(self, buf, timer) -> Any: """ Read analog values into ``buf`` at a rate set by the ``timer`` object. ``buf`` can be bytearray or array.array for example. The ADC values have 12-bit resolution and are stored directly into ``buf`` if its element size is 16 bits or greater. If ``buf`` has only 8-bit elements (eg a bytearray) then the sample resolution will be reduced to 8 bits. ``timer`` should be a Timer object, and a sample is read each time the timer triggers. The timer must already be initialised and running at the desired sampling frequency. To support previous behaviour of this function, ``timer`` can also be an integer which specifies the frequency (in Hz) to sample at. In this case Timer(6) will be automatically configured to run at the given frequency. Example using a Timer object (preferred way):: adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19 tim = pyb.Timer(6, freq=10) # create a timer running at 10Hz buf = bytearray(100) # creat a buffer to store the samples adc.read_timed(buf, tim) # sample 100 values, taking 10s Example using an integer for the frequency:: adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19 buf = bytearray(100) # create a buffer of 100 bytes adc.read_timed(buf, 10) # read analog values into buf at 10Hz # this will take 10 seconds to finish for val in buf: # loop over all values print(val) # print the value out This function does not allocate any heap memory. It has blocking behaviour: it does not return to the calling program until the buffer is full. """ ... def read_timed_multi(self, adcs, bufs, timer) -> bool: """ This is a static method. It can be used to extract relative timing or phase data from multiple ADC's. It reads analog values from multiple ADC's into buffers at a rate set by the *timer* object. Each time the timer triggers a sample is rapidly read from each ADC in turn. ADC and buffer instances are passed in tuples with each ADC having an associated buffer. All buffers must be of the same type and length and the number of buffers must equal the number of ADC's. Buffers can be ``bytearray`` or ``array.array`` for example. The ADC values have 12-bit resolution and are stored directly into the buffer if its element size is 16 bits or greater. If buffers have only 8-bit elements (eg a ``bytearray``) then the sample resolution will be reduced to 8 bits. *timer* must be a Timer object. The timer must already be initialised and running at the desired sampling frequency. Example reading 3 ADC's:: adc0 = pyb.ADC(pyb.Pin.board.X1) # Create ADC's adc1 = pyb.ADC(pyb.Pin.board.X2) adc2 = pyb.ADC(pyb.Pin.board.X3) tim = pyb.Timer(8, freq=100) # Create timer rx0 = array.array('H', (0 for i in range(100))) # ADC buffers of rx1 = array.array('H', (0 for i in range(100))) # 100 16-bit words rx2 = array.array('H', (0 for i in range(100))) # read analog values into buffers at 100Hz (takes one second) pyb.ADC.read_timed_multi((adc0, adc1, adc2), (rx0, rx1, rx2), tim) for n in range(len(rx0)): print(rx0[n], rx1[n], rx2[n]) This function does not allocate any heap memory. It has blocking behaviour: it does not return to the calling program until the buffers are full. The function returns ``True`` if all samples were acquired with correct timing. At high sample rates the time taken to acquire a set of samples can exceed the timer period. In this case the function returns ``False``, indicating a loss of precision in the sample interval. In extreme cases samples may be missed. The maximum rate depends on factors including the data width and the number of ADC's being read. In testing two ADC's were sampled at a timer rate of 210kHz without overrun. Samples were missed at 215kHz. For three ADC's the limit is around 140kHz, and for four it is around 110kHz. At high sample rates disabling interrupts for the duration can reduce the risk of sporadic data loss. """ ... class CAN: """ Construct a CAN object on the given bus. *bus* can be 1-2, or ``'YA'`` or ``'YB'``. With no additional parameters, the CAN object is created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra arguments are given, the bus is initialised. See :meth:`CAN.init` for parameters of initialisation. The physical pins of the CAN buses are: - ``CAN(1)`` is on ``YA``: ``(RX, TX) = (Y3, Y4) = (PB8, PB9)`` - ``CAN(2)`` is on ``YB``: ``(RX, TX) = (Y5, Y6) = (PB12, PB13)`` """ # The mode of the CAN bus used in :meth:`~CAN.init()`. NORMAL: Any # The mode of the CAN bus used in :meth:`~CAN.init()`. LOOPBACK: Any # The mode of the CAN bus used in :meth:`~CAN.init()`. SILENT: Any # The mode of the CAN bus used in :meth:`~CAN.init()`. SILENT_LOOPBACK: Any # Possible states of the CAN controller returned from :meth:`~CAN.state()`. STOPPED: Any # Possible states of the CAN controller returned from :meth:`~CAN.state()`. ERROR_ACTIVE: Any # Possible states of the CAN controller returned from :meth:`~CAN.state()`. ERROR_WARNING: Any # Possible states of the CAN controller returned from :meth:`~CAN.state()`. ERROR_PASSIVE: Any # Possible states of the CAN controller returned from :meth:`~CAN.state()`. BUS_OFF: Any # The operation mode of a filter used in :meth:`~CAN.setfilter()`. LIST16: Any # The operation mode of a filter used in :meth:`~CAN.setfilter()`. MASK16: Any # The operation mode of a filter used in :meth:`~CAN.setfilter()`. LIST32: Any # The operation mode of a filter used in :meth:`~CAN.setfilter()`. MASK32: Any def __init__(self, bus, *args) -> None: ... @classmethod def initfilterbanks(cls, nr) -> None: """ Reset and disable all filter banks and assign how many banks should be available for CAN(1). STM32F405 has 28 filter banks that are shared between the two available CAN bus controllers. This function configures how many filter banks should be assigned to each. *nr* is the number of banks that will be assigned to CAN(1), the rest of the 28 are assigned to CAN(2). At boot, 14 banks are assigned to each controller. """ ... def init(self, mode, extframe=False, prescaler=100, *, sjw=1, bs1=6, bs2=8, auto_restart=False, baudrate=0, sample_point=75) -> None: """ Initialise the CAN bus with the given parameters: - *mode* is one of: NORMAL, LOOPBACK, SILENT, SILENT_LOOPBACK - if *extframe* is True then the bus uses extended identifiers in the frames (29 bits); otherwise it uses standard 11 bit identifiers - *prescaler* is used to set the duration of 1 time quanta; the time quanta will be the input clock (PCLK1, see :meth:`pyb.freq()`) divided by the prescaler - *sjw* is the resynchronisation jump width in units of the time quanta; it can be 1, 2, 3, 4 - *bs1* defines the location of the sample point in units of the time quanta; it can be between 1 and 1024 inclusive - *bs2* defines the location of the transmit point in units of the time quanta; it can be between 1 and 16 inclusive - *auto_restart* sets whether the controller will automatically try and restart communications after entering the bus-off state; if this is disabled then :meth:`~CAN.restart()` can be used to leave the bus-off state - *baudrate* if a baudrate other than 0 is provided, this function will try to automatically calculate a CAN bit-timing (overriding *prescaler*, *bs1* and *bs2*) that satisfies both the baudrate and the desired *sample_point*. - *sample_point* given in a percentage of the bit time, the *sample_point* specifies the position of the last bit sample with respect to the whole bit time. The default *sample_point* is 75%. The time quanta tq is the basic unit of time for the CAN bus. tq is the CAN prescaler value divided by PCLK1 (the frequency of internal peripheral bus 1); see :meth:`pyb.freq()` to determine PCLK1. A single bit is made up of the synchronisation segment, which is always 1 tq. Then follows bit segment 1, then bit segment 2. The sample point is after bit segment 1 finishes. The transmit point is after bit segment 2 finishes. The baud rate will be 1/bittime, where the bittime is 1 + BS1 + BS2 multiplied by the time quanta tq. For example, with PCLK1=42MHz, prescaler=100, sjw=1, bs1=6, bs2=8, the value of tq is 2.38 microseconds. The bittime is 35.7 microseconds, and the baudrate is 28kHz. See page 680 of the STM32F405 datasheet for more details. """ ... def deinit(self) -> None: """ Turn off the CAN bus. """ ... def restart(self) -> Any: """ Force a software restart of the CAN controller without resetting its configuration. If the controller enters the bus-off state then it will no longer participate in bus activity. If the controller is not configured to automatically restart (see :meth:`~CAN.init()`) then this method can be used to trigger a restart, and the controller will follow the CAN protocol to leave the bus-off state and go into the error active state. """ ... def state(self) -> Any: """ Return the state of the controller. The return value can be one of: - ``CAN.STOPPED`` -- the controller is completely off and reset; - ``CAN.ERROR_ACTIVE`` -- the controller is on and in the Error Active state (both TEC and REC are less than 96); - ``CAN.ERROR_WARNING`` -- the controller is on and in the Error Warning state (at least one of TEC or REC is 96 or greater); - ``CAN.ERROR_PASSIVE`` -- the controller is on and in the Error Passive state (at least one of TEC or REC is 128 or greater); - ``CAN.BUS_OFF`` -- the controller is on but not participating in bus activity (TEC overflowed beyond 255). """ ... def info(self, list: Optional[Any]) -> Any: """ Get information about the controller's error states and TX and RX buffers. If *list* is provided then it should be a list object with at least 8 entries, which will be filled in with the information. Otherwise a new list will be created and filled in. In both cases the return value of the method is the populated list. The values in the list are: - TEC value - REC value - number of times the controller enterted the Error Warning state (wrapped around to 0 after 65535) - number of times the controller enterted the Error Passive state (wrapped around to 0 after 65535) - number of times the controller enterted the Bus Off state (wrapped around to 0 after 65535) - number of pending TX messages - number of pending RX messages on fifo 0 - number of pending RX messages on fifo 1 """ ... def setfilter(self, bank, mode, fifo, params, *, rtr) -> None: """ Configure a filter bank: - *bank* is the filter bank that is to be configured. - *mode* is the mode the filter should operate in. - *fifo* is which fifo (0 or 1) a message should be stored in, if it is accepted by this filter. - *params* is an array of values the defines the filter. The contents of the array depends on the *mode* argument. +-----------+---------------------------------------------------------+ |*mode* |contents of *params* array | +===========+=========================================================+ |CAN.LIST16 |Four 16 bit ids that will be accepted | +-----------+---------------------------------------------------------+ |CAN.LIST32 |Two 32 bit ids that will be accepted | +-----------+---------------------------------------------------------+ |CAN.MASK16 |Two 16 bit id/mask pairs. E.g. (1, 3, 4, 4) | | | | The first pair, 1 and 3 will accept all ids | | | | that have bit 0 = 1 and bit 1 = 0. | | | | The second pair, 4 and 4, will accept all ids | | | | that have bit 2 = 1. | +-----------+---------------------------------------------------------+ |CAN.MASK32 |As with CAN.MASK16 but with only one 32 bit id/mask pair.| +-----------+---------------------------------------------------------+ - *rtr* is an array of booleans that states if a filter should accept a remote transmission request message. If this argument is not given then it defaults to ``False`` for all entries. The length of the array depends on the *mode* argument. +-----------+----------------------+ |*mode* |length of *rtr* array | +===========+======================+ |CAN.LIST16 |4 | +-----------+----------------------+ |CAN.LIST32 |2 | +-----------+----------------------+ |CAN.MASK16 |2 | +-----------+----------------------+ |CAN.MASK32 |1 | +-----------+----------------------+ """ ... def clearfilter(self, bank) -> None: """ Clear and disables a filter bank: - *bank* is the filter bank that is to be cleared. """ ... def any(self, fifo) -> bool: """ Return ``True`` if any message waiting on the FIFO, else ``False``. """ ... def recv(self, fifo, list=None, *, timeout=5000) -> Tuple: """ Receive data on the bus: - *fifo* is an integer, which is the FIFO to receive on - *list* is an optional list object to be used as the return value - *timeout* is the timeout in milliseconds to wait for the receive. Return value: A tuple containing four values. - The id of the message. - A boolean that indicates if the message is an RTR message. - The FMI (Filter Match Index) value. - An array containing the data. If *list* is ``None`` then a new tuple will be allocated, as well as a new bytes object to contain the data (as the fourth element in the tuple). If *list* is not ``None`` then it should be a list object with a least four elements. The fourth element should be a memoryview object which is created from either a bytearray or an array of type 'B' or 'b', and this array must have enough room for at least 8 bytes. The list object will then be populated with the first three return values above, and the memoryview object will be resized inplace to the size of the data and filled in with that data. The same list and memoryview objects can be reused in subsequent calls to this method, providing a way of receiving data without using the heap. For example:: buf = bytearray(8) lst = [0, 0, 0, memoryview(buf)] # No heap memory is allocated in the following call can.recv(0, lst) """ ... def send(self, data, id, *, timeout=0, rtr=False) -> None: """ Send a message on the bus: - *data* is the data to send (an integer to send, or a buffer object). - *id* is the id of the message to be sent. - *timeout* is the timeout in milliseconds to wait for the send. - *rtr* is a boolean that specifies if the message shall be sent as a remote transmission request. If *rtr* is True then only the length of *data* is used to fill in the DLC slot of the frame; the actual bytes in *data* are unused. If timeout is 0 the message is placed in a buffer in one of three hardware buffers and the method returns immediately. If all three buffers are in use an exception is thrown. If timeout is not 0, the method waits until the message is transmitted. If the message can't be transmitted within the specified time an exception is thrown. Return value: ``None``. """ ... def rxcallback(self, fifo, fun) -> None: """ Register a function to be called when a message is accepted into a empty fifo: - *fifo* is the receiving fifo. - *fun* is the function to be called when the fifo becomes non empty. The callback function takes two arguments the first is the can object it self the second is a integer that indicates the reason for the callback. +--------+------------------------------------------------+ | Reason | | +========+================================================+ | 0 | A message has been accepted into a empty FIFO. | +--------+------------------------------------------------+ | 1 | The FIFO is full | +--------+------------------------------------------------+ | 2 | A message has been lost due to a full FIFO | +--------+------------------------------------------------+ Example use of rxcallback:: def cb0(bus, reason): print('cb0') if reason == 0: print('pending') if reason == 1: print('full') if reason == 2: print('overflow') can = CAN(1, CAN.LOOPBACK) can.rxcallback(0, cb0) """ ... class DAC: """ Construct a new DAC object. ``port`` can be a pin object, or an integer (1 or 2). DAC(1) is on pin X5 and DAC(2) is on pin X6. ``bits`` is an integer specifying the resolution, and can be 8 or 12. The maximum value for the write and write_timed methods will be 2\*\*``bits``-1. The *buffering* parameter selects the behaviour of the DAC op-amp output buffer, whose purpose is to reduce the output impedance. It can be ``None`` to select the default (buffering enabled for :meth:`DAC.noise`, :meth:`DAC.triangle` and :meth:`DAC.write_timed`, and disabled for :meth:`DAC.write`), ``False`` to disable buffering completely, or ``True`` to enable output buffering. When buffering is enabled the DAC pin can drive loads down to 5KΩ. Otherwise it has an output impedance of 15KΩ maximum: consequently to achieve a 1% accuracy without buffering requires the applied load to be less than 1.5MΩ. Using the buffer incurs a penalty in accuracy, especially near the extremes of range. """ def __init__(self, port, bits=8, *, buffering=None) -> None: ... def init(self, bits=8, *, buffering=None) -> Any: """ Reinitialise the DAC. *bits* can be 8 or 12. *buffering* can be ``None``, ``False`` or ``True``; see above constructor for the meaning of this parameter. """ ... def deinit(self) -> Any: """ De-initialise the DAC making its pin available for other uses. """ ... def noise(self, freq) -> None: """ Generate a pseudo-random noise signal. A new random sample is written to the DAC output at the given frequency. """ ... def triangle(self, freq) -> None: """ Generate a triangle wave. The value on the DAC output changes at the given frequency and ramps through the full 12-bit range (up and down). Therefore the frequency of the repeating triangle wave itself is 8192 times smaller. """ ... def write(self, value) -> Any: """ Direct access to the DAC output. The minimum value is 0. The maximum value is 2\*\*``bits``-1, where ``bits`` is set when creating the DAC object or by using the ``init`` method. """ ... def write_timed(self, data, freq, *, mode=NORMAL) -> Any: """ Initiates a burst of RAM to DAC using a DMA transfer. The input data is treated as an array of bytes in 8-bit mode, and an array of unsigned half-words (array typecode 'H') in 12-bit mode. ``freq`` can be an integer specifying the frequency to write the DAC samples at, using Timer(6). Or it can be an already-initialised Timer object which is used to trigger the DAC sample. Valid timers are 2, 4, 5, 6, 7 and 8. ``mode`` can be ``DAC.NORMAL`` or ``DAC.CIRCULAR``. Example using both DACs at the same time:: dac1 = DAC(1) dac2 = DAC(2) dac1.write_timed(buf1, pyb.Timer(6, freq=100), mode=DAC.CIRCULAR) dac2.write_timed(buf2, pyb.Timer(7, freq=200), mode=DAC.CIRCULAR) """ ... class ExtInt: """ Create an ExtInt object: - ``pin`` is the pin on which to enable the interrupt (can be a pin object or any valid pin name). - ``mode`` can be one of: - ``ExtInt.IRQ_RISING`` - trigger on a rising edge; - ``ExtInt.IRQ_FALLING`` - trigger on a falling edge; - ``ExtInt.IRQ_RISING_FALLING`` - trigger on a rising or falling edge. - ``pull`` can be one of: - ``pyb.Pin.PULL_NONE`` - no pull up or down resistors; - ``pyb.Pin.PULL_UP`` - enable the pull-up resistor; - ``pyb.Pin.PULL_DOWN`` - enable the pull-down resistor. - ``callback`` is the function to call when the interrupt triggers. The callback function must accept exactly 1 argument, which is the line that triggered the interrupt. """ # interrupt on a falling edge IRQ_FALLING: Any # interrupt on a rising edge IRQ_RISING: Any # interrupt on a rising or falling edge IRQ_RISING_FALLING: Any def __init__(self, pin, mode, pull, callback) -> None: ... @classmethod def regs( cls, ) -> Any: """ Dump the values of the EXTI registers. """ ... def disable(self) -> None: """ Disable the interrupt associated with the ExtInt object. This could be useful for debouncing. """ ... def enable(self) -> None: """ Enable a disabled interrupt. """ ... def line(self) -> int: """ Return the line number that the pin is mapped to. """ ... def swint(self) -> Any: """ Trigger the callback from software. """ ... class Flash: """ Create and return a block device that represents the flash device presented to the USB mass storage interface. It includes a virtual partition table at the start, and the actual flash starts at block ``0x100``. This constructor is deprecated and will be removed in a future version of MicroPython. """ def __init__(self) -> None: ... def readblocks(self, block_num, buf, offset: Optional[int]) -> Any: ... def writeblocks(self, block_num, buf, offset: Optional[int]) -> Any: ... def ioctl(self, cmd, arg) -> Any: """ These methods implement the simple and :ref:`extended <block-device-interface>` block protocol defined by :class:`os.AbstractBlockDev`. """ ... class I2C: """ Construct an I2C object on the given bus. ``bus`` can be 1 or 2, 'X' or 'Y'. With no additional parameters, the I2C object is created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra arguments are given, the bus is initialised. See ``init`` for parameters of initialisation. The physical pins of the I2C buses on Pyboards V1.0 and V1.1 are: - ``I2C(1)`` is on the X position: ``(SCL, SDA) = (X9, X10) = (PB6, PB7)`` - ``I2C(2)`` is on the Y position: ``(SCL, SDA) = (Y9, Y10) = (PB10, PB11)`` On the Pyboard Lite: - ``I2C(1)`` is on the X position: ``(SCL, SDA) = (X9, X10) = (PB6, PB7)`` - ``I2C(3)`` is on the Y position: ``(SCL, SDA) = (Y9, Y10) = (PA8, PB8)`` Calling the constructor with 'X' or 'Y' enables portability between Pyboard types. """ # for initialising the bus to controller mode CONTROLLER: Any # for initialising the bus to peripheral mode PERIPHERAL: Any def __init__(self, bus, *args) -> None: ... def deinit(self) -> None: """ Turn off the I2C bus. """ ... def init(self, mode, *, addr=0x12, baudrate=400000, gencall=False, dma=False) -> None: """ Initialise the I2C bus with the given parameters: - ``mode`` must be either ``I2C.CONTROLLER`` or ``I2C.PERIPHERAL`` - ``addr`` is the 7-bit address (only sensible for a peripheral) - ``baudrate`` is the SCL clock rate (only sensible for a controller) - ``gencall`` is whether to support general call mode - ``dma`` is whether to allow the use of DMA for the I2C transfers (note that DMA transfers have more precise timing but currently do not handle bus errors properly) """ ... def is_ready(self, addr) -> Any: """ Check if an I2C device responds to the given address. Only valid when in controller mode. """ ... def mem_read(self, data, addr, memaddr, *, timeout=5000, addr_size=8) -> Any: """ Read from the memory of an I2C device: - ``data`` can be an integer (number of bytes to read) or a buffer to read into - ``addr`` is the I2C device address - ``memaddr`` is the memory location within the I2C device - ``timeout`` is the timeout in milliseconds to wait for the read - ``addr_size`` selects width of memaddr: 8 or 16 bits Returns the read data. This is only valid in controller mode. """ ... def mem_write(self, data, addr, memaddr, *, timeout=5000, addr_size=8) -> None: """ Write to the memory of an I2C device: - ``data`` can be an integer or a buffer to write from - ``addr`` is the I2C device address - ``memaddr`` is the memory location within the I2C device - ``timeout`` is the timeout in milliseconds to wait for the write - ``addr_size`` selects width of memaddr: 8 or 16 bits Returns ``None``. This is only valid in controller mode. """ ... def recv(self, recv, addr=0x00, *, timeout=5000) -> bytes: """ Receive data on the bus: - ``recv`` can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled with received bytes - ``addr`` is the address to receive from (only required in controller mode) - ``timeout`` is the timeout in milliseconds to wait for the receive Return value: if ``recv`` is an integer then a new buffer of the bytes received, otherwise the same buffer that was passed in to ``recv``. """ ... def send(self, send, addr=0x00, *, timeout=5000) -> None: """ Send data on the bus: - ``send`` is the data to send (an integer to send, or a buffer object) - ``addr`` is the address to send to (only required in controller mode) - ``timeout`` is the timeout in milliseconds to wait for the send Return value: ``None``. """ ... def scan(self) -> List: """ Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond. Only valid when in controller mode. """ ... class LCD: """ Construct an LCD object in the given skin position. ``skin_position`` can be 'X' or 'Y', and should match the position where the LCD pyskin is plugged in. """ def __init__(self, skin_position) -> None: ... def command(self, instr_data, buf) -> None: """ Send an arbitrary command to the LCD. Pass 0 for ``instr_data`` to send an instruction, otherwise pass 1 to send data. ``buf`` is a buffer with the instructions/data to send. """ ... def contrast(self, value) -> None: """ Set the contrast of the LCD. Valid values are between 0 and 47. """ ... def fill(self, colour) -> None: """ Fill the screen with the given colour (0 or 1 for white or black). This method writes to the hidden buffer. Use ``show()`` to show the buffer. """ ... def get(self, x, y) -> int: """ Get the pixel at the position ``(x, y)``. Returns 0 or 1. This method reads from the visible buffer. """ ... def light(self, value) -> None: """ Turn the backlight on/off. True or 1 turns it on, False or 0 turns it off. """ ... def pixel(self, x, y, colour) -> None: """ Set the pixel at ``(x, y)`` to the given colour (0 or 1). This method writes to the hidden buffer. Use ``show()`` to show the buffer. """ ... def show(self) -> None: """ Show the hidden buffer on the screen. """ ... def text(self, str, x, y, colour) -> None: """ Draw the given text to the position ``(x, y)`` using the given colour (0 or 1). This method writes to the hidden buffer. Use ``show()`` to show the buffer. """ ... def write(self, str) -> None: """ Write the string ``str`` to the screen. It will appear immediately. """ ... class LED: """ Create an LED object associated with the given LED: - ``id`` is the LED number, 1-4. """ def __init__(self, id) -> None: ... def intensity(self, value: Optional[Any]) -> None: """ Get or set the LED intensity. Intensity ranges between 0 (off) and 255 (full on). If no argument is given, return the LED intensity. If an argument is given, set the LED intensity and return ``None``. *Note:* Only LED(3) and LED(4) can have a smoothly varying intensity, and they use timer PWM to implement it. LED(3) uses Timer(2) and LED(4) uses Timer(3). These timers are only configured for PWM if the intensity of the relevant LED is set to a value between 1 and 254. Otherwise the timers are free for general purpose use. """ ... def off(self) -> None: """ Turn the LED off. """ ... def on(self) -> None: """ Turn the LED on, to maximum intensity. """ ... def toggle(self) -> Any: """ Toggle the LED between on (maximum intensity) and off. If the LED is at non-zero intensity then it is considered "on" and toggle will turn it off. """ ... class Pin: """ Create a new Pin object associated with the id. If additional arguments are given, they are used to initialise the pin. See :meth:`pin.init`. """ # initialise the pin to alternate-function mode with an open-drain drive AF_OD: Any # initialise the pin to alternate-function mode with a push-pull drive AF_PP: Any # initialise the pin to analog mode ANALOG: Any # initialise the pin to input mode IN: Any # initialise the pin to output mode with an open-drain drive OUT_OD: Any # initialise the pin to output mode with a push-pull drive OUT_PP: Any # enable the pull-down resistor on the pin PULL_DOWN: Any # don't enable any pull up or down resistors on the pin PULL_NONE: Any # enable the pull-up resistor on the pin PULL_UP: Any def __init__(self, id, *args) -> None: ... @classmethod def debug(cls, state: Optional[Any]) -> bool: """ Get or set the debugging state (``True`` or ``False`` for on or off). """ ... @classmethod def dict(cls, dict: Optional[Any]) -> Any: """ Get or set the pin mapper dictionary. """ ... @classmethod def mapper(cls, fun: Optional[Any]) -> Any: """ Get or set the pin mapper function. """ ... def init(self, mode, pull=PULL_NONE, *, value=None, alt=-1) -> None: """ Initialise the pin: - *mode* can be one of: - ``Pin.IN`` - configure the pin for input; - ``Pin.OUT_PP`` - configure the pin for output, with push-pull control; - ``Pin.OUT_OD`` - configure the pin for output, with open-drain control; - ``Pin.AF_PP`` - configure the pin for alternate function, pull-pull; - ``Pin.AF_OD`` - configure the pin for alternate function, open-drain; - ``Pin.ANALOG`` - configure the pin for analog. - *pull* can be one of: - ``Pin.PULL_NONE`` - no pull up or down resistors; - ``Pin.PULL_UP`` - enable the pull-up resistor; - ``Pin.PULL_DOWN`` - enable the pull-down resistor. - *value* if not None will set the port output value before enabling the pin. - *alt* can be used when mode is ``Pin.AF_PP`` or ``Pin.AF_OD`` to set the index or name of one of the alternate functions associated with a pin. This arg was previously called *af* which can still be used if needed. Returns: ``None``. """ ... def value(self, value: Optional[Any]) -> int: """ Get or set the digital logic level of the pin: - With no argument, return 0 or 1 depending on the logic level of the pin. - With ``value`` given, set the logic level of the pin. ``value`` can be anything that converts to a boolean. If it converts to ``True``, the pin is set high, otherwise it is set low. """ ... def __str__(self) -> str: """ Return a string describing the pin object. """ ... def af(self) -> Any: """ Returns the currently configured alternate-function of the pin. The integer returned will match one of the allowed constants for the af argument to the init function. """ ... def af_list(self) -> List: """ Returns an array of alternate functions available for this pin. """ ... def gpio(self) -> int: """ Returns the base address of the GPIO block associated with this pin. """ ... def mode(self) -> Any: """ Returns the currently configured mode of the pin. The integer returned will match one of the allowed constants for the mode argument to the init function. """ ... def name(self) -> str: """ Get the pin name. """ ... def names(self) -> str: """ Returns the cpu and board names for this pin. """ ... def pin(self) -> int: """ Get the pin number. """ ... def port(self) -> Any: """ Get the pin port. """ ... def pull(self) -> Any: """ Returns the currently configured pull of the pin. The integer returned will match one of the allowed constants for the pull argument to the init function. """ ... class Switch(Pin): """ Create and return a switch object. """ def __init__(self) -> None: ... def __call__(self) -> Any: """ Call switch object directly to get its state: ``True`` if pressed down, ``False`` otherwise. """ ... def value(self) -> bool: """ Get the switch state. Returns ``True`` if pressed down, otherwise ``False``. """ ... def callback(self, fun) -> None: """ Register the given function to be called when the switch is pressed down. If ``fun`` is ``None``, then it disables the callback. """ ... class pinaf: """ """ def __str__(self) -> str: """ Return a string describing the alternate function. """ ... def index(self) -> int: """ Return the alternate function index. """ ... def name(self) -> str: """ Return the name of the alternate function. """ ... def reg(self) -> Any: """ Return the base register associated with the peripheral assigned to this alternate function. For example, if the alternate function were TIM2_CH3 this would return stm.TIM2 """ ... class RTC: """ Create an RTC object. """ def __init__(self) -> None: ... def datetime(self, datetimetuple: Optional[Any]) -> Tuple: """ Get or set the date and time of the RTC. With no arguments, this method returns an 8-tuple with the current date and time. With 1 argument (being an 8-tuple) it sets the date and time (and ``subseconds`` is reset to 255). The 8-tuple has the following format: (year, month, day, weekday, hours, minutes, seconds, subseconds) ``weekday`` is 1-7 for Monday through Sunday. ``subseconds`` counts down from 255 to 0 """ ... def wakeup(self, timeout, callback=None) -> None: """ Set the RTC wakeup timer to trigger repeatedly at every ``timeout`` milliseconds. This trigger can wake the pyboard from both the sleep states: :meth:`pyb.stop` and :meth:`pyb.standby`. If ``timeout`` is ``None`` then the wakeup timer is disabled. If ``callback`` is given then it is executed at every trigger of the wakeup timer. ``callback`` must take exactly one argument. """ ... def info(self) -> Any: """ Get information about the startup time and reset source. - The lower 0xffff are the number of milliseconds the RTC took to start up. - Bit 0x10000 is set if a power-on reset occurred. - Bit 0x20000 is set if an external reset occurred """ ... def calibration(self, cal) -> int: """ Get or set RTC calibration. With no arguments, ``calibration()`` returns the current calibration value, which is an integer in the range [-511 : 512]. With one argument it sets the RTC calibration. The RTC Smooth Calibration mechanism adjusts the RTC clock rate by adding or subtracting the given number of ticks from the 32768 Hz clock over a 32 second period (corresponding to 2^20 clock ticks.) Each tick added will speed up the clock by 1 part in 2^20, or 0.954 ppm; likewise the RTC clock it slowed by negative values. The usable calibration range is: (-511 * 0.954) ~= -487.5 ppm up to (512 * 0.954) ~= 488.5 ppm """ ... class Servo: """ Create a servo object. ``id`` is 1-4, and corresponds to pins X1 through X4. """ def __init__(self, id) -> None: ... def angle(self, angle: Optional[Any], time=0) -> Any: """ If no arguments are given, this function returns the current angle. If arguments are given, this function sets the angle of the servo: - ``angle`` is the angle to move to in degrees. - ``time`` is the number of milliseconds to take to get to the specified angle. If omitted, then the servo moves as quickly as possible to its new position. """ ... def speed(self, speed: Optional[Any], time=0) -> Any: """ If no arguments are given, this function returns the current speed. If arguments are given, this function sets the speed of the servo: - ``speed`` is the speed to change to, between -100 and 100. - ``time`` is the number of milliseconds to take to get to the specified speed. If omitted, then the servo accelerates as quickly as possible. """ ... def pulse_width(self, value: Optional[Any]) -> Any: """ If no arguments are given, this function returns the current raw pulse-width value. If an argument is given, this function sets the raw pulse-width value. """ ... def calibration(self, pulse_min, pulse_max, pulse_centre, pulse_angle_90, pulse_speed_100) -> Tuple: """ If no arguments are given, this function returns the current calibration data, as a 5-tuple. If arguments are given, this function sets the timing calibration: - ``pulse_min`` is the minimum allowed pulse width. - ``pulse_max`` is the maximum allowed pulse width. - ``pulse_centre`` is the pulse width corresponding to the centre/zero position. - ``pulse_angle_90`` is the pulse width corresponding to 90 degrees. - ``pulse_speed_100`` is the pulse width corresponding to a speed of 100. """ ... class SPI: """ Construct an SPI object on the given bus. ``bus`` can be 1 or 2, or 'X' or 'Y'. With no additional parameters, the SPI object is created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra arguments are given, the bus is initialised. See ``init`` for parameters of initialisation. The physical pins of the SPI buses are: - ``SPI(1)`` is on the X position: ``(NSS, SCK, MISO, MOSI) = (X5, X6, X7, X8) = (PA4, PA5, PA6, PA7)`` - ``SPI(2)`` is on the Y position: ``(NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7, Y8) = (PB12, PB13, PB14, PB15)`` At the moment, the NSS pin is not used by the SPI driver and is free for other use. """ CONTROLLER: Any # for initialising the SPI bus to controller or peripheral mode PERIPHERAL: Any LSB: Any # set the first bit to be the least or most significant bit MSB: Any def __init__(self, bus, *args) -> None: ... def deinit(self) -> None: """ Turn off the SPI bus. """ ... def init(self, mode, baudrate=328125, *, prescaler=1, polarity=1, phase=0, bits=8, firstbit=MSB, ti=False, crc=None) -> None: """ Initialise the SPI bus with the given parameters: - ``mode`` must be either ``SPI.CONTROLLER`` or ``SPI.PERIPHERAL``. - ``baudrate`` is the SCK clock rate (only sensible for a controller). - ``prescaler`` is the prescaler to use to derive SCK from the APB bus frequency; use of ``prescaler`` overrides ``baudrate``. - ``polarity`` can be 0 or 1, and is the level the idle clock line sits at. - ``phase`` can be 0 or 1 to sample data on the first or second clock edge respectively. - ``bits`` can be 8 or 16, and is the number of bits in each transferred word. - ``firstbit`` can be ``SPI.MSB`` or ``SPI.LSB``. - ``ti`` True indicates Texas Instruments, as opposed to Motorola, signal conventions. - ``crc`` can be None for no CRC, or a polynomial specifier. Note that the SPI clock frequency will not always be the requested baudrate. The hardware only supports baudrates that are the APB bus frequency (see :meth:`pyb.freq`) divided by a prescaler, which can be 2, 4, 8, 16, 32, 64, 128 or 256. SPI(1) is on AHB2, and SPI(2) is on AHB1. For precise control over the SPI clock frequency, specify ``prescaler`` instead of ``baudrate``. Printing the SPI object will show you the computed baudrate and the chosen prescaler. """ ... def recv(self, recv, *, timeout=5000) -> bytes: """ Receive data on the bus: - ``recv`` can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled with received bytes. - ``timeout`` is the timeout in milliseconds to wait for the receive. Return value: if ``recv`` is an integer then a new buffer of the bytes received, otherwise the same buffer that was passed in to ``recv``. """ ... def send(self, send, *, timeout=5000) -> None: """ Send data on the bus: - ``send`` is the data to send (an integer to send, or a buffer object). - ``timeout`` is the timeout in milliseconds to wait for the send. Return value: ``None``. """ ... def send_recv(self, send, recv=None, *, timeout=5000) -> bytes: """ Send and receive data on the bus at the same time: - ``send`` is the data to send (an integer to send, or a buffer object). - ``recv`` is a mutable buffer which will be filled with received bytes. It can be the same as ``send``, or omitted. If omitted, a new buffer will be created. - ``timeout`` is the timeout in milliseconds to wait for the receive. Return value: the buffer with the received bytes. """ ... class Timer: """ Construct a new timer object of the given id. If additional arguments are given, then the timer is initialised by ``init(...)``. ``id`` can be 1 to 14. """ def __init__(self, id, *args) -> None: ... def init(self, *, freq, prescaler, period, mode=UP, div=1, callback=None, deadtime=0) -> None: """ Initialise the timer. Initialisation must be either by frequency (in Hz) or by prescaler and period:: tim.init(freq=100) # set the timer to trigger at 100Hz tim.init(prescaler=83, period=999) # set the prescaler and period directly Keyword arguments: - ``freq`` --- specifies the periodic frequency of the timer. You might also view this as the frequency with which the timer goes through one complete cycle. - ``prescaler`` [0-0xffff] - specifies the value to be loaded into the timer's Prescaler Register (PSC). The timer clock source is divided by (``prescaler + 1``) to arrive at the timer clock. Timers 2-7 and 12-14 have a clock source of 84 MHz (pyb.freq()[2] \* 2), and Timers 1, and 8-11 have a clock source of 168 MHz (pyb.freq()[3] \* 2). - ``period`` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5. Specifies the value to be loaded into the timer's AutoReload Register (ARR). This determines the period of the timer (i.e. when the counter cycles). The timer counter will roll-over after ``period + 1`` timer clock cycles. - ``mode`` can be one of: - ``Timer.UP`` - configures the timer to count from 0 to ARR (default) - ``Timer.DOWN`` - configures the timer to count from ARR down to 0. - ``Timer.CENTER`` - configures the timer to count from 0 to ARR and then back down to 0. - ``div`` can be one of 1, 2, or 4. Divides the timer clock to determine the sampling clock used by the digital filters. - ``callback`` - as per Timer.callback() - ``deadtime`` - specifies the amount of "dead" or inactive time between transitions on complimentary channels (both channels will be inactive) for this time). ``deadtime`` may be an integer between 0 and 1008, with the following restrictions: 0-128 in steps of 1. 128-256 in steps of 2, 256-512 in steps of 8, and 512-1008 in steps of 16. ``deadtime`` measures ticks of ``source_freq`` divided by ``div`` clock ticks. ``deadtime`` is only available on timers 1 and 8. You must either specify freq or both of period and prescaler. """ ... def deinit(self) -> None: """ Deinitialises the timer. Disables the callback (and the associated irq). Disables any channel callbacks (and the associated irq). Stops the timer, and disables the timer peripheral. """ ... def callback(self, fun) -> None: """ Set the function to be called when the timer triggers. ``fun`` is passed 1 argument, the timer object. If ``fun`` is ``None`` then the callback will be disabled. """ ... def channel(self, channel, mode, *args) -> Any: """ If only a channel number is passed, then a previously initialized channel object is returned (or ``None`` if there is no previous channel). Otherwise, a TimerChannel object is initialized and returned. Each channel can be configured to perform pwm, output compare, or input capture. All channels share the same underlying timer, which means that they share the same timer clock. Keyword arguments: - ``mode`` can be one of: - ``Timer.PWM`` --- configure the timer in PWM mode (active high). - ``Timer.PWM_INVERTED`` --- configure the timer in PWM mode (active low). - ``Timer.OC_TIMING`` --- indicates that no pin is driven. - ``Timer.OC_ACTIVE`` --- the pin will be made active when a compare match occurs (active is determined by polarity) - ``Timer.OC_INACTIVE`` --- the pin will be made inactive when a compare match occurs. - ``Timer.OC_TOGGLE`` --- the pin will be toggled when an compare match occurs. - ``Timer.OC_FORCED_ACTIVE`` --- the pin is forced active (compare match is ignored). - ``Timer.OC_FORCED_INACTIVE`` --- the pin is forced inactive (compare match is ignored). - ``Timer.IC`` --- configure the timer in Input Capture mode. - ``Timer.ENC_A`` --- configure the timer in Encoder mode. The counter only changes when CH1 changes. - ``Timer.ENC_B`` --- configure the timer in Encoder mode. The counter only changes when CH2 changes. - ``Timer.ENC_AB`` --- configure the timer in Encoder mode. The counter changes when CH1 or CH2 changes. - ``callback`` - as per TimerChannel.callback() - ``pin`` None (the default) or a Pin object. If specified (and not None) this will cause the alternate function of the the indicated pin to be configured for this timer channel. An error will be raised if the pin doesn't support any alternate functions for this timer channel. Keyword arguments for Timer.PWM modes: - ``pulse_width`` - determines the initial pulse width value to use. - ``pulse_width_percent`` - determines the initial pulse width percentage to use. Keyword arguments for Timer.OC modes: - ``compare`` - determines the initial value of the compare register. - ``polarity`` can be one of: - ``Timer.HIGH`` - output is active high - ``Timer.LOW`` - output is active low Optional keyword arguments for Timer.IC modes: - ``polarity`` can be one of: - ``Timer.RISING`` - captures on rising edge. - ``Timer.FALLING`` - captures on falling edge. - ``Timer.BOTH`` - captures on both edges. Note that capture only works on the primary channel, and not on the complimentary channels. Notes for Timer.ENC modes: - Requires 2 pins, so one or both pins will need to be configured to use the appropriate timer AF using the Pin API. - Read the encoder value using the timer.counter() method. - Only works on CH1 and CH2 (and not on CH1N or CH2N) - The channel number is ignored when setting the encoder mode. PWM Example:: timer = pyb.Timer(2, freq=1000) ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=8000) ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=16000) """ ... def counter(self, value: Optional[Any]) -> Any: """ Get or set the timer counter. """ ... def freq(self, value: Optional[Any]) -> Any: """ Get or set the frequency for the timer (changes prescaler and period if set). """ ... def period(self, value: Optional[Any]) -> Any: """ Get or set the period of the timer. """ ... def prescaler(self, value: Optional[Any]) -> Any: """ Get or set the prescaler for the timer. """ ... def source_freq(self) -> Any: """ Get the frequency of the source of the timer. """ ... class timerchannel: """ """ def callback(self, fun) -> None: """ Set the function to be called when the timer channel triggers. ``fun`` is passed 1 argument, the timer object. If ``fun`` is ``None`` then the callback will be disabled. """ ... def capture(self, value: Optional[Any]) -> Any: """ Get or set the capture value associated with a channel. capture, compare, and pulse_width are all aliases for the same function. capture is the logical name to use when the channel is in input capture mode. """ ... def compare(self, value: Optional[Any]) -> Any: """ Get or set the compare value associated with a channel. capture, compare, and pulse_width are all aliases for the same function. compare is the logical name to use when the channel is in output compare mode. """ ... def pulse_width(self, value: Optional[Any]) -> Any: """ Get or set the pulse width value associated with a channel. capture, compare, and pulse_width are all aliases for the same function. pulse_width is the logical name to use when the channel is in PWM mode. In edge aligned mode, a pulse_width of ``period + 1`` corresponds to a duty cycle of 100% In center aligned mode, a pulse width of ``period`` corresponds to a duty cycle of 100% """ ... def pulse_width_percent(self, value: Optional[Any]) -> Any: """ Get or set the pulse width percentage associated with a channel. The value is a number between 0 and 100 and sets the percentage of the timer period for which the pulse is active. The value can be an integer or floating-point number for more accuracy. For example, a value of 25 gives a duty cycle of 25%. """ ... class UART: """ Construct a UART object on the given bus. For Pyboard ``bus`` can be 1-4, 6, 'XA', 'XB', 'YA', or 'YB'. For Pyboard Lite ``bus`` can be 1, 2, 6, 'XB', or 'YA'. For Pyboard D ``bus`` can be 1-4, 'XA', 'YA' or 'YB'. With no additional parameters, the UART object is created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra arguments are given, the bus is initialised. See ``init`` for parameters of initialisation. The physical pins of the UART buses on Pyboard are: - ``UART(4)`` is on ``XA``: ``(TX, RX) = (X1, X2) = (PA0, PA1)`` - ``UART(1)`` is on ``XB``: ``(TX, RX) = (X9, X10) = (PB6, PB7)`` - ``UART(6)`` is on ``YA``: ``(TX, RX) = (Y1, Y2) = (PC6, PC7)`` - ``UART(3)`` is on ``YB``: ``(TX, RX) = (Y9, Y10) = (PB10, PB11)`` - ``UART(2)`` is on: ``(TX, RX) = (X3, X4) = (PA2, PA3)`` The Pyboard Lite supports UART(1), UART(2) and UART(6) only, pins are: - ``UART(1)`` is on ``XB``: ``(TX, RX) = (X9, X10) = (PB6, PB7)`` - ``UART(6)`` is on ``YA``: ``(TX, RX) = (Y1, Y2) = (PC6, PC7)`` - ``UART(2)`` is on: ``(TX, RX) = (X1, X2) = (PA2, PA3)`` The Pyboard D supports UART(1), UART(2), UART(3) and UART(4) only, pins are: - ``UART(4)`` is on ``XA``: ``(TX, RX) = (X1, X2) = (PA0, PA1)`` - ``UART(1)`` is on ``YA``: ``(TX, RX) = (Y1, Y2) = (PA9, PA10)`` - ``UART(3)`` is on ``YB``: ``(TX, RX) = (Y9, Y10) = (PB10, PB11)`` - ``UART(2)`` is on: ``(TX, RX) = (X3, X4) = (PA2, PA3)`` *Note:* Pyboard D has ``UART(1)`` on ``YA``, unlike Pyboard and Pyboard Lite that both have ``UART(1)`` on ``XB`` and ``UART(6)`` on ``YA``. """ # to select the flow control type. RTS: Any # to select the flow control type. CTS: Any def __init__(self, bus, *args) -> None: ... def init(self, baudrate, bits=8, parity=None, stop=1, *, timeout=0, flow=0, timeout_char=0, read_buf_len=64) -> Any: """ Initialise the UART bus with the given parameters: - ``baudrate`` is the clock rate. - ``bits`` is the number of bits per character, 7, 8 or 9. - ``parity`` is the parity, ``None``, 0 (even) or 1 (odd). - ``stop`` is the number of stop bits, 1 or 2. - ``flow`` sets the flow control type. Can be 0, ``UART.RTS``, ``UART.CTS`` or ``UART.RTS | UART.CTS``. - ``timeout`` is the timeout in milliseconds to wait for writing/reading the first character. - ``timeout_char`` is the timeout in milliseconds to wait between characters while writing or reading. - ``read_buf_len`` is the character length of the read buffer (0 to disable). This method will raise an exception if the baudrate could not be set within 5% of the desired value. The minimum baudrate is dictated by the frequency of the bus that the UART is on; UART(1) and UART(6) are APB2, the rest are on APB1. The default bus frequencies give a minimum baudrate of 1300 for UART(1) and UART(6) and 650 for the others. Use :func:`pyb.freq <pyb.freq>` to reduce the bus frequencies to get lower baudrates. *Note:* with parity=None, only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits are supported. """ ... def deinit(self) -> None: """ Turn off the UART bus. """ ... def any(self) -> int: """ Returns the number of bytes waiting (may be 0). """ ... def read(self, nbytes: Optional[Any]) -> bytes: """ Read characters. If ``nbytes`` is specified then read at most that many bytes. If ``nbytes`` are available in the buffer, returns immediately, otherwise returns when sufficient characters arrive or the timeout elapses. If ``nbytes`` is not given then the method reads as much data as possible. It returns after the timeout has elapsed. *Note:* for 9 bit characters each character takes two bytes, ``nbytes`` must be even, and the number of characters is ``nbytes/2``. Return value: a bytes object containing the bytes read in. Returns ``None`` on timeout. """ ... def readchar(self) -> int: """ Receive a single character on the bus. Return value: The character read, as an integer. Returns -1 on timeout. """ ... def readinto(self, buf, nbytes: Optional[Any]) -> int: """ Read bytes into the ``buf``. If ``nbytes`` is specified then read at most that many bytes. Otherwise, read at most ``len(buf)`` bytes. Return value: number of bytes read and stored into ``buf`` or ``None`` on timeout. """ ... def readline(self) -> None: """ Read a line, ending in a newline character. If such a line exists, return is immediate. If the timeout elapses, all available data is returned regardless of whether a newline exists. Return value: the line read or ``None`` on timeout if no data is available. """ ... def write(self, buf) -> int: """ Write the buffer of bytes to the bus. If characters are 7 or 8 bits wide then each byte is one character. If characters are 9 bits wide then two bytes are used for each character (little endian), and ``buf`` must contain an even number of bytes. Return value: number of bytes written. If a timeout occurs and no bytes were written returns ``None``. """ ... def writechar(self, char) -> None: """ Write a single character on the bus. ``char`` is an integer to write. Return value: ``None``. See note below if CTS flow control is used. """ ... def sendbreak(self) -> None: """ Send a break condition on the bus. This drives the bus low for a duration of 13 bits. Return value: ``None``. """ ... class USB_HID: """ Create a new USB_HID object. """ def __init__(self) -> None: ... def recv(self, data, *, timeout=5000) -> int: """ Receive data on the bus: - ``data`` can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled with received bytes. - ``timeout`` is the timeout in milliseconds to wait for the receive. Return value: if ``data`` is an integer then a new buffer of the bytes received, otherwise the number of bytes read into ``data`` is returned. """ ... def send(self, data) -> None: """ Send data over the USB HID interface: - ``data`` is the data to send (a tuple/list of integers, or a bytearray). """ ... class USB_VCP: """ Create a new USB_VCP object. The *id* argument specifies which USB VCP port to use. """ # to select the flow control type. RTS: Any # to select the flow control type. CTS: Any # IRQ trigger values for :meth:`USB_VCP.irq`. IRQ_RX: Any def __init__(self, id=0) -> None: ... def init(self, *, flow=-1) -> None: """ Configure the USB VCP port. If the *flow* argument is not -1 then the value sets the flow control, which can be a bitwise-or of ``USB_VCP.RTS`` and ``USB_VCP.CTS``. RTS is used to control read behaviour and CTS, to control write behaviour. """ ... def setinterrupt(self, chr) -> None: """ Set the character which interrupts running Python code. This is set to 3 (CTRL-C) by default, and when a CTRL-C character is received over the USB VCP port, a KeyboardInterrupt exception is raised. Set to -1 to disable this interrupt feature. This is useful when you want to send raw bytes over the USB VCP port. """ ... def isconnected(self) -> bool: """ Return ``True`` if USB is connected as a serial device, else ``False``. """ ... def any(self) -> bool: """ Return ``True`` if any characters waiting, else ``False``. """ ... def close(self) -> Any: """ This method does nothing. It exists so the USB_VCP object can act as a file. """ ... def read(self, nbytes: Optional[Any]) -> bytes: """ Read at most ``nbytes`` from the serial device and return them as a bytes object. If ``nbytes`` is not specified then the method reads all available bytes from the serial device. USB_VCP `stream` implicitly works in non-blocking mode, so if no pending data available, this method will return immediately with ``None`` value. """ ... def readinto(self, buf, maxlen: Optional[Any]) -> int: """ Read bytes from the serial device and store them into ``buf``, which should be a buffer-like object. At most ``len(buf)`` bytes are read. If ``maxlen`` is given and then at most ``min(maxlen, len(buf))`` bytes are read. Returns the number of bytes read and stored into ``buf`` or ``None`` if no pending data available. """ ... def readline(self) -> bytes: """ Read a whole line from the serial device. Returns a bytes object containing the data, including the trailing newline character or ``None`` if no pending data available. """ ... def readlines(self) -> List: """ Read as much data as possible from the serial device, breaking it into lines. Returns a list of bytes objects, each object being one of the lines. Each line will include the newline character. """ ... def write(self, buf) -> int: """ Write the bytes from ``buf`` to the serial device. Returns the number of bytes written. """ ... def recv(self, data, *, timeout=5000) -> int: """ Receive data on the bus: - ``data`` can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled with received bytes. - ``timeout`` is the timeout in milliseconds to wait for the receive. Return value: if ``data`` is an integer then a new buffer of the bytes received, otherwise the number of bytes read into ``data`` is returned. """ ... def send(self, data, *, timeout=5000) -> int: """ Send data over the USB VCP: - ``data`` is the data to send (an integer to send, or a buffer object). - ``timeout`` is the timeout in milliseconds to wait for the send. Return value: number of bytes sent. """ ... def irq(self, handler=None, trigger=IRQ_RX, hard=False) -> None: """ Register *handler* to be called whenever an event specified by *trigger* occurs. The *handler* function must take exactly one argument, which will be the USB VCP object. Pass in ``None`` to disable the callback. Valid values for *trigger* are: - ``USB_VCP.IRQ_RX``: new data is available for reading from the USB VCP object. """ ... def delay(ms) -> None: """ Delay for the given number of milliseconds. """ ... def udelay(us) -> None: """ Delay for the given number of microseconds. """ ... def millis() -> int: """ Returns the number of milliseconds since the board was last reset. The result is always a MicroPython smallint (31-bit signed number), so after 2^30 milliseconds (about 12.4 days) this will start to return negative numbers. Note that if :meth:`pyb.stop()` is issued the hardware counter supporting this function will pause for the duration of the "sleeping" state. This will affect the outcome of :meth:`pyb.elapsed_millis()`. """ ... def micros() -> int: """ Returns the number of microseconds since the board was last reset. The result is always a MicroPython smallint (31-bit signed number), so after 2^30 microseconds (about 17.8 minutes) this will start to return negative numbers. Note that if :meth:`pyb.stop()` is issued the hardware counter supporting this function will pause for the duration of the "sleeping" state. This will affect the outcome of :meth:`pyb.elapsed_micros()`. """ ... def elapsed_millis(start) -> int: """ Returns the number of milliseconds which have elapsed since ``start``. This function takes care of counter wrap, and always returns a positive number. This means it can be used to measure periods up to about 12.4 days. Example:: start = pyb.millis() while pyb.elapsed_millis(start) < 1000: # Perform some operation """ ... def elapsed_micros(start) -> int: """ Returns the number of microseconds which have elapsed since ``start``. This function takes care of counter wrap, and always returns a positive number. This means it can be used to measure periods up to about 17.8 minutes. Example:: start = pyb.micros() while pyb.elapsed_micros(start) < 1000: # Perform some operation pass """ ... def hard_reset() -> NoReturn: """ Resets the pyboard in a manner similar to pushing the external RESET button. """ ... def bootloader() -> None: """ Activate the bootloader without BOOT\* pins. """ ... def fault_debug(value) -> None: """ Enable or disable hard-fault debugging. A hard-fault is when there is a fatal error in the underlying system, like an invalid memory access. If the *value* argument is ``False`` then the board will automatically reset if there is a hard fault. If *value* is ``True`` then, when the board has a hard fault, it will print the registers and the stack trace, and then cycle the LEDs indefinitely. The default value is disabled, i.e. to automatically reset. """ ... def disable_irq() -> Any: """ Disable interrupt requests. Returns the previous IRQ state: ``False``/``True`` for disabled/enabled IRQs respectively. This return value can be passed to enable_irq to restore the IRQ to its original state. """ ... def enable_irq(state=True) -> None: """ Enable interrupt requests. If ``state`` is ``True`` (the default value) then IRQs are enabled. If ``state`` is ``False`` then IRQs are disabled. The most common use of this function is to pass it the value returned by ``disable_irq`` to exit a critical section. """ ... def freq(sysclk, hclk, pclk1, pclk2) -> Tuple: """ If given no arguments, returns a tuple of clock frequencies: (sysclk, hclk, pclk1, pclk2). These correspond to: - sysclk: frequency of the CPU - hclk: frequency of the AHB bus, core memory and DMA - pclk1: frequency of the APB1 bus - pclk2: frequency of the APB2 bus If given any arguments then the function sets the frequency of the CPU, and the buses if additional arguments are given. Frequencies are given in Hz. Eg freq(120000000) sets sysclk (the CPU frequency) to 120MHz. Note that not all values are supported and the largest supported frequency not greater than the given value will be selected. Supported sysclk frequencies are (in MHz): 8, 16, 24, 30, 32, 36, 40, 42, 48, 54, 56, 60, 64, 72, 84, 96, 108, 120, 144, 168. The maximum frequency of hclk is 168MHz, of pclk1 is 42MHz, and of pclk2 is 84MHz. Be sure not to set frequencies above these values. The hclk, pclk1 and pclk2 frequencies are derived from the sysclk frequency using a prescaler (divider). Supported prescalers for hclk are: 1, 2, 4, 8, 16, 64, 128, 256, 512. Supported prescalers for pclk1 and pclk2 are: 1, 2, 4, 8. A prescaler will be chosen to best match the requested frequency. A sysclk frequency of 8MHz uses the HSE (external crystal) directly and 16MHz uses the HSI (internal oscillator) directly. The higher frequencies use the HSE to drive the PLL (phase locked loop), and then use the output of the PLL. Note that if you change the frequency while the USB is enabled then the USB may become unreliable. It is best to change the frequency in boot.py, before the USB peripheral is started. Also note that sysclk frequencies below 36MHz do not allow the USB to function correctly. """ ... def wfi() -> None: """ Wait for an internal or external interrupt. This executes a ``wfi`` instruction which reduces power consumption of the MCU until any interrupt occurs (be it internal or external), at which point execution continues. Note that the system-tick interrupt occurs once every millisecond (1000Hz) so this function will block for at most 1ms. """ ... def stop() -> Any: """ Put the pyboard in a "sleeping" state. This reduces power consumption to less than 500 uA. To wake from this sleep state requires an external interrupt or a real-time-clock event. Upon waking execution continues where it left off. See :meth:`rtc.wakeup` to configure a real-time-clock wakeup event. """ ... def standby() -> Any: """ Put the pyboard into a "deep sleep" state. This reduces power consumption to less than 50 uA. To wake from this sleep state requires a real-time-clock event, or an external interrupt on X1 (PA0=WKUP) or X18 (PC13=TAMP1). Upon waking the system undergoes a hard reset. See :meth:`rtc.wakeup` to configure a real-time-clock wakeup event. """ ... def have_cdc() -> bool: """ Return True if USB is connected as a serial device, False otherwise. """ ... def hid(hidtuple) -> Any: """ Takes a 4-tuple (or list) and sends it to the USB host (the PC) to signal a HID mouse-motion event. """ ... def info(dump_alloc_table: Optional[Any]) -> None: """ Print out lots of information about the board. """ ... def main(filename) -> None: """ Set the filename of the main script to run after boot.py is finished. If this function is not called then the default file main.py will be executed. It only makes sense to call this function from within boot.py. """ ... def mount(device, mountpoint, *, readonly=False, mkfs=False) -> Any: ... def repl_uart(uart) -> UART: """ Get or set the UART object where the REPL is repeated on. """ ... def rng() -> int: """ Return a 30-bit hardware generated random number. """ ... def sync() -> None: """ Sync all file systems. """ ... def unique_id() -> str: """ Returns a string of 12 bytes (96 bits), which is the unique ID of the MCU. """ ... def usb_mode(modestr: Optional[Any], port=-1, vid=0xF055, pid=-1, msc=(), hid=hid_mouse, high_speed=False) -> str: """ If called with no arguments, return the current USB mode as a string. If called with *modestr* provided, attempts to configure the USB mode. The following values of *modestr* are understood: - ``None``: disables USB - ``'VCP'``: enable with VCP (Virtual COM Port) interface - ``'MSC'``: enable with MSC (mass storage device class) interface - ``'VCP+MSC'``: enable with VCP and MSC - ``'VCP+HID'``: enable with VCP and HID (human interface device) - ``'VCP+MSC+HID'``: enabled with VCP, MSC and HID (only available on PYBD boards) For backwards compatibility, ``'CDC'`` is understood to mean ``'VCP'`` (and similarly for ``'CDC+MSC'`` and ``'CDC+HID'``). The *port* parameter should be an integer (0, 1, ...) and selects which USB port to use if the board supports multiple ports. A value of -1 uses the default or automatically selected port. The *vid* and *pid* parameters allow you to specify the VID (vendor id) and PID (product id). A *pid* value of -1 will select a PID based on the value of *modestr*. If enabling MSC mode, the *msc* parameter can be used to specify a list of SCSI LUNs to expose on the mass storage interface. For example ``msc=(pyb.Flash(), pyb.SDCard())``. If enabling HID mode, you may also specify the HID details by passing the *hid* keyword parameter. It takes a tuple of (subclass, protocol, max packet length, polling interval, report descriptor). By default it will set appropriate values for a USB mouse. There is also a ``pyb.hid_keyboard`` constant, which is an appropriate tuple for a USB keyboard. The *high_speed* parameter, when set to ``True``, enables USB HS mode if it is supported by the hardware. """ ...
35.700626
137
0.585008
2dcf4ee2b9809e61bebe3b40244d45afa2af9982
264
py
Python
Aula-07/ex012.py
matheussantanads/exercicios-python
3b25db164342e9613f97d2f81ff218a99ab3febe
[ "MIT" ]
1
2020-07-15T02:59:58.000Z
2020-07-15T02:59:58.000Z
Aula-07/ex012.py
matheussantanads/exercicios-python
3b25db164342e9613f97d2f81ff218a99ab3febe
[ "MIT" ]
null
null
null
Aula-07/ex012.py
matheussantanads/exercicios-python
3b25db164342e9613f97d2f81ff218a99ab3febe
[ "MIT" ]
null
null
null
# Curso Python 07 # ---Desafio 12--- # Faça um algoritmo que leia o preço de um produto # e mostre seu novo preço, com 5& de desconto. val = float(input('Digite o preço do produto: ')) print(f'O novo preço do produto com 5% de desconto é de R$ {val*0.95:.2f}')
29.333333
75
0.67803
c02ab334a6323e03902333c923cceead75c45741
1,922
py
Python
scripts/addb-py/chronometry/s3server_integration/s3_overrides.py
swatid-seagate/cortx-motr
ab17cd5f401be08bb4f72790b4d2316ecc99449d
[ "Apache-2.0" ]
null
null
null
scripts/addb-py/chronometry/s3server_integration/s3_overrides.py
swatid-seagate/cortx-motr
ab17cd5f401be08bb4f72790b4d2316ecc99449d
[ "Apache-2.0" ]
1
2022-02-03T09:51:48.000Z
2022-02-03T09:51:48.000Z
scripts/addb-py/chronometry/s3server_integration/s3_overrides.py
swatid-seagate/cortx-motr
ab17cd5f401be08bb4f72790b4d2316ecc99449d
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # # Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates # # 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. # # For any questions about this software or licensing, # please email opensource@seagate.com or cortx-questions@seagate.com. # import argparse def parse_args(): description=""" s3_overrides.py: Apply overrides to the specified s3config.yaml """ parser = argparse.ArgumentParser(description=description) parser.add_argument("overrides", help="Overrides string in format key=value") parser.add_argument("s3config", help="s3config.yaml file") return parser.parse_args() def main(): args = parse_args() data = [] if args.overrides: with open(args.s3config, 'r') as f: for line in f.readlines(): data.append(line) for kv in args.overrides.split(" "): key, value = kv.split('=') for idx, line in enumerate(data): if key in line.split(': ')[0]: k = line.split(': ')[0] print(f"Overriding {k} with new value: {value}, old value: {line.split(': ')[1].split('#')[0]}") nl='\n' data[idx] = f"{k}: {value} # Override by s3_overrides.py{nl}" with open(args.s3config, 'w') as f: for line in data: f.write(line) if __name__ == '__main__': main()
32.576271
116
0.632674
4db58384e3ca9e88e5284baae7bf371e99a79093
3,443
py
Python
sky_anisotropy/reductions.py
viniwiedemann/sky-anisotropy
f183ac11f87755203ede357749d75364af3b958d
[ "MIT" ]
null
null
null
sky_anisotropy/reductions.py
viniwiedemann/sky-anisotropy
f183ac11f87755203ede357749d75364af3b958d
[ "MIT" ]
null
null
null
sky_anisotropy/reductions.py
viniwiedemann/sky-anisotropy
f183ac11f87755203ede357749d75364af3b958d
[ "MIT" ]
null
null
null
import itertools from collections import OrderedDict import sky_anisotropy as sa import numpy as np import xarray as xr import healpy as hp from dask.diagnostics import ProgressBar import dask.array as da import dask.dataframe as dd from dask import compute def digitize_columns(partition, col_to_bins): for col in col_to_bins.keys(): bins = col_to_bins[col] partition[col + '_digitized'] = np.digitize(partition[col], bins=bins) - 1 return partition def ang2pix(theta, phi, nside=64): return hp.ang2pix(nside=nside, theta=theta, phi=phi) def binned_skymaps(ddf, col_to_bins, ra_col=None, dec_col=None, nside=64, num_workers=1, scheduler='threading', **compute_kwargs): """ Calculate binned skymaps for input data Parameters ---------- ddf : dask.dataframe.DataFrame Input data. col_to_bins : collections.OrderedDict Dictionary with mapping between columns in ddf and bin edges. ra_col : str Column name in ddf with right ascension values (in radians). dec_col : str Column name in ddf with declination values (in radians). nside : int, optional Number of sides used for healpix map (default is 64). num_workers : int, optional Number of processes or threads to use (default is 1). scheduler : str, optional Dask scheduler to use (default is 'threading'). compute_kwargs : dict Optional keyword arguments to pass to Dask's compute() function. Returns ------- data : xarray.DataArray """ if not all([ra_col, dec_col]): raise ValueError('Both ra_col and dec_col must not be None') if not isinstance(ddf, dd.DataFrame): raise TypeError('ddf must be a dask DataFrame') if not isinstance(col_to_bins, OrderedDict): raise TypeError('col_to_bins must be an instance of collections.OrderedDict') npix = hp.nside2npix(nside) # Get bin bin index for each column ddf_digitized = ddf.map_partitions(digitize_columns, col_to_bins) shape = list((len(bins)-1 for bins in col_to_bins.values())) bin_idxs = [np.arange(l) for l in shape] # Compute skymaps for each unique bin combination cols = col_to_bins.keys() maps = [] for idx in itertools.product(*bin_idxs): bool_masks = list(ddf_digitized['{}_digitized'.format(col)] == i for col, i in zip(cols, idx)) if len(bool_masks) == 1: mask = bool_masks[0] else: mask = da.logical_and(*bool_masks) theta, phi = sa.equatorial_to_healpy(ddf.loc[mask, ra_col], ddf.loc[mask, dec_col]) ipix = da.map_blocks(ang2pix, theta.values, phi.values) m, _ = da.histogram(ipix, bins=np.arange(npix + 1)) maps.append(m) with ProgressBar(): maps = compute(*maps, num_workers=num_workers, scheduler=scheduler, **compute_kwargs) # Format maps into an xarray.DataArray data = np.zeros(shape + [npix]) for idx, m in zip(itertools.product(*bin_idxs), maps): data[idx] = m dims = col_to_bins.keys() + ['ipix'] coords = {} for col in col_to_bins.keys(): bins = col_to_bins[col] coords[col] = (bins[1:] + bins[:-1]) / 2 data = xr.DataArray(data, dims=dims, coords=coords) return data
32.481132
85
0.636073
cf7df2474da6895903c23431ea6365a161487a53
6,558
py
Python
sdk/python/pulumi_azure_nextgen/apimanagement/v20180601preview/certificate.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/apimanagement/v20180601preview/certificate.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/apimanagement/v20180601preview/certificate.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 __all__ = ['Certificate'] class Certificate(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, certificate_id: Optional[pulumi.Input[str]] = None, data: Optional[pulumi.Input[str]] = None, password: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, service_name: Optional[pulumi.Input[str]] = None, __props__=None, __name__=None, __opts__=None): """ Certificate details. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] certificate_id: Identifier of the certificate entity. Must be unique in the current API Management service instance. :param pulumi.Input[str] data: Base 64 encoded certificate using the application/x-pkcs12 representation. :param pulumi.Input[str] password: Password for the Certificate :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[str] service_name: The name of the API Management service. """ 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__['certificate_id'] = certificate_id if data is None and not opts.urn: raise TypeError("Missing required property 'data'") __props__['data'] = data if password is None and not opts.urn: raise TypeError("Missing required property 'password'") __props__['password'] = password 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 if service_name is None and not opts.urn: raise TypeError("Missing required property 'service_name'") __props__['service_name'] = service_name __props__['expiration_date'] = None __props__['name'] = None __props__['subject'] = None __props__['thumbprint'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:apimanagement:Certificate"), pulumi.Alias(type_="azure-nextgen:apimanagement/latest:Certificate"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20160707:Certificate"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20161010:Certificate"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20170301:Certificate"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20180101:Certificate"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20190101:Certificate"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20191201:Certificate"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20191201preview:Certificate"), pulumi.Alias(type_="azure-nextgen:apimanagement/v20200601preview:Certificate")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(Certificate, __self__).__init__( 'azure-nextgen:apimanagement/v20180601preview:Certificate', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'Certificate': """ Get an existing Certificate 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 Certificate(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="expirationDate") def expiration_date(self) -> pulumi.Output[str]: """ Expiration date of the certificate. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard. """ return pulumi.get(self, "expiration_date") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter def subject(self) -> pulumi.Output[str]: """ Subject attribute of the certificate. """ return pulumi.get(self, "subject") @property @pulumi.getter def thumbprint(self) -> pulumi.Output[str]: """ Thumbprint of the certificate. """ return pulumi.get(self, "thumbprint") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Resource type for API Management resource. """ return pulumi.get(self, "type") 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
45.541667
784
0.65584
6fab1da81fe43a3041403cb96261ed2eed29054f
2,481
py
Python
dags/kv_uploader_dag.py
nsutton00/starthinker
e597d679a95ca85a21af9cf4df3ff935ca34abf8
[ "Apache-2.0" ]
null
null
null
dags/kv_uploader_dag.py
nsutton00/starthinker
e597d679a95ca85a21af9cf4df3ff935ca34abf8
[ "Apache-2.0" ]
null
null
null
dags/kv_uploader_dag.py
nsutton00/starthinker
e597d679a95ca85a21af9cf4df3ff935ca34abf8
[ "Apache-2.0" ]
null
null
null
########################################################################### # # Copyright 2019 Google Inc. # # 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. # ########################################################################### ''' -------------------------------------------------------------- Before running this Airflow module... Install StarThinker in cloud composer from open source: pip install git+https://github.com/google/starthinker Or push local code to the cloud composer plugins directory: source install/deploy.sh 4) Composer Menu l) Install All -------------------------------------------------------------- Tag Key Value Uploader A tool for bulk editing key value pairs for CM pllacements. Add this card to a recipe and save it. Then click <strong>Run Now</strong> to deploy. Follow the instructuons in the sheet for setup. ''' from starthinker_airflow.factory import DAG_Factory # Add the following credentials to your Airflow configuration. USER_CONN_ID = "starthinker_user" # The connection to use for user authentication. GCP_CONN_ID = "starthinker_service" # The connection to use for service authentication. INPUTS = { 'recipe_name': '', # Name of document to deploy to. } TASKS = [ { 'drive': { 'auth': 'user', 'hour': [ ], 'copy': { 'source': 'https://docs.google.com/spreadsheets/d/19Sxy4BDtK9ocq_INKTiZ-rZHgqhfpiiokXOTsYzmah0/', 'destination': { 'field': { 'name': 'recipe_name', 'prefix': 'Key Value Uploader For ', 'kind': 'string', 'order': 1, 'description': 'Name of document to deploy to.', 'default': '' } } } } } ] DAG_FACTORY = DAG_Factory('kv_uploader', { 'tasks':TASKS }, INPUTS) DAG_FACTORY.apply_credentails(USER_CONN_ID, GCP_CONN_ID) DAG = DAG_FACTORY.execute() if __name__ == "__main__": DAG_FACTORY.print_commandline()
29.188235
105
0.600564
9b53d64bc81fe3135c7f596d68bf88330dd5d7f2
2,637
py
Python
CoppeliaSim_Edu_V4_1_0_Ubuntu18_04/programming/libPlugin/simStubsGen/lua_to_xml.py
YueErro/ModernRobotics
82345c04157c1322b24553bf00abd1f2b03281a5
[ "MIT" ]
39
2018-08-28T21:28:07.000Z
2022-03-12T10:30:40.000Z
external/v_repStubsGen/lua_to_xml.py
kasperg3/vrep_ros_interface
8e68a1b37591e7fe8576ca8b8cce9d6859a6bf5e
[ "BSD-3-Clause" ]
175
2017-06-29T09:37:43.000Z
2021-07-09T12:55:28.000Z
external/v_repStubsGen/lua_to_xml.py
kasperg3/vrep_ros_interface
8e68a1b37591e7fe8576ca8b8cce9d6859a6bf5e
[ "BSD-3-Clause" ]
14
2018-07-12T06:59:48.000Z
2021-03-31T08:27:39.000Z
from sys import argv, exit import re if len(argv) != 3: print('usage: {} <input-lua-file> <output-xml-file>'.format(argv[0])) exit(1) luafile = argv[1] outfile = argv[2] fun = None args, rets = [], [] with open(outfile, 'w') as fout: fout.write('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n') fout.write('<plugin>\n') def processTableType(t): if '.' in t: table, itemtype = t.split('.') if table == 'table': return 'table" item-type="%s' % itemtype return t def output(): if fun: f, fdesc = fun fout.write(' <command name="{}">\n'.format(f)) fout.write(' <description>{}</description>\n'.format(fdesc)) fout.write(' <params>\n') for (t, n, d) in args: t = processTableType(t) fout.write(' <param name="{}" type="{}">\n'.format(n, t)) fout.write(' <description>{}</description>\n'.format(d)) fout.write(' </param>\n') fout.write(' </params>\n') fout.write(' <return>\n') for (t, n, d) in rets: t = processTableType(t) fout.write(' <param name="{}" type="{}">'.format(n, t)) fout.write(' <description>{}</description>\n'.format(d)) fout.write(' </param>\n') fout.write(' </return>\n') fout.write(' </command>\n') with open(luafile, 'r') as f: for line in f: m = re.match(r'\s*--\s*@([^\s]+)\s+(.*)$', line) if m: tag, line = map(lambda s: s.strip(), m.groups()) if tag == 'fun': m = re.match(r'([^\s]+)\s*(.*)$', line) if m: name, description = map(lambda s: s.strip(), m.groups()) fun = (name, description) elif tag in ('arg', 'ret'): m = re.match(r'([^\s]+)\s+([^\s]+)\s*(.*)$', line) if m: dtype, name, description = map(lambda s: s.strip(), m.groups()) if tag == 'arg': args.append((dtype, name, description)) elif tag == 'ret': rets.append((dtype, name, description)) else: output() fun = None args, rets = [], [] output() fout.write('</plugin>\n')
36.625
87
0.406523
f84e04cc7107778c9b9a61eea2bfc836f40bdc5d
325
py
Python
pyjobs/core/migrations/0012_remove_profile_phone.py
Mdslino/PyJobs
d2496d58067503c3304a6c59052238b1f097472b
[ "BSD-3-Clause" ]
132
2017-10-27T23:54:47.000Z
2022-03-15T12:10:10.000Z
pyjobs/core/migrations/0012_remove_profile_phone.py
Mdslino/PyJobs
d2496d58067503c3304a6c59052238b1f097472b
[ "BSD-3-Clause" ]
129
2017-09-05T04:22:50.000Z
2022-03-12T01:06:49.000Z
pyjobs/core/migrations/0012_remove_profile_phone.py
Mdslino/PyJobs
d2496d58067503c3304a6c59052238b1f097472b
[ "BSD-3-Clause" ]
82
2017-10-28T00:14:04.000Z
2021-07-27T20:00:40.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-04-13 23:30 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("core", "0011_auto_20180413_2320")] operations = [migrations.RemoveField(model_name="profile", name="phone")]
25
77
0.732308
cfd33b9dc4d628986d2742047594e934ea9f7792
2,274
py
Python
tests/test_worker_serialize.py
mozaiques/zombase
fc8dbfdad7cdb1975fac63030fc6f6c20b6df260
[ "MIT" ]
3
2015-01-22T21:54:49.000Z
2022-02-13T14:22:00.000Z
tests/test_worker_serialize.py
mozaiques/zombase
fc8dbfdad7cdb1975fac63030fc6f6c20b6df260
[ "MIT" ]
null
null
null
tests/test_worker_serialize.py
mozaiques/zombase
fc8dbfdad7cdb1975fac63030fc6f6c20b6df260
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from zombase import worker import test_worker class InvalidWorker(worker.MappingManagingWorker): pass class Worker(worker.MappingManagingWorker): def _serialize_one(self, item): return {'a_prop': item.a_prop} class TestInvalidWorker(test_worker.BaseTestWorker): def test_invalid_worker(self): foreman = test_worker.FakeForeman() a_worker = InvalidWorker( foreman, managed_sqla_map=test_worker.FakeMapping, managed_sqla_map_name='fake', ) with self.assertRaises(NotImplementedError): a_worker.serialize_one(test_worker.FakeMapping()) class TestSerialize(test_worker.BaseTestWorker): def setUp(self): foreman = test_worker.FakeForeman() self.a_worker = Worker( foreman, managed_sqla_map=test_worker.FakeMapping, managed_sqla_map_name='fake', ) test_worker.BaseTestWorker.setUp(self) def tearDown(self): del self.a_worker test_worker.BaseTestWorker.tearDown(self) def test_serialize_one(self): fake_item = test_worker.FakeMapping() serialized = self.a_worker.serialize_one(fake_item) self.assertTrue(isinstance(serialized, dict)) self.assertEqual(serialized['a_prop'], fake_item.a_prop) def test_serialize_one_with_func(self): fake_item = test_worker.FakeMapping() def times_3(item): return item.a_prop * 3 serialized = self.a_worker.serialize_one(fake_item, times_3=times_3) self.assertEqual(serialized['times_3'], fake_item.a_prop * 3) def test_serialize_list(self): fake_item1 = test_worker.FakeMapping() fake_item2 = test_worker.FakeMapping() fake_item2.a_prop = 13 def times_2(item): return item.a_prop * 2 serialized = list(self.a_worker.serialize( (fake_item1, fake_item2), times_2=times_2)) self.assertEqual(serialized[0]['a_prop'], fake_item1.a_prop) self.assertEqual(serialized[1]['a_prop'], fake_item2.a_prop) self.assertEqual(serialized[0]['times_2'], fake_item1.a_prop * 2) self.assertEqual(serialized[1]['times_2'], fake_item2.a_prop * 2)
29.153846
76
0.669745
4fb12f36b5ef1e79fa440554ef86c56934a3e114
11,385
py
Python
test/test_cell.py
azagajewski/ColiCoords
fa26e46971e24ff582c4d33331c5b8181f605c9f
[ "MIT" ]
null
null
null
test/test_cell.py
azagajewski/ColiCoords
fa26e46971e24ff582c4d33331c5b8181f605c9f
[ "MIT" ]
null
null
null
test/test_cell.py
azagajewski/ColiCoords
fa26e46971e24ff582c4d33331c5b8181f605c9f
[ "MIT" ]
null
null
null
from test.testcase import ArrayTestCase from test.test_functions import load_testdata from colicoords.preprocess import data_to_cells from colicoords.data_models import Data from colicoords.support import pad_cell from colicoords.cell import CellList, Cell from colicoords.fileIO import load import os import sys import numpy as np import unittest class TestCell(ArrayTestCase): def setUp(self): #todo update this self.data = load_testdata('ds2') self.cell_list = data_to_cells(self.data, initial_crop=2, rotate='binary') self.cell_obj = self.cell_list[0] self.cell_obj.optimize() def test_measure_r(self): r_max = self.cell_obj.measure_r(data_name='fluorescence', mode='max', in_place=False, step=0.5) r_mid = self.cell_obj.measure_r(data_name='fluorescence', mode='mid', in_place=False) self.assertEqual(r_max, 5.0) self.assertAlmostEqual(r_mid, 8.11, 2) r_max = self.cell_obj.measure_r(data_name='brightfield', mode='max', in_place=False, step=0.5) r_mid = self.cell_obj.measure_r(data_name='brightfield', mode='mid', in_place=False) r_min = self.cell_obj.measure_r(data_name='brightfield', mode='min', in_place=False) print(r_min) self.assertEqual(r_max, 9.0) self.assertAlmostEqual(r_mid, 6.49, 2) with self.assertRaises(ValueError): r_ = self.cell_obj.measure_r(mode='asdf') cell = self.cell_obj.copy() r_max = cell.measure_r(data_name='brightfield', mode='max', in_place=True, step=0.5) self.assertEqual(r_max, None) self.assertEqual(cell.coords.r, 9.0) def test_reconstruct(self): bf_recontstr = self.cell_obj.reconstruct_image('brightfield') lsq = np.sum((bf_recontstr - self.cell_obj.data.bf_img)**2) if sys.version_info.minor == 6: self.assertAlmostEqual(44728880.48196769, float(lsq), 2) else: # Changed from 44728880.4819674 between py3.6 -> py3.6+ self.assertAlmostEqual(44774714.40809806, float(lsq), 2) bf_rscl = self.cell_obj.reconstruct_image('brightfield', r_scale=0.5) cell = self.cell_obj.copy() cell.data.add_data(bf_rscl, 'brightfield', 'rescaled') r_mid = cell.measure_r(data_name='rescaled', mode='mid', in_place=False) self.assertAlmostEqual(12.974043291957795, float(r_mid), 2) def test_get_intensity(self): cell = self.cell_obj.copy() i0 = self.cell_obj.get_intensity() i1 = self.cell_obj.get_intensity(data_name='fluorescence') i2 = self.cell_obj.get_intensity(data_name='fluorescence', mask='coords') cell.coords.r *= 2 i3 = cell.get_intensity(data_name='fluorescence', mask='coords') i4 = self.cell_obj.get_intensity(data_name='fluorescence', func=np.max) i5 = self.cell_obj.get_intensity(data_name='fluorescence', func=np.min) i6 = self.cell_obj.get_intensity(data_name='fluorescence', func=np.median) with self.assertRaises(ValueError): self.cell_obj.get_intensity(data_name='asdfsdfa') ii = np.array([i0, i1, i2, i3, i4, i5, i6]) vi = np.array([23729.91051454139, 23729.91051454139, 23580.72807991121, 11281.533678756477, 40733, 3094, 27264.0]) assert np.allclose(ii, vi) class TestCellList(ArrayTestCase): def setUp(self): #todo update this self.data = load_testdata('ds2') self.cell_list = data_to_cells(self.data, initial_crop=2, rotate='binary') self.cell_obj = self.cell_list[0] self.cell_obj.optimize() def test_indexing(self): cell_list = self.cell_list[2:10] self.assertIsInstance(cell_list, CellList) cell = self.cell_list[5] self.assertEqual(np.where(self.cell_list.name == cell.name)[0][0], 5) self.assertIsInstance(cell, Cell) self.assertTrue(cell in self.cell_list) def test_geometry(self): props = ['radius', 'length', 'circumference', 'area', 'surface', 'volume'] cell_list_copy = self.cell_list.copy() for prop in props: m1 = getattr(self.cell_list, prop) m2 = getattr(cell_list_copy, prop) self.assertArrayEqual(m1, m2) shape = self.cell_obj.data.shape cell_pad = pad_cell(self.cell_obj, (shape[0] + 5, shape[1] + 10)) for prop in props: m1 = getattr(self.cell_obj, prop) m2 = getattr(cell_pad, prop) self.assertAlmostEqual(m1, m2, 6) # On Linux (Travis) the result is exactly equal # TODO 3D array fluorescence testing class TestCellListSTORM(ArrayTestCase): def setUp(self): f_path = os.path.dirname(os.path.realpath(__file__)) self.cell_list = load(os.path.join(f_path, 'test_data', 'test_synth_cell_storm.hdf5')) self.cell = self.cell_list[0] x = np.arange(20) y = np.exp(-x / 5) img_3d = self.cell.data.data_dict['fluorescence'][np.newaxis, :, :] * y[:, np.newaxis, np.newaxis] self.cell.data.add_data(img_3d, 'fluorescence', 'flu_3d') data = Data() data.add_data(self.cell.data.binary_img, 'binary') self.empty_cell = Cell(data) def test_l_dist(self): nbins = 50 with self.assertRaises(IndexError): x, y = self.empty_cell.l_dist(nbins) with self.assertRaises(ValueError): # todo refactor to stay as KeyError? x, y = self.cell.l_dist(nbins, data_name='notexisting') with self.assertRaises(ValueError): x, y = self.cell.l_dist(nbins, method='notexisting') storm_int_sum = np.sum(self.cell.data.data_dict['storm']['intensity']) x, y = self.cell.l_dist(nbins, data_name='storm', r_max=20) self.assertEqual(np.sum(y), storm_int_sum) x, y = self.cell.l_dist(nbins, data_name='storm', method='box', r_max=20) self.assertEqual(np.sum(y), storm_int_sum) x, y = self.cell.l_dist(nbins, data_name='storm', method='box', storm_weight=True, r_max=20) self.assertEqual(np.sum(y), storm_int_sum) x, y = self.cell.l_dist(nbins, data_name='fluorescence') x, y = self.cell.l_dist(nbins, data_name='fluorescence', method='box') x, y = self.cell.l_dist(nbins, method='box',) x, y = self.cell.l_dist(nbins, method='box', l_mean=0.75*self.cell.length, norm_x=True) x, y = self.cell.l_dist(nbins, method='box', norm_x=True) x, y = self.cell.l_dist(nbins, method='box', r_max=np.inf) x, y = self.cell.l_dist(nbins, method='box', r_max=1) x, y = self.cell.l_dist(nbins, method='box', r_max=0) x, y_list = self.cell.l_dist(nbins, data_name='flu_3d') self.assertEqual(len(y_list), 20) def test_l_classify(self): p, b, m = self.cell.l_classify(data_name='storm') total = len(self.cell.data.data_dict['storm']) self.assertEqual(p + b + m, total) p, b, m = self.cell.l_classify() total = len(self.cell.data.data_dict['storm']) self.assertEqual(p + b + m, total) def test_r_dist(self): stop = 15 step = 0.5 with self.assertRaises(IndexError): x, y = self.empty_cell.r_dist(stop, step) with self.assertRaises(ValueError): # todo refactor to stay as KeyError? x, y = self.cell.r_dist(stop, step, data_name='notexisting') with self.assertRaises(ValueError): x, y = self.cell.r_dist(stop, step, method='notexisting') stop = 15 step = 0.5 bins_box = np.arange(0, stop + step, step) + 0.5 * step bins = np.arange(0, stop + step, step) storm_int_sum = np.sum(self.cell.data.data_dict['storm']['intensity']) x, y = self.cell.r_dist(data_name='storm', stop=stop, step=step) self.assertArrayEqual(bins_box, x) self.assertEqual(np.sum(y), storm_int_sum) x, y = self.cell.r_dist(data_name='storm', stop=stop, step=step, storm_weight=True) self.assertArrayEqual(bins_box, x) self.assertEqual(np.sum(y), storm_int_sum) x, y = self.cell.r_dist(stop, step, data_name='fluorescence') self.assertArrayEqual(bins, x) x, y = self.cell.r_dist(stop, step, data_name='fluorescence', limit_l='full') x, y = self.cell.r_dist(stop, step, data_name='fluorescence', limit_l='poles') with self.assertRaises(AssertionError): x, y = self.cell.r_dist(stop, step, data_name='fluorescence', limit_l=0) with self.assertRaises(AssertionError): x, y = self.cell.r_dist(stop, step, data_name='fluorescence', limit_l=1) x, y = self.cell.r_dist(stop, step, data_name='fluorescence', limit_l=0.5) self.assertArrayEqual(bins, x) x, y = self.cell.r_dist(stop, step, data_name='fluorescence', limit_l=1e-3) self.assertArrayEqual(bins, x) x, y = self.cell.r_dist(stop, step, data_name='fluorescence', limit_l=1e-10) self.assertArrayEqual(bins, x) x, y = self.cell.r_dist(stop, step, data_name='fluorescence', limit_l=1-1e-10) self.assertArrayEqual(bins, x) def test_phi_dist(self): step = 0.5 with self.assertRaises(IndexError): x, yl, yr = self.empty_cell.phi_dist(step) with self.assertRaises(ValueError): # todo refactor to stay as KeyError? x, yl, yr = self.cell.phi_dist(step, data_name='notexisting') with self.assertRaises(ValueError): x, yl, yr = self.cell.phi_dist(step, method='notexisting') stop = 180 bins_box = np.arange(0, stop + step, step) + 0.5 * step bins = np.arange(0, stop + step, step) x, y = self.cell.data.data_dict['storm']['x'], self.cell.data.data_dict['storm']['y'] lc, rc, psi = self.cell.coords.transform(x, y) b = np.logical_and(psi != 0, psi != 180) # only localizations at poles storm_int_sum = np.sum(self.cell.data.data_dict['storm']['intensity'][b]) x, yl, yr = self.cell.phi_dist(step, data_name='storm', r_max=np.inf) self.assertArrayEqual(bins_box, x) self.assertEqual(np.sum(yl + yr), storm_int_sum) x, yl, yr = self.cell.phi_dist(step, data_name='storm', storm_weight=True, r_max=np.inf) self.assertArrayEqual(bins_box, x) self.assertEqual(np.sum(yl + yr), storm_int_sum) x, yl, yr = self.cell.phi_dist(step, data_name='storm', r_max=0) self.assertEqual(np.sum(yl + yr), 0) x, yl, yr = self.cell.phi_dist(step, data_name='fluorescence') self.assertArrayEqual(bins, x) x, yl, yr = self.cell.phi_dist(step, data_name='fluorescence', r_min=-5) x, yl, yr = self.cell.phi_dist(step, data_name='fluorescence', r_max=0) x, yl, yr = self.cell.phi_dist(step, data_name='fluorescence', r_max=0, r_min=5) self.assertEqual(np.sum(yl + yr), 0) if __name__ == '__main__': unittest.main()
43.454198
123
0.618621
c7efb9ed7449394c573acbaa1492998a9b1bbb18
1,756
py
Python
apps/songs/patches.py
Torniojaws/vortech-backend
f775a97eeae089fa720088d86fe92d40bc5d65bc
[ "MIT" ]
null
null
null
apps/songs/patches.py
Torniojaws/vortech-backend
f775a97eeae089fa720088d86fe92d40bc5d65bc
[ "MIT" ]
93
2017-09-01T22:24:10.000Z
2021-12-22T14:07:06.000Z
apps/songs/patches.py
Torniojaws/vortech-backend
f775a97eeae089fa720088d86fe92d40bc5d65bc
[ "MIT" ]
null
null
null
"""To implement the RFC 6902 logic for patches, there are some various complex methods needed. For clarity, they are in this separate file as helper methods.""" from copy import deepcopy from jsonpatch import JsonPatch def patch_item(song, patchdata, **kwargs): """This is used to run patches on the database model, using the method described here: https://gist.github.com/mattupstate/d63caa0156b3d2bdfcdb NB: There are two limitations: 1. When op is "move", there is no simple way to make sure the source is empty 2. When op is "remove", there also is no simple way to make sure the source is empty Most of the data in this project is nullable=False anyway, so they cannot be deleted. """ # Map the values to DB column names mapped_patchdata = [] for p in patchdata: if p["op"] == "move" or p["op"] == "remove": # Nothing in this resource is nullable, so let's raise to return 422 in the main raise ValueError("No nullable values in Songs") # Replace eg. /title with /Title p = patch_mapping(p) mapped_patchdata.append(p) data = song.asdict(exclude_pk=True, **kwargs) patch = JsonPatch(mapped_patchdata) data = patch.apply(data) song.fromdict(data) def patch_mapping(patch): """This is used to map a patch "path" or "from" to a custom value. Useful for when the patch path/from is not the same as the DB column name.""" mapping = { "/title": "/Title", "/duration": "/Duration", } mutable = deepcopy(patch) for prop in patch: if prop == "path" or prop == "from": mutable[prop] = mapping.get(patch[prop], None) return mutable
37.361702
95
0.643508
256938d9027345a88523d27064d66f9053052ad1
759
py
Python
functional_spec/src/cars.py
sahasrara62/parking_lot
ada8f14ce2bf0d9ccd9472ab1c5d4376f1e2a85e
[ "Apache-2.0" ]
3
2020-01-30T11:58:11.000Z
2021-03-24T06:43:49.000Z
functional_spec/src/cars.py
sahasrara62/parking_lot
ada8f14ce2bf0d9ccd9472ab1c5d4376f1e2a85e
[ "Apache-2.0" ]
null
null
null
functional_spec/src/cars.py
sahasrara62/parking_lot
ada8f14ce2bf0d9ccd9472ab1c5d4376f1e2a85e
[ "Apache-2.0" ]
5
2019-10-20T18:29:34.000Z
2022-01-22T04:12:55.000Z
__all__ = ['Car'] class Car(object): """ defining the property of the car property include : car "registration number" and "colour" of the car """ def __init__(self, registration_number, color): """ initialising the car object :param registration_number: registation number of car :param color: color of car """ self._reg_number = registration_number self._color = color @property def get_registration_number(self): """ give registration number of the car :return: """ return self._reg_number @property def get_color(self): """ return color of car :return: """ return self._color
21.083333
72
0.578393
8c72269eb6344355df7d62a8b5e36378f967ad06
129
py
Python
routes/web.py
josephmancuso/ambient
193152d72ca2302f2167ac5e4afcc50fa48d0bc2
[ "MIT" ]
5
2020-06-07T14:20:50.000Z
2020-07-24T15:20:42.000Z
routes/web.py
josephmancuso/ambient
193152d72ca2302f2167ac5e4afcc50fa48d0bc2
[ "MIT" ]
null
null
null
routes/web.py
josephmancuso/ambient
193152d72ca2302f2167ac5e4afcc50fa48d0bc2
[ "MIT" ]
null
null
null
"""Web Routes.""" from masonite.routes import Route ROUTES = [ Route.get('/', 'WelcomeController@show').name('welcome'), ]
16.125
61
0.651163
805a3334542dd9d9f7ce49999346e1053eaf9e02
5,149
py
Python
code_for_hw5/code_for_hw5/modules_disp.py
codr-oneci/Machine-Learning-Algorithms
9d90fc4abe8646e86c38c69a2969b23e501a792e
[ "MIT" ]
null
null
null
code_for_hw5/code_for_hw5/modules_disp.py
codr-oneci/Machine-Learning-Algorithms
9d90fc4abe8646e86c38c69a2969b23e501a792e
[ "MIT" ]
null
null
null
code_for_hw5/code_for_hw5/modules_disp.py
codr-oneci/Machine-Learning-Algorithms
9d90fc4abe8646e86c38c69a2969b23e501a792e
[ "MIT" ]
null
null
null
import pdb import numpy as np import random import matplotlib import matplotlib.pyplot as plt def classify(X, Y, nn, it=10000, lr=0.005): D = X.shape[0] N = X.shape[1] O = Y.shape[0] # Modifies the weights and biases nn.sgd(X, Y, it, lr) # Draw it... def predict(x): return nn.modules[-1].class_fun(nn.forward(x))[0] xmin, ymin = np.min(X, axis=1)-1 xmax, ymax = np.max(X, axis=1)+1 print(xmin,ymin,xmax,ymax) nax = plot_objective_2d(lambda x: predict(x), xmin, xmax, ymin, ymax) plot_data(X, Y, nax) plt.show() return nn #################### # SUPPORT AND DISPLAY CODE #################### # Takes a list of numbers and returns a row vector: 1 x n def rv(value_list): return np.array([value_list]) def cv(value_list): return np.transpose(rv(value_list)) def tidy_plot(xmin, xmax, ymin, ymax, center = False, title = None, xlabel = None, ylabel = None): plt.figure(facecolor="white") ax = plt.subplot() if center: ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['bottom'].set_position('zero') ax.spines['top'].set_color('none') ax.spines['left'].set_smart_bounds(True) ax.spines['bottom'].set_smart_bounds(True) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') else: ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() eps = .05 plt.xlim(xmin-eps, xmax+eps) plt.ylim(ymin-eps, ymax+eps) if title: ax.set_title(title) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) return ax def plot_points(x, y, ax = None, clear = False, xmin = None, xmax = None, ymin = None, ymax = None, style = 'or-', equal = False): padup = lambda v: v + 0.05 * abs(v) paddown = lambda v: v - 0.05 * abs(v) if ax is None: if xmin == None: xmin = paddown(np.min(x)) if xmax == None: xmax = padup(np.max(x)) if ymin == None: ymin = paddown(np.min(y)) if ymax == None: ymax = padup(np.max(y)) ax = tidy_plot(xmin, xmax, ymin, ymax) x_range = xmax - xmin; y_range = ymax - ymin if equal and .1 < x_range / y_range < 10: #ax.set_aspect('equal') plt.axis('equal') if x_range > y_range: ax.set_xlim((xmin, xmax)) else: ax.set_ylim((ymin, ymax)) xlim, ylim = ax.get_xlim(), ax.get_ylim() elif clear: xlim, ylim = ax.get_xlim(), ax.get_ylim() ax.clear() else: xlim, ylim = ax.get_xlim(), ax.get_ylim() ax.plot(x, y, style, markeredgewidth=0.0, linewidth = 5.0) # Seems to occasionally mess up the limits ax.set_xlim(xlim); ax.set_ylim(ylim) ax.grid(True, which='both') return ax def add_ones(X): return np.vstack([X, np.ones(X.shape[1])]) def plot_data(data, labels, ax = None, xmin = None, xmax = None, ymin = None, ymax = None): # Handle 1D data if data.shape[0] == 1: data = add_ones(data) if ax is None: if xmin == None: xmin = np.min(data[0, :]) - 0.5 if xmax == None: xmax = np.max(data[0, :]) + 0.5 if ymin == None: ymin = np.min(data[1, :]) - 0.5 if ymax == None: ymax = np.max(data[1, :]) + 0.5 ax = tidy_plot(xmin, xmax, ymin, ymax) x_range = xmax - xmin; y_range = ymax - ymin if .1 < x_range / y_range < 10: ax.set_aspect('equal') xlim, ylim = ax.get_xlim(), ax.get_ylim() else: xlim, ylim = ax.get_xlim(), ax.get_ylim() for yi in set([int(_y) for _y in set(labels.flatten().tolist())]): color = ['r', 'g', 'b'][yi] marker = ['X', 'o', 'v'][yi] cl = np.where(labels[0,:]==yi) ax.scatter(data[0,cl], data[1,cl], c = color, marker = marker, s=50, edgecolors = 'none') ax.set_xlim(xlim); ax.set_ylim(ylim) ax.grid(True, which='both') return ax def plot_objective_2d(J, xmin = -5, xmax = 5, ymin = -5, ymax = 5, cmin = None, cmax = None, res = 50, ax = None): if ax is None: ax = tidy_plot(xmin, xmax, ymin, ymax) else: if xmin == None: xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() else: ax.set_xlim((xmin, xmax)) ax.set_ylim((ymin, ymax)) ima = np.array([[J(cv([x1i, x2i])) \ for x1i in np.linspace(xmin, xmax, res)] \ for x2i in np.linspace(ymin, ymax, res)]) im = ax.imshow(np.flipud(ima), interpolation = 'none', extent = [xmin, xmax, ymin, ymax], cmap = 'viridis') if cmin is not None or cmax is not None: if cmin is None: cmin = min(ima) if cmax is None: cmax = max(ima) im.set_clim(cmin, cmax) plt.colorbar(im) return ax
34.326667
76
0.540882
35ba03d36d6034ab09960f756ec38d5915a47aea
69,265
py
Python
samples/contrib/e2e-outlier-drift-explainer/seldon/seldon_e2e_cifar10.kale.nfs.py
evan-hataishi/kfp-tekton
6e1f367841c7add4ca13e5472220939846da81b0
[ "Apache-2.0" ]
null
null
null
samples/contrib/e2e-outlier-drift-explainer/seldon/seldon_e2e_cifar10.kale.nfs.py
evan-hataishi/kfp-tekton
6e1f367841c7add4ca13e5472220939846da81b0
[ "Apache-2.0" ]
1,720
2021-01-25T09:32:00.000Z
2022-03-31T08:09:51.000Z
samples/contrib/e2e-outlier-drift-explainer/seldon/seldon_e2e_cifar10.kale.nfs.py
evan-hataishi/kfp-tekton
6e1f367841c7add4ca13e5472220939846da81b0
[ "Apache-2.0" ]
null
null
null
import kfp.dsl as dsl import json import kfp.components as comp from collections import OrderedDict from kubernetes import client as k8s_client def setup(MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_MODEL_BUCKET: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_MODEL_BUCKET = "{}" MINIO_SECRET_KEY = "{}" '''.format(MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorImage from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch from alibi_detect.utils.fetching import fetch_tf_model import json import logging import matplotlib.pyplot as plt import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image import time logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' minioClient = get_minio() buckets = minioClient.list_buckets() for bucket in buckets: print(bucket.name, bucket.creation_date) ''' block4 = ''' if not minioClient.bucket_exists(MINIO_MODEL_BUCKET): minioClient.make_bucket(MINIO_MODEL_BUCKET) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, ) html_artifact = _kale_run_code(blocks) with open("/setup.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('setup') _kale_mlmd_utils.call("mark_execution_complete") def train_model_and_explainer(CIFAR10_MODEL_PATH: str, EXPLAINER_MODEL_PATH: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_MODEL_BUCKET: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' CIFAR10_MODEL_PATH = "{}" EXPLAINER_MODEL_PATH = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_MODEL_BUCKET = "{}" MINIO_SECRET_KEY = "{}" '''.format(CIFAR10_MODEL_PATH, EXPLAINER_MODEL_PATH, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorImage from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch from alibi_detect.utils.fetching import fetch_tf_model import json import logging import matplotlib.pyplot as plt import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image import time logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' model = fetch_tf_model('cifar10', 'resnet32') ''' block4 = ''' train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype('float32') / 255 X_test = X_test.astype('float32') / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) ''' block5 = ''' class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] ''' block6 = ''' idx = 1 X = X_test[idx].reshape(1, 32, 32, 3) plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() print("class:",class_names[y_test[idx][0]]) print("prediction:",class_names[model.predict(X_test[idx:idx+1])[0].argmax()]) ''' block7 = ''' modelfilepath="resnet" tf.saved_model.save(model, modelfilepath) ''' block8 = ''' from os import listdir from os.path import isfile, join model_filepath="resnet" print(get_minio().fput_object(MINIO_MODEL_BUCKET, f"{CIFAR10_MODEL_PATH}/1/saved_model.pb", modelfilepath+"/saved_model.pb")) variable_filepath = modelfilepath+"/variables" onlyfiles = [f for f in listdir(variable_filepath) if isfile(join(variable_filepath, f))] for filename in onlyfiles: print(filename) print(get_minio().fput_object(MINIO_MODEL_BUCKET, f"{CIFAR10_MODEL_PATH}/1/variables/{filename}", join(variable_filepath, filename))) ''' block9 = ''' def predict_fn(x): return model.predict(x) ''' block10 = ''' image_shape = (32, 32, 3) segmentation_fn = 'slic' kwargs = {'n_segments': 5, 'compactness': 20, 'sigma': .5} explainer = AnchorImage(predict_fn, image_shape, segmentation_fn=segmentation_fn, segmentation_kwargs=kwargs, images_background=None) ''' block11 = ''' idx=0 image = X_test[0] np.random.seed(0) explanation = explainer.explain(image, threshold=.95, p_sample=.5, tau=0.25) ''' block12 = ''' X = X_test[idx].reshape(1, 32, 32, 3) plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() print("class:",class_names[y_test[idx][0]]) print("prediction:",class_names[model.predict(X_test[idx:idx+1])[0].argmax()]) ''' block13 = ''' plt.imshow(explanation["anchor"]) ''' block14 = ''' with open("explainer.dill", "wb") as dill_file: dill.dump(explainer, dill_file) dill_file.close() print(get_minio().fput_object(MINIO_MODEL_BUCKET, f"{EXPLAINER_MODEL_PATH}/explainer.dill", 'explainer.dill')) ''' data_saving_block = ''' # -----------------------DATA SAVING START--------------------------------- from kale.marshal import utils as _kale_marshal_utils _kale_marshal_utils.set_kale_data_directory("/marshal") _kale_marshal_utils.save(X_test, "X_test") _kale_marshal_utils.save(X_train, "X_train") _kale_marshal_utils.save(class_names, "class_names") _kale_marshal_utils.save(y_test, "y_test") _kale_marshal_utils.save(y_train, "y_train") # -----------------------DATA SAVING END----------------------------------- ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, block5, block6, block7, block8, block9, block10, block11, block12, block13, block14, data_saving_block) html_artifact = _kale_run_code(blocks) with open("/train_model_and_explainer.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('train_model_and_explainer') _kale_mlmd_utils.call("mark_execution_complete") def deploy_model(CIFAR10_MODEL_PATH: str, DEPLOY_NAMESPACE: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_MODEL_BUCKET: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' CIFAR10_MODEL_PATH = "{}" DEPLOY_NAMESPACE = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_MODEL_BUCKET = "{}" MINIO_SECRET_KEY = "{}" '''.format(CIFAR10_MODEL_PATH, DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() data_loading_block = ''' # -----------------------DATA LOADING START-------------------------------- from kale.marshal import utils as _kale_marshal_utils _kale_marshal_utils.set_kale_data_directory("/marshal") _kale_marshal_utils.set_kale_directory_file_names() X_test = _kale_marshal_utils.load("X_test") class_names = _kale_marshal_utils.load("class_names") y_test = _kale_marshal_utils.load("y_test") # -----------------------DATA LOADING END---------------------------------- ''' block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorImage from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch from alibi_detect.utils.fetching import fetch_tf_model import json import logging import matplotlib.pyplot as plt import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image import time logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' secret = f"""apiVersion: v1 kind: Secret metadata: name: seldon-init-container-secret namespace: {DEPLOY_NAMESPACE} type: Opaque stringData: AWS_ACCESS_KEY_ID: {MINIO_ACCESS_KEY} AWS_SECRET_ACCESS_KEY: {MINIO_SECRET_KEY} AWS_ENDPOINT_URL: http://{MINIO_HOST} USE_SSL: "false" """ with open("secret.yaml","w") as f: f.write(secret) run("cat secret.yaml | kubectl apply -f -", shell=True) ''' block4 = ''' sa = f"""apiVersion: v1 kind: ServiceAccount metadata: name: minio-sa namespace: {DEPLOY_NAMESPACE} secrets: - name: seldon-init-container-secret """ with open("sa.yaml","w") as f: f.write(sa) run("kubectl apply -f sa.yaml", shell=True) ''' block5 = ''' model_yaml=f"""apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: cifar10-classifier namespace: {DEPLOY_NAMESPACE} spec: protocol: tensorflow predictors: - componentSpecs: graph: implementation: TENSORFLOW_SERVER modelUri: s3://{MINIO_MODEL_BUCKET}/{CIFAR10_MODEL_PATH} envSecretRefName: seldon-init-container-secret name: classifier logger: mode: all explainer: type: AnchorImages name: default replicas: 1 """ with open("model.yaml","w") as f: f.write(model_yaml) run("kubectl apply -f model.yaml", shell=True) ''' block6 = ''' run(f"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l seldon-deployment-id=cifar10-classifier -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE})", shell=True) ''' block7 = ''' run(f"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l seldon-deployment-id=cifar10-classifier -o jsonpath='{{.items[1].metadata.name}}' -n {DEPLOY_NAMESPACE})", shell=True) ''' block8 = ''' def test_model(): idx=10 test_example=X_test[idx:idx+1].tolist() payload='{"instances":'+f"{test_example}"+' }' cmd=f"""curl -d '{payload}' \\ http://cifar10-classifier-default.{DEPLOY_NAMESPACE}:8000/v1/models/classifier/:predict \\ -H "Content-Type: application/json" """ ret = Popen(cmd, shell=True,stdout=PIPE) raw = ret.stdout.read().decode("utf-8") print(raw) res=json.loads(raw) arr=np.array(res["predictions"]) X = X_test[idx].reshape(1, 32, 32, 3) plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() print("class:",class_names[y_test[idx][0]]) print("prediction:",class_names[arr[0].argmax()]) ok = False while not ok: try: test_model() ok = True except: print("Failed calling model, sleeping") time.sleep(2) ''' block9 = ''' idx=10 test_example=X_test[idx:idx+1].tolist() payload='{"instances":'+f"{test_example}"+' }' cmd=f"""curl -d '{payload}' \\ http://cifar10-classifier-default-explainer.{DEPLOY_NAMESPACE}:9000/v1/models/cifar10-classifier/:explain \\ -H "Content-Type: application/json" """ ret = Popen(cmd, shell=True,stdout=PIPE) raw = ret.stdout.read().decode("utf-8") print(raw) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, data_loading_block, block1, block2, block3, block4, block5, block6, block7, block8, block9, ) html_artifact = _kale_run_code(blocks) with open("/deploy_model.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('deploy_model') _kale_mlmd_utils.call("mark_execution_complete") def train_drift_detector(DRIFT_MODEL_PATH: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_MODEL_BUCKET: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' DRIFT_MODEL_PATH = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_MODEL_BUCKET = "{}" MINIO_SECRET_KEY = "{}" '''.format(DRIFT_MODEL_PATH, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() data_loading_block = ''' # -----------------------DATA LOADING START-------------------------------- from kale.marshal import utils as _kale_marshal_utils _kale_marshal_utils.set_kale_data_directory("/marshal") _kale_marshal_utils.set_kale_directory_file_names() X_test = _kale_marshal_utils.load("X_test") y_test = _kale_marshal_utils.load("y_test") # -----------------------DATA LOADING END---------------------------------- ''' block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorImage from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch from alibi_detect.utils.fetching import fetch_tf_model import json import logging import matplotlib.pyplot as plt import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image import time logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' import matplotlib.pyplot as plt import numpy as np import os import tensorflow as tf from tensorflow.keras.layers import Conv2D, Dense, Flatten, InputLayer, Reshape from alibi_detect.cd import KSDrift from alibi_detect.cd.preprocess import uae, hidden_output from alibi_detect.models.resnet import scale_by_instance from alibi_detect.utils.fetching import fetch_tf_model, fetch_detector from alibi_detect.utils.prediction import predict_batch from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.datasets import fetch_cifar10c, corruption_types_cifar10c ''' block4 = ''' tf.random.set_seed(0) if True: np.random.seed(0) n_test = X_test.shape[0] idx = np.random.choice(n_test, size=n_test // 2, replace=False) idx_h0 = np.delete(np.arange(n_test), idx, axis=0) X_ref,y_ref = X_test[idx], y_test[idx] X_h0, y_h0 = X_test[idx_h0], y_test[idx_h0] print(X_ref.shape, X_h0.shape) # define encoder encoding_dim = 32 encoder_net = tf.keras.Sequential( [ InputLayer(input_shape=(32, 32, 3)), Conv2D(64, 4, strides=2, padding='same', activation=tf.nn.relu), Conv2D(128, 4, strides=2, padding='same', activation=tf.nn.relu), Conv2D(512, 4, strides=2, padding='same', activation=tf.nn.relu), Flatten(), Dense(encoding_dim,) ] ) # initialise drift detector p_val = .05 cd = KSDrift( p_val=p_val, # p-value for K-S test X_ref=X_ref, # test against original test set preprocess_fn=uae, # UAE for dimensionality reduction preprocess_kwargs={'encoder_net': encoder_net, 'batch_size': 128}, alternative='two-sided' # other options: 'less', 'greater' ) else: cd = load_detector("/home/models/samples/cd/cifar10") ''' block5 = ''' from alibi_detect.utils.saving import save_detector, load_detector from os import listdir from os.path import isfile, join filepath="cifar10Drift" save_detector(cd, filepath) onlyfiles = [f for f in listdir(filepath) if isfile(join(filepath, f))] for filename in onlyfiles: print(filename) print(get_minio().fput_object(MINIO_MODEL_BUCKET, f"{DRIFT_MODEL_PATH}/{filename}", join(filepath, filename))) filepath="cifar10Drift/model" onlyfiles = [f for f in listdir(filepath) if isfile(join(filepath, f))] for filename in onlyfiles: print(filename) print(get_minio().fput_object(MINIO_MODEL_BUCKET, f"{DRIFT_MODEL_PATH}/model/{filename}", join(filepath, filename))) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, data_loading_block, block1, block2, block3, block4, block5, ) html_artifact = _kale_run_code(blocks) with open("/train_drift_detector.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('train_drift_detector') _kale_mlmd_utils.call("mark_execution_complete") def train_outlier_detector(MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_MODEL_BUCKET: str, MINIO_SECRET_KEY: str, OUTLIER_MODEL_PATH: str, TRAIN_OUTLIER_DETECTOR: bool): pipeline_parameters_block = ''' MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_MODEL_BUCKET = "{}" MINIO_SECRET_KEY = "{}" OUTLIER_MODEL_PATH = "{}" TRAIN_OUTLIER_DETECTOR = {} '''.format(MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY, OUTLIER_MODEL_PATH, TRAIN_OUTLIER_DETECTOR) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() data_loading_block = ''' # -----------------------DATA LOADING START-------------------------------- from kale.marshal import utils as _kale_marshal_utils _kale_marshal_utils.set_kale_data_directory("/marshal") _kale_marshal_utils.set_kale_directory_file_names() X_train = _kale_marshal_utils.load("X_train") # -----------------------DATA LOADING END---------------------------------- ''' block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorImage from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch from alibi_detect.utils.fetching import fetch_tf_model import json import logging import matplotlib.pyplot as plt import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image import time logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' import logging import matplotlib.pyplot as plt import numpy as np import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block4 = ''' if TRAIN_OUTLIER_DETECTOR: latent_dim = 1024 encoder_net = tf.keras.Sequential( [ InputLayer(input_shape=(32, 32, 3)), Conv2D(64, 4, strides=2, padding='same', activation=tf.nn.relu), Conv2D(128, 4, strides=2, padding='same', activation=tf.nn.relu), Conv2D(512, 4, strides=2, padding='same', activation=tf.nn.relu) ]) decoder_net = tf.keras.Sequential( [ InputLayer(input_shape=(latent_dim,)), Dense(4*4*128), Reshape(target_shape=(4, 4, 128)), Conv2DTranspose(256, 4, strides=2, padding='same', activation=tf.nn.relu), Conv2DTranspose(64, 4, strides=2, padding='same', activation=tf.nn.relu), Conv2DTranspose(3, 4, strides=2, padding='same', activation='sigmoid') ]) # initialize outlier detector od = OutlierVAE(threshold=.015, # threshold for outlier score score_type='mse', # use MSE of reconstruction error for outlier detection encoder_net=encoder_net, # can also pass VAE model instead decoder_net=decoder_net, # of separate encoder and decoder latent_dim=latent_dim, samples=2) # train od.fit(X_train, loss_fn=elbo, cov_elbo=dict(sim=.05), epochs=50, verbose=True) else: od = load_detector("/home/models/samples/od/cifar10") ''' block5 = ''' idx = 8 X = X_train[idx].reshape(1, 32, 32, 3) X_recon = od.vae(X) plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() plt.imshow(X_recon.numpy().reshape(32, 32, 3)) plt.axis('off') plt.show() ''' block6 = ''' X = X_train[:500] print(X.shape) od_preds = od.predict(X, outlier_type='instance', # use 'feature' or 'instance' level return_feature_score=True, # scores used to determine outliers return_instance_score=True) print(list(od_preds['data'].keys())) target = np.zeros(X.shape[0],).astype(int) # all normal CIFAR10 training instances labels = ['normal', 'outlier'] plot_instance_score(od_preds, target, labels, od.threshold) ''' block7 = ''' from alibi_detect.utils.saving import save_detector, load_detector from os import listdir from os.path import isfile, join filepath="cifar10outlier" save_detector(od, filepath) onlyfiles = [f for f in listdir(filepath) if isfile(join(filepath, f))] for filename in onlyfiles: print(filename) print(get_minio().fput_object(MINIO_MODEL_BUCKET, f"{OUTLIER_MODEL_PATH}/{filename}", join(filepath, filename))) filepath="cifar10outlier/model" onlyfiles = [f for f in listdir(filepath) if isfile(join(filepath, f))] for filename in onlyfiles: print(filename) print(get_minio().fput_object(MINIO_MODEL_BUCKET, f"{OUTLIER_MODEL_PATH}/model/{filename}", join(filepath, filename))) ''' data_saving_block = ''' # -----------------------DATA SAVING START--------------------------------- from kale.marshal import utils as _kale_marshal_utils _kale_marshal_utils.set_kale_data_directory("/marshal") _kale_marshal_utils.save(X_train, "X_train") # -----------------------DATA SAVING END----------------------------------- ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, data_loading_block, block1, block2, block3, block4, block5, block6, block7, data_saving_block) html_artifact = _kale_run_code(blocks) with open("/train_outlier_detector.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('train_outlier_detector') _kale_mlmd_utils.call("mark_execution_complete") def deploy_event_display(DEPLOY_NAMESPACE: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' DEPLOY_NAMESPACE = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_SECRET_KEY = "{}" '''.format(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorImage from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch from alibi_detect.utils.fetching import fetch_tf_model import json import logging import matplotlib.pyplot as plt import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image import time logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' event_display=f"""apiVersion: apps/v1 kind: Deployment metadata: name: event-display namespace: {DEPLOY_NAMESPACE} spec: replicas: 1 selector: matchLabels: &labels app: event-display template: metadata: labels: *labels spec: containers: - name: helloworld-go # Source code: https://github.com/knative/eventing-contrib/tree/master/cmd/event_display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display@sha256:f4628e97a836c77ed38bd3b6fd3d0b06de4d5e7db6704772fe674d48b20bd477 --- kind: Service apiVersion: v1 metadata: name: event-display namespace: {DEPLOY_NAMESPACE} spec: selector: app: event-display ports: - protocol: TCP port: 80 targetPort: 8080 --- apiVersion: eventing.knative.dev/v1alpha1 kind: Trigger metadata: name: cifar10-outlier-display namespace: {DEPLOY_NAMESPACE} spec: broker: default filter: attributes: type: io.seldon.serving.inference.outlier subscriber: ref: apiVersion: v1 kind: Service name: event-display --- apiVersion: eventing.knative.dev/v1alpha1 kind: Trigger metadata: name: cifar10-drift-display namespace: {DEPLOY_NAMESPACE} spec: broker: default filter: attributes: type: io.seldon.serving.inference.drift subscriber: ref: apiVersion: v1 kind: Service name: event-display """ with open("event_display.yaml","w") as f: f.write(event_display) run("kubectl apply -f event_display.yaml", shell=True) ''' block4 = ''' run(f"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/event-display -n {DEPLOY_NAMESPACE}", shell=True) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, ) html_artifact = _kale_run_code(blocks) with open("/deploy_event_display.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('deploy_event_display') _kale_mlmd_utils.call("mark_execution_complete") def deploy_outlier_detector(DEPLOY_NAMESPACE: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_MODEL_BUCKET: str, MINIO_SECRET_KEY: str, OUTLIER_MODEL_PATH: str): pipeline_parameters_block = ''' DEPLOY_NAMESPACE = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_MODEL_BUCKET = "{}" MINIO_SECRET_KEY = "{}" OUTLIER_MODEL_PATH = "{}" '''.format(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY, OUTLIER_MODEL_PATH) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorImage from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch from alibi_detect.utils.fetching import fetch_tf_model import json import logging import matplotlib.pyplot as plt import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image import time logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' outlier_yaml=f"""apiVersion: serving.knative.dev/v1 kind: Service metadata: name: cifar10-outlier namespace: {DEPLOY_NAMESPACE} spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.2.1 imagePullPolicy: IfNotPresent args: - --model_name - cifar10od - --protocol - tensorflow.http - --storage_uri - s3://{MINIO_MODEL_BUCKET}/{OUTLIER_MODEL_PATH} - --reply_url - http://default-broker - --event_type - io.seldon.serving.inference.outlier - --event_source - io.seldon.serving.cifar10od - OutlierDetector envFrom: - secretRef: name: seldon-init-container-secret """ with open("outlier.yaml","w") as f: f.write(outlier_yaml) run("kubectl apply -f outlier.yaml", shell=True) ''' block4 = ''' trigger_outlier_yaml=f"""apiVersion: eventing.knative.dev/v1alpha1 kind: Trigger metadata: name: cifar10-outlier-trigger namespace: {DEPLOY_NAMESPACE} spec: filter: sourceAndType: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: cifar10-outlier """ with open("outlier_trigger.yaml","w") as f: f.write(trigger_outlier_yaml) run("kubectl apply -f outlier_trigger.yaml", shell=True) ''' block5 = ''' run(f"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l serving.knative.dev/service=cifar10-outlier -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE})", shell=True) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, block5, ) html_artifact = _kale_run_code(blocks) with open("/deploy_outlier_detector.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('deploy_outlier_detector') _kale_mlmd_utils.call("mark_execution_complete") def test_oulier_detection(DEPLOY_NAMESPACE: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' DEPLOY_NAMESPACE = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_SECRET_KEY = "{}" '''.format(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() data_loading_block = ''' # -----------------------DATA LOADING START-------------------------------- from kale.marshal import utils as _kale_marshal_utils _kale_marshal_utils.set_kale_data_directory("/marshal") _kale_marshal_utils.set_kale_directory_file_names() X_train = _kale_marshal_utils.load("X_train") class_names = _kale_marshal_utils.load("class_names") y_train = _kale_marshal_utils.load("y_train") # -----------------------DATA LOADING END---------------------------------- ''' block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorImage from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch from alibi_detect.utils.fetching import fetch_tf_model import json import logging import matplotlib.pyplot as plt import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image import time logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' idx = 1 X = X_train[idx:idx+1] ''' block4 = ''' np.random.seed(0) X_mask, mask = apply_mask(X.reshape(1, 32, 32, 3), mask_size=(10,10), n_masks=1, channels=[0,1,2], mask_type='normal', noise_distr=(0,1), clip_rng=(0,1)) ''' block5 = ''' def predict(): test_example=X_mask.tolist() payload='{"instances":'+f"{test_example}"+' }' cmd=f"""curl -d '{payload}' \\ http://cifar10-classifier-default.{DEPLOY_NAMESPACE}:8000/v1/models/classifier/:predict \\ -H "Content-Type: application/json" """ ret = Popen(cmd, shell=True,stdout=PIPE) raw = ret.stdout.read().decode("utf-8") print(raw) res=json.loads(raw) arr=np.array(res["predictions"]) plt.imshow(X_mask.reshape(32, 32, 3)) plt.axis('off') plt.show() print("class:",class_names[y_train[idx][0]]) print("prediction:",class_names[arr[0].argmax()]) ''' block6 = ''' def get_outlier_event_display_logs(): cmd=f"kubectl logs $(kubectl get pod -l app=event-display -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE}) -n {DEPLOY_NAMESPACE}" ret = Popen(cmd, shell=True,stdout=PIPE) res = ret.stdout.read().decode("utf-8").split("\\n") data= [] for i in range(0,len(res)): if res[i] == 'Data,': j = json.loads(json.loads(res[i+1])) if "is_outlier"in j["data"].keys(): data.append(j) if len(data) > 0: return data[-1] else: return None j = None while j is None: predict() print("Waiting for outlier logs, sleeping") time.sleep(2) j = get_outlier_event_display_logs() print(j) print("Outlier",j["data"]["is_outlier"]==[1]) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, data_loading_block, block1, block2, block3, block4, block5, block6, ) html_artifact = _kale_run_code(blocks) with open("/test_oulier_detection.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('test_oulier_detection') _kale_mlmd_utils.call("mark_execution_complete") def deploy_drift_detector(DEPLOY_NAMESPACE: str, DRIFT_MODEL_PATH: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_MODEL_BUCKET: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' DEPLOY_NAMESPACE = "{}" DRIFT_MODEL_PATH = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_MODEL_BUCKET = "{}" MINIO_SECRET_KEY = "{}" '''.format(DEPLOY_NAMESPACE, DRIFT_MODEL_PATH, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorImage from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch from alibi_detect.utils.fetching import fetch_tf_model import json import logging import matplotlib.pyplot as plt import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image import time logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' drift_yaml=f"""apiVersion: serving.knative.dev/v1 kind: Service metadata: name: cifar10-drift namespace: {DEPLOY_NAMESPACE} spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.2.2-dev imagePullPolicy: IfNotPresent args: - --model_name - cifar10cd - --protocol - tensorflow.http - --storage_uri - s3://{MINIO_MODEL_BUCKET}/{DRIFT_MODEL_PATH} - --reply_url - http://default-broker - --event_type - io.seldon.serving.inference.drift - --event_source - io.seldon.serving.cifar10cd - DriftDetector - --drift_batch_size - '500' envFrom: - secretRef: name: seldon-init-container-secret """ with open("drift.yaml","w") as f: f.write(drift_yaml) run("kubectl apply -f drift.yaml", shell=True) ''' block4 = ''' trigger_outlier_yaml=f"""apiVersion: eventing.knative.dev/v1alpha1 kind: Trigger metadata: name: cifar10-drift-trigger namespace: {DEPLOY_NAMESPACE} spec: filter: sourceAndType: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: cifar10-drift """ with open("outlier_trigger.yaml","w") as f: f.write(trigger_outlier_yaml) run("kubectl apply -f outlier_trigger.yaml", shell=True) ''' block5 = ''' run(f"kubectl rollout status -n {DEPLOY_NAMESPACE} deploy/$(kubectl get deploy -l serving.knative.dev/service=cifar10-drift -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE})", shell=True) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, block5, ) html_artifact = _kale_run_code(blocks) with open("/deploy_drift_detector.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('deploy_drift_detector') _kale_mlmd_utils.call("mark_execution_complete") def test_drift_detector(DEPLOY_NAMESPACE: str, MINIO_ACCESS_KEY: str, MINIO_HOST: str, MINIO_SECRET_KEY: str): pipeline_parameters_block = ''' DEPLOY_NAMESPACE = "{}" MINIO_ACCESS_KEY = "{}" MINIO_HOST = "{}" MINIO_SECRET_KEY = "{}" '''.format(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_SECRET_KEY) from kale.utils import mlmd_utils as _kale_mlmd_utils _kale_mlmd_utils.init_metadata() block1 = ''' import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, OneHotEncoder from alibi.explainers import AnchorImage from alibi.datasets import fetch_adult from minio import Minio from minio.error import ResponseError from joblib import dump, load import dill from subprocess import run, Popen, PIPE from alibi_detect.utils.data import create_outlier_batch from alibi_detect.utils.fetching import fetch_tf_model import json import logging import matplotlib.pyplot as plt import tensorflow as tf tf.keras.backend.clear_session() from tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Layer, Reshape, InputLayer from tqdm import tqdm from alibi_detect.models.losses import elbo from alibi_detect.od import OutlierVAE from alibi_detect.utils.fetching import fetch_detector from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.saving import save_detector, load_detector from alibi_detect.utils.visualize import plot_instance_score, plot_feature_outlier_image import time logger = tf.get_logger() logger.setLevel(logging.ERROR) ''' block2 = ''' def get_minio(): return Minio(MINIO_HOST, access_key=MINIO_ACCESS_KEY, secret_key=MINIO_SECRET_KEY, secure=False) ''' block3 = ''' def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() ''' block4 = ''' from alibi_detect.datasets import fetch_cifar10c, corruption_types_cifar10c corruption = ['motion_blur'] X_corr, y_corr = fetch_cifar10c(corruption=corruption, severity=5, return_X_y=True) X_corr = X_corr.astype('float32') / 255 ''' block5 = ''' show(X_corr[0]) show(X_corr[1]) show(X_corr[2]) ''' block6 = ''' def predict(X): test_example=X.tolist() payload='{"instances":'+f"{test_example}"+' }' with open("payload.json","w") as f: f.write(payload) cmd=f"""curl -d @./payload.json \\ http://cifar10-classifier-default.{DEPLOY_NAMESPACE}:8000/v1/models/classifier/:predict \\ -H "Content-Type: application/json" """ run(cmd, shell=True) ''' block7 = ''' def get_drift_event_display_logs(): cmd=f"kubectl logs $(kubectl get pod -l app=event-display -o jsonpath='{{.items[0].metadata.name}}' -n {DEPLOY_NAMESPACE}) -n {DEPLOY_NAMESPACE}" ret = Popen(cmd, shell=True,stdout=PIPE) res = ret.stdout.read().decode("utf-8").split("\\n") data= [] for i in range(0,len(res)): if res[i] == 'Data,': j = json.loads(json.loads(res[i+1])) if "is_drift"in j["data"].keys(): data.append(j) if len(data) > 0: return data[-1] else: return None j = None for i in range(0,1000,50): X = X_corr[i:i+50] predict(X) print("Waiting for drift logs, sleeping") time.sleep(2) j = get_drift_event_display_logs() if j is not None: break print(j) print("Drift",j["data"]["is_drift"]==1) ''' block8 = ''' ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, block4, block5, block6, block7, block8, ) html_artifact = _kale_run_code(blocks) with open("/test_drift_detector.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('test_drift_detector') _kale_mlmd_utils.call("mark_execution_complete") setup_op = comp.func_to_container_op( setup, base_image='seldonio/jupyter-lab-alibi-kale:0.11') train_model_and_explainer_op = comp.func_to_container_op( train_model_and_explainer, base_image='seldonio/jupyter-lab-alibi-kale:0.11') deploy_model_op = comp.func_to_container_op( deploy_model, base_image='seldonio/jupyter-lab-alibi-kale:0.11') train_drift_detector_op = comp.func_to_container_op( train_drift_detector, base_image='seldonio/jupyter-lab-alibi-kale:0.11') train_outlier_detector_op = comp.func_to_container_op( train_outlier_detector, base_image='seldonio/jupyter-lab-alibi-kale:0.11') deploy_event_display_op = comp.func_to_container_op( deploy_event_display, base_image='seldonio/jupyter-lab-alibi-kale:0.11') deploy_outlier_detector_op = comp.func_to_container_op( deploy_outlier_detector, base_image='seldonio/jupyter-lab-alibi-kale:0.11') test_oulier_detection_op = comp.func_to_container_op( test_oulier_detection, base_image='seldonio/jupyter-lab-alibi-kale:0.11') deploy_drift_detector_op = comp.func_to_container_op( deploy_drift_detector, base_image='seldonio/jupyter-lab-alibi-kale:0.11') test_drift_detector_op = comp.func_to_container_op( test_drift_detector, base_image='seldonio/jupyter-lab-alibi-kale:0.11') @dsl.pipeline( name='seldon-e2e-cifar10-glv9p', description='Seldon CIFAR10 Example' ) def auto_generated_pipeline(CIFAR10_MODEL_PATH='tfserving/cifar10/model', DEPLOY_NAMESPACE='admin', DRIFT_MODEL_PATH='tfserving/cifar10/drift', EXPLAINER_MODEL_PATH='tfserving/cifar10/explainer', MINIO_ACCESS_KEY='minio', MINIO_HOST='minio-service.kubeflow:9000', MINIO_MODEL_BUCKET='seldon', MINIO_SECRET_KEY='minio123', OUTLIER_MODEL_PATH='tfserving/cifar10/outlier', TRAIN_DRIFT_DETECTOR='False', TRAIN_OUTLIER_DETECTOR='False'): pvolumes_dict = OrderedDict() volume_step_names = [] volume_name_parameters = [] marshal_vop = dsl.VolumeOp( name="kale-marshal-volume", resource_name="kale-marshal-pvc", storage_class="nfs-client", modes=dsl.VOLUME_MODE_RWM, size="1Gi" ) volume_step_names.append(marshal_vop.name) volume_name_parameters.append(marshal_vop.outputs["name"].full_name) pvolumes_dict['/marshal'] = marshal_vop.volume volume_step_names.sort() volume_name_parameters.sort() setup_task = setup_op(MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY)\ .add_pvolumes(pvolumes_dict)\ .after() setup_task.container.working_dir = "/home/jovyan" setup_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update({'setup': '/setup.html'}) setup_task.output_artifact_paths.update(output_artifacts) setup_task.add_pod_label("pipelines.kubeflow.org/metadata_written", "true") dep_names = setup_task.dependent_names + volume_step_names setup_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: setup_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) train_model_and_explainer_task = train_model_and_explainer_op(CIFAR10_MODEL_PATH, EXPLAINER_MODEL_PATH, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY)\ .add_pvolumes(pvolumes_dict)\ .after(setup_task) train_model_and_explainer_task.container.working_dir = "/home/jovyan" train_model_and_explainer_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update( {'train_model_and_explainer': '/train_model_and_explainer.html'}) train_model_and_explainer_task.output_artifact_paths.update( output_artifacts) train_model_and_explainer_task.add_pod_label( "pipelines.kubeflow.org/metadata_written", "true") dep_names = train_model_and_explainer_task.dependent_names + volume_step_names train_model_and_explainer_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: train_model_and_explainer_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) deploy_model_task = deploy_model_op(CIFAR10_MODEL_PATH, DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY)\ .add_pvolumes(pvolumes_dict)\ .after(train_model_and_explainer_task) deploy_model_task.container.working_dir = "/home/jovyan" deploy_model_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update({'deploy_model': '/deploy_model.html'}) deploy_model_task.output_artifact_paths.update(output_artifacts) deploy_model_task.add_pod_label( "pipelines.kubeflow.org/metadata_written", "true") dep_names = deploy_model_task.dependent_names + volume_step_names deploy_model_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: deploy_model_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) train_drift_detector_task = train_drift_detector_op(DRIFT_MODEL_PATH, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY)\ .add_pvolumes(pvolumes_dict)\ .after(train_model_and_explainer_task) train_drift_detector_task.container.working_dir = "/home/jovyan" train_drift_detector_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update( {'train_drift_detector': '/train_drift_detector.html'}) train_drift_detector_task.output_artifact_paths.update(output_artifacts) train_drift_detector_task.add_pod_label( "pipelines.kubeflow.org/metadata_written", "true") dep_names = train_drift_detector_task.dependent_names + volume_step_names train_drift_detector_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: train_drift_detector_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) train_outlier_detector_task = train_outlier_detector_op(MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY, OUTLIER_MODEL_PATH, TRAIN_OUTLIER_DETECTOR)\ .add_pvolumes(pvolumes_dict)\ .after(train_model_and_explainer_task) train_outlier_detector_task.container.working_dir = "/home/jovyan" train_outlier_detector_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update( {'train_outlier_detector': '/train_outlier_detector.html'}) train_outlier_detector_task.output_artifact_paths.update(output_artifacts) train_outlier_detector_task.add_pod_label( "pipelines.kubeflow.org/metadata_written", "true") dep_names = train_outlier_detector_task.dependent_names + volume_step_names train_outlier_detector_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: train_outlier_detector_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) deploy_event_display_task = deploy_event_display_op(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_SECRET_KEY)\ .add_pvolumes(pvolumes_dict)\ .after(train_drift_detector_task, train_outlier_detector_task, deploy_model_task) deploy_event_display_task.container.working_dir = "/home/jovyan" deploy_event_display_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update( {'deploy_event_display': '/deploy_event_display.html'}) deploy_event_display_task.output_artifact_paths.update(output_artifacts) deploy_event_display_task.add_pod_label( "pipelines.kubeflow.org/metadata_written", "true") dep_names = deploy_event_display_task.dependent_names + volume_step_names deploy_event_display_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: deploy_event_display_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) deploy_outlier_detector_task = deploy_outlier_detector_op(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY, OUTLIER_MODEL_PATH)\ .add_pvolumes(pvolumes_dict)\ .after(deploy_event_display_task) deploy_outlier_detector_task.container.working_dir = "/home/jovyan" deploy_outlier_detector_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update( {'deploy_outlier_detector': '/deploy_outlier_detector.html'}) deploy_outlier_detector_task.output_artifact_paths.update(output_artifacts) deploy_outlier_detector_task.add_pod_label( "pipelines.kubeflow.org/metadata_written", "true") dep_names = deploy_outlier_detector_task.dependent_names + volume_step_names deploy_outlier_detector_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: deploy_outlier_detector_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) test_oulier_detection_task = test_oulier_detection_op(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_SECRET_KEY)\ .add_pvolumes(pvolumes_dict)\ .after(deploy_outlier_detector_task) test_oulier_detection_task.container.working_dir = "/home/jovyan" test_oulier_detection_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update( {'test_oulier_detection': '/test_oulier_detection.html'}) test_oulier_detection_task.output_artifact_paths.update(output_artifacts) test_oulier_detection_task.add_pod_label( "pipelines.kubeflow.org/metadata_written", "true") dep_names = test_oulier_detection_task.dependent_names + volume_step_names test_oulier_detection_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: test_oulier_detection_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) deploy_drift_detector_task = deploy_drift_detector_op(DEPLOY_NAMESPACE, DRIFT_MODEL_PATH, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_MODEL_BUCKET, MINIO_SECRET_KEY)\ .add_pvolumes(pvolumes_dict)\ .after(test_oulier_detection_task) deploy_drift_detector_task.container.working_dir = "/home/jovyan" deploy_drift_detector_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update( {'deploy_drift_detector': '/deploy_drift_detector.html'}) deploy_drift_detector_task.output_artifact_paths.update(output_artifacts) deploy_drift_detector_task.add_pod_label( "pipelines.kubeflow.org/metadata_written", "true") dep_names = deploy_drift_detector_task.dependent_names + volume_step_names deploy_drift_detector_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: deploy_drift_detector_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) test_drift_detector_task = test_drift_detector_op(DEPLOY_NAMESPACE, MINIO_ACCESS_KEY, MINIO_HOST, MINIO_SECRET_KEY)\ .add_pvolumes(pvolumes_dict)\ .after(deploy_drift_detector_task) test_drift_detector_task.container.working_dir = "/home/jovyan" test_drift_detector_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update( {'test_drift_detector': '/test_drift_detector.html'}) test_drift_detector_task.output_artifact_paths.update(output_artifacts) test_drift_detector_task.add_pod_label( "pipelines.kubeflow.org/metadata_written", "true") dep_names = test_drift_detector_task.dependent_names + volume_step_names test_drift_detector_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: test_drift_detector_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) if __name__ == "__main__": pipeline_func = auto_generated_pipeline pipeline_filename = pipeline_func.__name__ + '.pipeline.tar.gz' import kfp.compiler as compiler compiler.Compiler().compile(pipeline_func, pipeline_filename) # Get or create an experiment and submit a pipeline run import kfp client = kfp.Client() experiment = client.create_experiment('seldon-e2e-cifar10') # Submit a pipeline run from kale.utils.kfp_utils import generate_run_name run_name = generate_run_name('seldon-e2e-cifar10-glv9p') run_result = client.run_pipeline( experiment.id, run_name, pipeline_filename, {})
37.259279
432
0.675464
65e83c298bc19d970f2f3315e8442311264e80b0
2,825
py
Python
catalyst/contrib/models/encoder/resnet.py
andrey-avdeev/catalyst
fd17aaba7775c99b7e2b1ce86e60aa8f2379acc3
[ "Apache-2.0" ]
1
2019-12-15T18:29:15.000Z
2019-12-15T18:29:15.000Z
catalyst/contrib/models/encoder/resnet.py
andrey-avdeev/catalyst
fd17aaba7775c99b7e2b1ce86e60aa8f2379acc3
[ "Apache-2.0" ]
null
null
null
catalyst/contrib/models/encoder/resnet.py
andrey-avdeev/catalyst
fd17aaba7775c99b7e2b1ce86e60aa8f2379acc3
[ "Apache-2.0" ]
1
2020-04-16T10:20:00.000Z
2020-04-16T10:20:00.000Z
from typing import Union # isort:skip from pathlib import Path import torch import torch.nn as nn import torchvision from catalyst import utils from catalyst.contrib.modules import Flatten from catalyst.contrib.registry import MODULES class ResnetEncoder(nn.Module): def __init__( self, arch: str = "resnet34", pretrained: bool = True, frozen: bool = True, pooling: str = None, pooling_kwargs: dict = None, cut_layers: int = 2, state_dict: Union[dict, str, Path] = None, ): """ Specifies an encoder for classification network Args: arch (str): Name for resnet. Have to be one of resnet18, resnet34, resnet50, resnet101, resnet152 pretrained (bool): If True, returns a model pre-trained on ImageNet frozen (bool): If frozen, sets requires_grad to False pooling (str): pooling pooling_kwargs (dict): params for pooling state_dict (Union[dict, str, Path]): Path to ``torch.Model`` or a dict containing parameters and persistent buffers. Examples: >>> encoder = ResnetEncoder( >>> arch="resnet18", >>> pretrained=False, >>> state_dict="/model/path/resnet18-5c106cde.pth" >>> ) """ super().__init__() resnet = torchvision.models.__dict__[arch](pretrained=pretrained) if state_dict is not None: if isinstance(state_dict, (Path, str)): state_dict = torch.load(str(state_dict)) resnet.load_state_dict(state_dict) modules = list(resnet.children())[:-cut_layers] # delete last layers if frozen: for module in modules: utils.set_requires_grad(module, requires_grad=False) if pooling is not None: pooling_kwargs = pooling_kwargs or {} pooling_layer_fn = MODULES.get(pooling) pooling_layer = pooling_layer_fn( in_features=resnet.fc.in_features, **pooling_kwargs) \ if "attn" in pooling.lower() \ else pooling_layer_fn(**pooling_kwargs) modules += [pooling_layer] if hasattr(pooling_layer, "out_features"): out_features = pooling_layer.out_features( in_features=resnet.fc.in_features ) else: out_features = None else: out_features = resnet.fc.in_features modules += [Flatten()] self.out_features = out_features self.encoder = nn.Sequential(*modules) def forward(self, image): """Extract the image feature vectors.""" features = self.encoder(image) return features
34.036145
79
0.587965
428aff44eb71fc3533446e292de15f75c9a74eb2
3,823
py
Python
src/dct/cli.py
jochem725/deepracer-camera-telemetry
e0ceb227cb937d5e502a6231c9b4ebde6927dc64
[ "MIT" ]
null
null
null
src/dct/cli.py
jochem725/deepracer-camera-telemetry
e0ceb227cb937d5e502a6231c9b4ebde6927dc64
[ "MIT" ]
null
null
null
src/dct/cli.py
jochem725/deepracer-camera-telemetry
e0ceb227cb937d5e502a6231c9b4ebde6927dc64
[ "MIT" ]
1
2021-10-02T17:27:33.000Z
2021-10-02T17:27:33.000Z
import click import requests import json import logging import sys import socket import os from dct.util.silverstone import DeepRacerCar from dct.camera.stream import DeepRacerMJPEGStream, StreamConsumer from dct.visualizations.base import BaseFrameVisualizer from dct.visualizations.hud import HudOverlay from dct.visualizations.gradcam import GradCamOverlay from dct.stream.broadcaster import Broadcaster from dct.stream.http import HTTPRequestHandler requests.packages.urllib3.disable_warnings() os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" root = logging.getLogger() root.setLevel(logging.DEBUG) vizlog = logging.getLogger("deepracer-viz") vizlog.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.INFO) formatter = logging.Formatter( "[%(levelname)s]\t%(asctime)s - %(name)s - %(filename)s - %(lineno)d - %(message)s" ) handler.setFormatter(formatter) vizlog.addHandler(handler) root.addHandler(handler) @click.group() @click.pass_context def cli(ctx): ctx.ensure_object(dict) # Add config to context with open( os.path.join(os.path.dirname(__file__), "..", "..", "config.json"), "r" ) as f: config = json.load(f) # Store in context so other commands can use. ctx.obj["CONFIG"] = config @cli.command() @click.pass_context def server(ctx): config = ctx.obj["CONFIG"] # Start the broadcasting server. requestHandler = HTTPRequestHandler(config["port"]) requestHandler.start() cars = [] for car in config["cars"]: car = DeepRacerCar( car["ip"], ssh_password=car["ssh_password"], name=car["name"] ) car.connect() cars.append(car) broadcasters = [] for i, car in enumerate(cars): stream = DeepRacerMJPEGStream( car, quality=config["stream_quality"], width=config["stream_width"], height=config["stream_height"], ) stream.start() # TODO: Hacky. streamconsumer = StreamConsumer() stream.consumers.append(streamconsumer) viz = BaseFrameVisualizer( streamconsumer, width=config["stream_width"], height=config["stream_height"], ) streamconsumer2 = StreamConsumer() stream.consumers.append(streamconsumer2) viz2 = BaseFrameVisualizer( streamconsumer2, width=config["stream_width"], height=config["stream_height"], ) viz2.add(HudOverlay(car)) streamconsumer3 = StreamConsumer() stream.consumers.append(streamconsumer3) viz3 = BaseFrameVisualizer( streamconsumer, width=config["stream_width"], height=config["stream_height"], ) viz3.add(GradCamOverlay(car)) viz3.add(HudOverlay(car)) # Add the broadcasters broadcasters.append(Broadcaster(viz, key="{}/live".format(i))) broadcasters.append(Broadcaster(viz2, key="{}/live_hud".format(i))) broadcasters.append(Broadcaster(viz3, key="{}/live_grad".format(i))) for broadcaster in broadcasters: broadcaster.start() requestHandler.addBroadcaster(broadcaster, key=broadcaster.key) logging.info("Output stream available: {}".format(broadcaster.key)) def quit(): # broadcaster.kill = True requestHandler.kill = True quitsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) quitsock.connect(("127.0.0.1", config["port"])) quitsock.close() sys.exit(1) try: while input() != "quit": continue quit() except KeyboardInterrupt: quit() except EOFError: try: quit() except KeyboardInterrupt: os._exit(0)
27.702899
87
0.644782
9629e4932c742a08741a3a472320c42f1f57c348
1,356
py
Python
__init__.py
devs-mycroft/skill-speak
587eb47c4e60ac62a225b2cafed38e634696032b
[ "Apache-2.0" ]
5
2018-11-14T19:31:11.000Z
2021-02-17T23:28:54.000Z
__init__.py
devs-mycroft/skill-speak
587eb47c4e60ac62a225b2cafed38e634696032b
[ "Apache-2.0" ]
9
2017-12-21T00:10:48.000Z
2022-02-22T05:52:40.000Z
__init__.py
devs-mycroft/skill-speak
587eb47c4e60ac62a225b2cafed38e634696032b
[ "Apache-2.0" ]
22
2017-05-02T22:53:50.000Z
2021-11-24T21:49:12.000Z
# Copyright 2016 Mycroft AI Inc. # # 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 re from os.path import dirname, join from adapt.intent import IntentBuilder from mycroft import MycroftSkill, intent_handler # TODO - Localization class SpeakSkill(MycroftSkill): @intent_handler(IntentBuilder("").require("Speak").require("Words")) def speak_back(self, message): """ Repeat the utterance back to the user. TODO: The method is very english centric and will need localization. """ # Remove everything up to the speak keyword and repeat that utterance = message.data.get('utterance') repeat = re.sub('^.*?' + message.data['Speak'], '', utterance) self.speak(repeat.strip()) def stop(self): pass def create_skill(): return SpeakSkill()
30.818182
74
0.693215
e716fa3f2eab14574e864c9101f4e6eece00c86a
2,853
py
Python
taurex/binning/simplebinner.py
rychallener/TauREx3_public
eb0eeeeca8f47e5e7d64d8d70b43a3af370b7677
[ "BSD-3-Clause" ]
10
2019-12-18T09:19:16.000Z
2021-06-21T11:02:06.000Z
taurex/binning/simplebinner.py
rychallener/TauREx3_public
eb0eeeeca8f47e5e7d64d8d70b43a3af370b7677
[ "BSD-3-Clause" ]
10
2020-03-24T18:02:15.000Z
2021-08-23T20:32:09.000Z
taurex/binning/simplebinner.py
rychallener/TauREx3_public
eb0eeeeca8f47e5e7d64d8d70b43a3af370b7677
[ "BSD-3-Clause" ]
8
2020-03-26T14:16:42.000Z
2021-12-18T22:11:25.000Z
from .binner import Binner from taurex.util import bindown from taurex.util.util import compute_bin_edges, wnwidth_to_wlwidth from taurex import OutputSize class SimpleBinner(Binner): """ Bins to a wavenumber grid given by ``wngrid``. The method places flux into the correct bins using histogramming methods. This is fast but can suffer as it assumes that there are no gaps in the wavenumber grid. This can cause weird results and may cause the flux to be higher in the boundary of points between two distinct regions (such as WFC3 + Spitzer) Parameters ---------- wngrid: :obj:`array` Wavenumber grid wngrid_width: :obj:`array`, optional Must have same shape as ``wngrid`` Full bin widths for each wavenumber grid point given in ``wngrid``. If not provided then this is automatically computed from ``wngrid``. """ def __init__(self, wngrid, wngrid_width=None): self._wngrid = wngrid self._wn_width = wngrid_width if self._wn_width is None: self._wn_width = compute_bin_edges(self._wngrid)[-1] def bindown(self, wngrid, spectrum, grid_width=None, error=None): """ Bins down spectrum. Parameters ---------- wngrid : :obj:`array` The wavenumber grid of the spectrum to be binned down. spectrum: :obj:`array` The spectra we wish to bin-down. Must be same shape as ``wngrid``. grid_width: :obj:`array`, optional Wavenumber grid full-widths for the spectrum to be binned down. Must be same shape as ``wngrid``. Optional. error: :obj:`array`, optional Associated errors or noise of the spectrum. Must be same shape as ``wngrid``.Optional parameter. Returns ------- binned_wngrid : :obj:`array` New wavenumber grid spectrum: :obj:`array` Binned spectrum. grid_width: :obj:`array` New grid-widths error: :obj:`array` or None Binned error if given else ``None`` """ return self._wngrid, bindown(wngrid, spectrum, self._wngrid), \ None, self._wn_width def generate_spectrum_output(self, model_output, output_size=OutputSize.heavy): output = super().generate_spectrum_output(model_output, output_size=output_size) output['binned_wngrid'] = self._wngrid output['binned_wlgrid'] = 10000/self._wngrid output['binned_wnwidth'] = self._wn_width output['binned_wlwidth'] = wnwidth_to_wlwidth(self._wngrid, self._wn_width) return output
31.351648
75
0.599019
61f2193d6c3963bcc4002919d59de6a4525e4e7b
3,104
py
Python
setup.py
gerrymanoim/distributed
ac35e0f8104baaccfb44f98b67a48ee359069316
[ "BSD-3-Clause" ]
3
2021-05-27T07:40:11.000Z
2021-05-27T07:40:16.000Z
setup.py
happyLeecz/DaskServerless
c1ddfe678fedc7f7ecb6eabb784b967f71a2054a
[ "BSD-3-Clause" ]
1
2019-04-25T14:13:48.000Z
2019-04-25T16:54:54.000Z
setup.py
happyLeecz/DaskServerless
c1ddfe678fedc7f7ecb6eabb784b967f71a2054a
[ "BSD-3-Clause" ]
2
2019-04-24T17:06:29.000Z
2020-09-02T10:48:07.000Z
#!/usr/bin/env python import os import sys from setuptools import find_packages, setup from setuptools.extension import Extension import versioneer requires = open("requirements.txt").read().strip().split("\n") setup_requires = [] install_requires = [] extras_require = {} for r in requires: if ";" in r: # requirements.txt conditional dependencies need to be reformatted for wheels # to the form: `'[extra_name]:condition' : ['requirements']` req, cond = r.split(";", 1) cond = ":" + cond cond_reqs = extras_require.setdefault(cond, []) cond_reqs.append(req) else: install_requires.append(r) cython_arg = None for i in range(len(sys.argv)): if sys.argv[i].startswith("--with-cython"): cython_arg = sys.argv[i] del sys.argv[i] break ext_modules = [] if cython_arg: try: import cython # noqa: F401 except ImportError: setup_requires.append("cython") profile = False try: _, param = cython_arg.split("=") profile = param == "profile" except ValueError: pass cyext_modules = [ Extension( "distributed.scheduler", sources=["distributed/scheduler.py"], ), ] for e in cyext_modules: e.cython_directives = { "annotation_typing": True, "binding": False, "embedsignature": True, "language_level": 3, "profile": profile, } ext_modules.extend(cyext_modules) setup( name="distributed", version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description="Distributed scheduler for Dask", url="https://distributed.dask.org", maintainer="Matthew Rocklin", maintainer_email="mrocklin@gmail.com", python_requires=">=3.7", license="BSD", package_data={ "": ["templates/index.html", "template.html"], "distributed": ["http/templates/*.html"], }, include_package_data=True, setup_requires=setup_requires, install_requires=install_requires, extras_require=extras_require, packages=find_packages(exclude=["*tests*"]), ext_modules=ext_modules, long_description=( open("README.rst").read() if os.path.exists("README.rst") else "" ), classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Topic :: Scientific/Engineering", "Topic :: System :: Distributed Computing", ], entry_points=""" [console_scripts] dask-ssh=distributed.cli.dask_ssh:go dask-scheduler=distributed.cli.dask_scheduler:go dask-worker=distributed.cli.dask_worker:go """, zip_safe=False, )
28.740741
85
0.616624
f022374a59090c7e70d1af21df023976e80004e5
1,360
py
Python
reviser/commands/sheller.py
rocketboosters/reviser
03ee5eadd35db78cf122e48fac4d48981518af11
[ "MIT" ]
null
null
null
reviser/commands/sheller.py
rocketboosters/reviser
03ee5eadd35db78cf122e48fac4d48981518af11
[ "MIT" ]
null
null
null
reviser/commands/sheller.py
rocketboosters/reviser
03ee5eadd35db78cf122e48fac4d48981518af11
[ "MIT" ]
null
null
null
""" Macro command to convert to interactive shell operation. This is a special command to use in run command groups/macros to start interactive command mode for the terminal. Useful when in scenarios where you wish to prefix an interactive session with commonly executed commands. For example, if you want to select certain targets with the select command as part of starting the shell, you could create a run command group/macro in your lambda.yaml that executes the select command and then executes the shell command. This would updated the selection and then with the shell command, start the shell in interactive mode. Without specifying the shell command here, the run command group/macro would just set a selection and then exit. """ import argparse import typing from reviser import interactivity def get_completions( completer: "interactivity.ShellCompleter", ) -> typing.List[str]: """Get shell auto-completes for this command.""" return [] def populate_subparser(parser: argparse.ArgumentParser): """Populate parser for this command.""" pass def run(ex: "interactivity.Execution") -> "interactivity.Execution": """Switch to an interactive shell.""" ex.shell.is_interactive = True return ex.finalize( status="SHELL", message="Switching to interactive shell execution.", echo=True, )
34.871795
87
0.754412
eecb24ca46a630491f547e61d79f7c2899b5a66d
379
py
Python
taxonomy/templatetags/pagination.py
vdejager/pipetaxon
2dcf2f4cf3fd9ca8677ba313c0191df45ccc3f77
[ "MIT" ]
18
2018-11-26T03:04:18.000Z
2021-05-12T16:25:27.000Z
taxonomy/templatetags/pagination.py
vdejager/pipetaxon
2dcf2f4cf3fd9ca8677ba313c0191df45ccc3f77
[ "MIT" ]
13
2018-11-26T17:41:41.000Z
2022-02-19T19:49:51.000Z
taxonomy/templatetags/pagination.py
vdejager/pipetaxon
2dcf2f4cf3fd9ca8677ba313c0191df45ccc3f77
[ "MIT" ]
3
2018-11-26T15:20:15.000Z
2020-11-27T07:26:17.000Z
from django import template register = template.Library() def pagination(value, offset): current_page_number = value.number lower = current_page_number - offset higher = current_page_number + offset if lower < 0: lower = 0 higher = offset + offset return "{0}:{1}".format(lower, higher) register.filter('pagination_offset', pagination)
19.947368
48
0.686016
9c194ae02cf369e888b212ddde338633a8277830
2,696
py
Python
test/test_LEB128.py
TrueBitFoundation/python-offchain
ecc1a68b50cddbc539110311916f1200a669eecd
[ "MIT" ]
2
2017-09-27T10:19:44.000Z
2018-01-02T06:10:23.000Z
test/test_LEB128.py
TrueBitFoundation/python-offchain
ecc1a68b50cddbc539110311916f1200a669eecd
[ "MIT" ]
1
2018-01-30T13:44:55.000Z
2018-01-30T13:44:55.000Z
test/test_LEB128.py
TrueBitFoundation/python-offchain
ecc1a68b50cddbc539110311916f1200a669eecd
[ "MIT" ]
1
2017-12-01T18:14:07.000Z
2017-12-01T18:14:07.000Z
import sys sys.path.append('../') from utils import * from binascii import hexlify vals = [-624485, -1, 0, 1, 624485] uResults = [None, None, bytes([0x00]), bytes([0x01]), bytes([0xE5, 0x8E, 0x26])] sResults = [bytes([0x9B, 0xF1, 0x59]), bytes([0x7F]), bytes([0x00]), bytes([0x01]), bytes([0xE5, 0x8E, 0x26])] success = Colors.green + "SUCCESS: " + Colors.ENDC fail = Colors.red + "FAIL: " + Colors.ENDC def test_unsigned_LEB128(): for idx, val in enumerate(vals): try: result = LEB128UnsignedEncode(val) if result != uResults[idx]: print(fail + "result from LEB128UnsignedEncode (%s) failed to " "provide correct output (%s)" % (hexlify(result), hexlify(uResults[idx]))) continue else: print(success + "result from LEB128UnsignedEncode is correct") res = LEB128UnsignedDecode(result) if res != val: print(fail + "result from LEB128UnsignedDecode (%d) failed to " "provide correct output (%d)" % (res, val)) else: print(success + "result from LEB128UnsignedDecode is correct") except: if val < 0: print(success + "%d properly identified as negative and threw " "exception" % val) else: print(fail + "%d could not be encoded properly") def test_signed_LEB128(): for idx, val in enumerate(vals): try: result = LEB128SignedEncode(val) if result != sResults[idx]: print(fail + "result from LEB128SignedEncode (%s) failed to " "provide correct output (%s)" % (hexlify(result), hexlify(sResults[idx]))) continue else: print(success + "result from LEB128SignedEncode is correct") res = LEB128SignedDecode(result) if res != val: print(fail + "result from LEB128SignedDecode (%d) failed to " "provide correct output (%d)" % (res, val)) else: print(success + "result from LEB128SignedDecode is correct") except: if val < 0: print(success + "%d properly identified as negative and threw " "exception" % val) else: print(fail + "%d could not be encoded properly") def main(): test_unsigned_LEB128() test_signed_LEB128() if __name__ == '__main__': main()
32.481928
79
0.517804
d4411fd37edf231ce67fb11f67770e8a78dbb302
223
py
Python
aio_statsd/utlis.py
AdamLeyshon/aiostatsd
4193e1e2674692ae76555a3fdc85d280d54a2102
[ "Apache-2.0" ]
null
null
null
aio_statsd/utlis.py
AdamLeyshon/aiostatsd
4193e1e2674692ae76555a3fdc85d280d54a2102
[ "Apache-2.0" ]
null
null
null
aio_statsd/utlis.py
AdamLeyshon/aiostatsd
4193e1e2674692ae76555a3fdc85d280d54a2102
[ "Apache-2.0" ]
null
null
null
import asyncio import sys __all__ = ["get_event_loop"] def get_event_loop() -> asyncio.AbstractEventLoop: if sys.version_info >= (3, 7): return asyncio.get_running_loop() return asyncio.get_event_loop()
18.583333
50
0.713004
defc699b1e9d62cdc8b04714a00cf1edf7dc65c6
596
py
Python
casemgmt/management/commands/oso_shell.py
saolsen/oso-casemgmt-django
05e7e1d54c0ca274341df3fa53c82b9735c377c6
[ "MIT" ]
3
2020-12-18T13:52:16.000Z
2021-02-17T17:05:28.000Z
casemgmt/management/commands/oso_shell.py
saolsen/oso-casemgmt-django
05e7e1d54c0ca274341df3fa53c82b9735c377c6
[ "MIT" ]
1
2021-04-13T18:58:17.000Z
2021-04-13T18:58:17.000Z
casemgmt/management/commands/oso_shell.py
saolsen/oso-casemgmt-django
05e7e1d54c0ca274341df3fa53c82b9735c377c6
[ "MIT" ]
2
2020-12-21T15:10:29.000Z
2021-02-17T19:22:05.000Z
import traceback from django.core.management.base import BaseCommand # Example: # python manage.py oso_shell class Command(BaseCommand): help = 'Start OSO Authorization Policy REPL Shell' def handle(self, *args, **options): from django_oso.oso import Oso while True: # Run OSO (which runs in loop too), and handle unhandled exceptions (KB Interrupt is already handled within # repl as a normal return. try: Oso.repl() return except Exception as e: traceback.print_exc()
28.380952
119
0.61745
662398fafbcd096657a8e0a87bcee81cd9e099df
1,408
py
Python
flowLossPlot.py
arfc/uiuc-arfc-2017-01
99e79735bc9ce977df4c4135e7b59bbb2a6b759c
[ "CC-BY-4.0" ]
null
null
null
flowLossPlot.py
arfc/uiuc-arfc-2017-01
99e79735bc9ce977df4c4135e7b59bbb2a6b759c
[ "CC-BY-4.0" ]
null
null
null
flowLossPlot.py
arfc/uiuc-arfc-2017-01
99e79735bc9ce977df4c4135e7b59bbb2a6b759c
[ "CC-BY-4.0" ]
null
null
null
#!/usr/bin/env python3 # makes a plot for the flow loss case # note: you need to comment out the header on the csv file import matplotlib.pyplot as pl from matplotlib import rc import numpy as np # directory with output data: outdir = ('/home/gav/projects/moltres/problems/' 'LOFA/') data = np.loadtxt(outdir+'out.csv', delimiter=',') # get colnames: with open(outdir+'out.csv') as fh: line1 = fh.readline().rstrip() colnames = line1[1:].split(sep=',') print("Found these data columns:") print(colnames) # maps colnames to column index colname2col = dict(zip(colnames, range(len(colnames)))) # latex rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica'], 'size': 20}) rc('text', usetex=True) pl.style.use('ggplot') # mwahaha, now people think i know R fig, ax = pl.subplots( figsize=(6,4)) ax.set_title('Power and salt flow velocity in core versus time') ax.set_xlabel('Time (s)') ax2 = ax.twinx() ax.set_ylabel('Salt flow velocity (cm/s)', color='b') ax2.set_ylabel('Average nuclear power (W/cm$^3$)', color='r') def flowRate(t): """ gives fixed flow rate as a function of time notice that it depends on pump coastdown time constant, so be sure to change that if needed. right now, it's set to 5s """ tau = 5.0 return 21.7 * np.exp(-t/tau) ax.plot(data[:,0], data[:,1], 'r-*') ax2.plot(data[:,0], flowRate(data[:,0]), 'b-*') fig.savefig('pumpFail.png')
31.288889
79
0.673295
35ecf8435c079fa59fa726fb6706894219e729f0
2,495
py
Python
grpcHandle/servicefunction/pieces_defects_process_service_function.py
dodoyuan/docker-airflow-datax
3fb37a34dd61b6694bf1845219f9392089424645
[ "Apache-2.0" ]
10
2018-12-01T20:15:00.000Z
2022-02-28T05:11:50.000Z
grpcHandle/servicefunction/pieces_defects_process_service_function.py
dodoyuan/docker-airflow-datax
3fb37a34dd61b6694bf1845219f9392089424645
[ "Apache-2.0" ]
null
null
null
grpcHandle/servicefunction/pieces_defects_process_service_function.py
dodoyuan/docker-airflow-datax
3fb37a34dd61b6694bf1845219f9392089424645
[ "Apache-2.0" ]
2
2020-10-12T09:37:54.000Z
2021-02-04T03:23:35.000Z
import settings import os from servicefunction.utils import get_format_time, write_file import subprocess log_file_dir = settings.AOI_LOG_DIR def exec_ftpdownloader_command(): pva_home = settings.PVA_HOME_PATH psa_home = settings.PSA_HOME_PATH oneday = settings.FTP_ONE_DAY days = settings.FTP_DAYS ftp_script_abs_path = settings.FTP_SCRIPT_ABS_PATH format_time = get_format_time() # os.path.join() if not os.path.exists(log_file_dir): os.makedirs(log_file_dir) file_name = format_time + '_ftp' cmd = 'python {script} --pva_home_path {pva} --psa_home_path {psa} --oneday {oneday} --days {days}'.\ format(script=ftp_script_abs_path, pva=pva_home, psa=psa_home, oneday=oneday, days=days) write_file(log_file_dir, cmd, file_name) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while p.poll() is None: out = p.stdout.readline() if out: write_file(log_file_dir, out, file_name) # print(p.returncode) if p.returncode == 0: return 'success' else: return 'failed' def exec_dataprocess_command(): main_script_abs_path = settings.MAIN_SCRIPT_ABS_PATH user = settings.MAIN_USER password = settings.MAIN_PASSWORD host = settings.MAIN_HOST port = settings.MIAN_PORT db = settings.MAIN_DB oneday = settings.MIAN_ONE_DAY days = settings.MIAN_DAYS homedir = settings.MAIN_HOME_DIR format_time = get_format_time() # filepath = os.path.join(LOG_ROOT, log_file_dir) if not os.path.exists(log_file_dir): os.makedirs(log_file_dir) file_name = format_time + '_main.log' cmd = 'python {script} --user {user} --password {passwd} --host {host} --port {port} --mysqldb {db} --oneday ' \ '{oneday} --days {days} --home_dir {homedir}'.format(script=main_script_abs_path, user=user, passwd=password, host=host, port=port, db=db, oneday=oneday, days=days, homedir=homedir) write_file(log_file_dir, cmd, file_name) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while p.poll() is None: out = p.stdout.readline() if out: write_file(log_file_dir, out, file_name) # print(p.returncode) if p.returncode == 0: return 'success' else: return 'failed'
35.642857
119
0.652505
4b93c7e6e153b8710df931b4d25c1cf600450f38
3,143
py
Python
gonzo/connectors/twitter/tests.py
paulcwatts/1hph
407337955121c3f59b4621acb392e6c23b57ae8e
[ "BSD-3-Clause" ]
1
2016-10-03T05:29:12.000Z
2016-10-03T05:29:12.000Z
gonzo/connectors/twitter/tests.py
paulcwatts/1hph
407337955121c3f59b4621acb392e6c23b57ae8e
[ "BSD-3-Clause" ]
null
null
null
gonzo/connectors/twitter/tests.py
paulcwatts/1hph
407337955121c3f59b4621acb392e6c23b57ae8e
[ "BSD-3-Clause" ]
null
null
null
from urlparse import urlparse from django.contrib.auth.models import User from django.test import TestCase from django.test.client import Client from gonzo.connectors import twitter from gonzo.connectors.twitter.models import TwitterProfile class TwitterTest(TestCase): def setUp(self): self.is_enabled = twitter.is_enabled() self.is_self_enabled = twitter.is_self_enabled() self.user = User.objects.create_user('testdude', '', 'testpassword') self.enabled_user = User.objects.create_user('enabled', '', 'enabled') twitter_profile = TwitterProfile.objects.create(user=self.enabled_user, screen_name='1hph', oauth_token='xxxx', oauth_secret='yyyy') def test_0_auth(self): try: self.assert_(twitter.get_auth()) self.assertRaises(twitter.UserNotAuthorized, lambda: twitter.get_auth_for_user(self.user)) self.assert_(twitter.get_auth_for_user(self.enabled_user)) except twitter.NotEnabled: self.assert_(not self.is_enabled) def test_1_self(self): try: self.assert_(twitter.get_auth_for_self()) self.assert_(twitter.get_api_for_self()) except twitter.SelfNotEnabled: self.assert_(not self.is_self_enabled) def test_3_get_auth_url(self): try: auth = twitter.get_auth() urlstr = auth.get_authorization_url() # Ensure it's "api.twitter.com" and that it's secured url = urlparse(urlstr) self.assertEquals(url.scheme, "https") self.assertEquals(url.hostname, "api.twitter.com") except twitter.NotEnabled: assert(not self.is_enabled) def test_4_api(self): try: self.assert_(twitter.get_api()) self.assertRaises(twitter.UserNotAuthorized, lambda: twitter.get_api_for_user(self.user)) self.assert_(twitter.get_api_for_user(self.enabled_user)) except twitter.NotEnabled: self.assert_(not self.is_enabled) def test_5_fill_profile(self): # It's easiest to test with a public profile. auth = twitter.get_auth_for_self() user = self.enabled_user profile = twitter.fill_profile(user, auth=auth) self.assert_(profile) self.assertEquals(profile.user_location, "Seattle, WA") self.assertEquals(user.first_name, "One Hour Photo") self.assertEquals(user.last_name, "Hunt!") self.assert_(profile.photo) self.assert_(profile.photo.url) self.assert_(profile.photo_width > 0) self.assert_(profile.photo_height > 0) def test_6_backend(self): c = Client() self.assert_(c.login(screen_name='1hph', secret='yyyy')) c.logout() self.assert_(not c.login(screen_name='1hph', secret='xxxx')) self.assert_(not c.login(screen_name='testdude', secret='yyyyy'))
40.294872
79
0.617881
c1c09f4e739f0a3ddd7390cc4e21dd606601cadb
4,455
py
Python
tests/experimental/test_implementations.py
rlbellaire/hydra-zen
e6832542162e6eb252112d1f4990b255423eef7f
[ "MIT" ]
null
null
null
tests/experimental/test_implementations.py
rlbellaire/hydra-zen
e6832542162e6eb252112d1f4990b255423eef7f
[ "MIT" ]
null
null
null
tests/experimental/test_implementations.py
rlbellaire/hydra-zen
e6832542162e6eb252112d1f4990b255423eef7f
[ "MIT" ]
null
null
null
# Copyright (c) 2021 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT from pathlib import Path import pytest from hydra import compose, initialize from hydra.core.config_store import ConfigStore from omegaconf.omegaconf import OmegaConf from hydra_zen import builds, instantiate from hydra_zen.experimental import hydra_multirun, hydra_run from hydra_zen.experimental._implementations import _store_config @pytest.mark.parametrize("as_dataclass", [True, False]) @pytest.mark.parametrize("as_dictconfig", [True, False]) def test_store_config(as_dataclass, as_dictconfig): cfg = builds(dict, a=1, b=1) if not as_dataclass: cfg = dict(f=cfg) if as_dictconfig: cfg = OmegaConf.create(cfg) cn = _store_config(cfg) cs = ConfigStore.instance() key = cn + ".yaml" assert key in cs.repo assert cs.repo[key].node == OmegaConf.create(cfg) @pytest.mark.usefixtures("cleandir") @pytest.mark.parametrize("runmode", [hydra_run, hydra_multirun]) @pytest.mark.parametrize("as_dataclass", [True, False]) @pytest.mark.parametrize( "as_dictconfig, with_hydra", [(True, True), (True, False), (False, False)] ) def test_hydra_run_config_type( runmode, as_dataclass, as_dictconfig, with_hydra, ): if not as_dataclass: cfg = dict(a=1, b=1) else: cfg = builds(dict, a=1, b=1) if as_dictconfig: if not with_hydra: cfg = OmegaConf.create(cfg) else: cn = _store_config(cfg) with initialize(config_path=None): cfg = compose(config_name=cn) job = runmode(cfg, task_function=instantiate) if isinstance(job, list): job = job[0][0] assert job.return_value == {"a": 1, "b": 1} @pytest.mark.usefixtures("cleandir") @pytest.mark.parametrize( "overrides", [None, [], ["hydra.run.dir=test_hydra_overrided"]] ) @pytest.mark.parametrize("config_dir", [Path.cwd(), None]) @pytest.mark.parametrize("with_log_configuration", [False, True]) def test_hydra_run_job( overrides, config_dir, with_log_configuration, ): cfg = dict(a=1, b=1) override_exists = overrides and len(overrides) > 1 job = hydra_run( cfg, task_function=instantiate, overrides=overrides, config_dir=config_dir, with_log_configuration=with_log_configuration, ) assert job.return_value == {"a": 1, "b": 1} if override_exists == 1: assert Path("test_hydra_overrided").exists() @pytest.mark.usefixtures("cleandir") @pytest.mark.parametrize( "overrides", [None, [], ["hydra.sweep.dir=test_hydra_overrided"]] ) @pytest.mark.parametrize("multirun_overrides", [None, ["a=1,2"]]) @pytest.mark.parametrize("config_dir", [Path.cwd(), None]) @pytest.mark.parametrize("with_log_configuration", [False, True]) def test_hydra_multirun( overrides, multirun_overrides, config_dir, with_log_configuration, ): cfg = dict(a=1, b=1) override_exists = overrides and len(overrides) > 1 _overrides = overrides if multirun_overrides is not None: _overrides = ( multirun_overrides if overrides is None else (overrides + multirun_overrides) ) job = hydra_multirun( cfg, task_function=instantiate, overrides=_overrides, config_dir=config_dir, with_log_configuration=with_log_configuration, ) for i, j in enumerate(job[0]): assert j.return_value == {"a": i + 1, "b": 1} if override_exists == 1: assert Path("test_hydra_overrided").exists() @pytest.mark.usefixtures("cleandir") @pytest.mark.parametrize( "overrides", [["hydra/launcher=submitit_local"]], ) def test_hydra_multirun_plugin(overrides): try: from hydra_plugins.hydra_submitit_launcher.submitit_launcher import ( BaseSubmititLauncher, ) except ImportError: pytest.skip("Submitit plugin not available") return cfg = builds(dict, a=1, b=1) multirun_overrides = ["a=1,2"] _overrides = ( multirun_overrides if overrides is None else overrides + multirun_overrides ) job = hydra_multirun(cfg, task_function=instantiate, overrides=_overrides) for i, j in enumerate(job[0]): submitit_folder = Path(j.working_dir).parent / ".submitit" assert submitit_folder.exists() assert j.return_value == {"a": i + 1, "b": 1}
28.557692
83
0.670258
9016d2f9eca64e4fad44ac1c09e6b7676671e4e4
4,046
py
Python
src/python/pants/engine/selectors.py
sammy-1234/pants
889016952a248cf229c78c014d9f6c95422d98b8
[ "Apache-2.0" ]
1
2020-08-26T03:30:31.000Z
2020-08-26T03:30:31.000Z
src/python/pants/engine/selectors.py
sammy-1234/pants
889016952a248cf229c78c014d9f6c95422d98b8
[ "Apache-2.0" ]
1
2021-09-02T14:16:37.000Z
2021-09-02T14:16:37.000Z
src/python/pants/engine/selectors.py
sammy-1234/pants
889016952a248cf229c78c014d9f6c95422d98b8
[ "Apache-2.0" ]
null
null
null
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import ast from pants.util.objects import SubclassesOf, TypeConstraint, datatype _type_field = SubclassesOf(type) class Get(datatype([ ('product', _type_field), ('subject_declared_type', _type_field), 'subject', ])): """Experimental synchronous generator API. May be called equivalently as either: # verbose form: Get(product_type, subject_declared_type, subject) # shorthand form: Get(product_type, subject_type(subject)) """ @staticmethod def extract_constraints(call_node): """Parses a `Get(..)` call in one of its two legal forms to return its type constraints. :param call_node: An `ast.Call` node representing a call to `Get(..)`. :return: A tuple of product type id and subject type id. """ def render_args(): return ', '.join( # Dump the Name's id to simplify output when available, falling back to the name of the # node's class. getattr(a, 'id', type(a).__name__) for a in call_node.args) if len(call_node.args) == 2: product_type, subject_constructor = call_node.args if not isinstance(product_type, ast.Name) or not isinstance(subject_constructor, ast.Call): # TODO(#7114): describe what types of objects are expected in the get call, not just the # argument names. After #7114 this will be easier because they will just be types! raise ValueError( 'Two arg form of {} expected (product_type, subject_type(subject)), but ' 'got: ({})'.format(Get.__name__, render_args())) return (product_type.id, subject_constructor.func.id) elif len(call_node.args) == 3: product_type, subject_declared_type, _ = call_node.args if not isinstance(product_type, ast.Name) or not isinstance(subject_declared_type, ast.Name): raise ValueError( 'Three arg form of {} expected (product_type, subject_declared_type, subject), but ' 'got: ({})'.format(Get.__name__, render_args())) return (product_type.id, subject_declared_type.id) else: raise ValueError('Invalid {}; expected either two or three args, but ' 'got: ({})'.format(Get.__name__, render_args())) @classmethod def create_statically_for_rule_graph(cls, product_type, subject_type): """Construct a `Get` with a None value. This method is used to help make it explicit which `Get` instances are parsed from @rule bodies and which are instantiated during rule execution. """ return cls(product_type, subject_type, None) def __new__(cls, *args): # TODO(#7114): Use datatype type checking for these fields! We can wait until after #7114, when # we can just check that they are types. if len(args) == 2: product, subject = args if isinstance(subject, (type, TypeConstraint)): raise TypeError("""\ The two-argument form of Get does not accept a type as its second argument. args were: Get({args!r}) Get.create_statically_for_rule_graph() should be used to generate a Get() for the `input_gets` field of a rule. If you are using a `yield Get(...)` in a rule and a type was intended, use the 3-argument version: Get({product!r}, {subject_type!r}, {subject!r}) """.format(args=args, product=product, subject_type=type(subject), subject=subject)) subject_declared_type = type(subject) elif len(args) == 3: product, subject_declared_type, subject = args else: raise ValueError('Expected either two or three arguments to {}; got {}.' .format(Get.__name__, args)) return super().__new__(cls, product, subject_declared_type, subject) class Params(datatype([('params', tuple)])): """A set of values with distinct types. Distinct types are enforced at consumption time by the rust type of the same name. """ def __new__(cls, *args): return super().__new__(cls, tuple(args))
39.666667
99
0.681167
886b821e869b0ede85173417b484ddeb8d42934b
1,475
py
Python
server/config/settings/components/paths.py
NikitaGrishchenko/csp-tender-hack-server
56055f51bf472f0f1e56b419a48d993cc91e0f3a
[ "MIT" ]
null
null
null
server/config/settings/components/paths.py
NikitaGrishchenko/csp-tender-hack-server
56055f51bf472f0f1e56b419a48d993cc91e0f3a
[ "MIT" ]
null
null
null
server/config/settings/components/paths.py
NikitaGrishchenko/csp-tender-hack-server
56055f51bf472f0f1e56b419a48d993cc91e0f3a
[ "MIT" ]
null
null
null
"""Paths settings""" import os # Base CONFIG_DIR = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ) BACKEND_DIR = os.path.dirname(CONFIG_DIR) PROJECT_DIR = os.path.dirname(BACKEND_DIR) ENV_FILE = os.path.join(PROJECT_DIR, ".env") ENV_FILE_EXAMPLE = os.path.join(PROJECT_DIR, ".env.example") # Nginx PUBLIC_DIR = os.path.join(PROJECT_DIR, "public") PRIVATE_DIR = os.path.join(PROJECT_DIR, "private") PUBLIC_MEDIA_DIR = os.path.join(PUBLIC_DIR, "media") PUBLIC_STATIC_DIR = os.path.join(PUBLIC_DIR, "static") # Backend LOGS_DIR = os.path.join(PRIVATE_DIR, "logs") APPS_DIR = os.path.join(BACKEND_DIR, "apps") FIXTURES_DIR = os.path.join(BACKEND_DIR, "fixtures") LOG_FILE = os.path.join(LOGS_DIR, "django-error.log") DEV_DATABASE_FILE = os.path.join(PRIVATE_DIR, "db.sqlite3") TEST_DATABASE_FILE = os.path.join(PRIVATE_DIR, "test_db.sqlite3") FIXTURE_DIRS = [ FIXTURES_DIR, ] # Apps templates APP_TEMPLATES = os.path.join(APPS_DIR, "core", "utils", "app_templates") API_APP_TEMPLATE = os.path.join(APP_TEMPLATES, "api.zip") CORE_APP_TEMPLATE = os.path.join(APP_TEMPLATES, "core.zip") DEFAULT_APP_TEMPLATE = os.path.join(APP_TEMPLATES, "default.zip") # Frontend STATIC_DIR = os.path.join(BACKEND_DIR, "static") DIST_DIR = os.path.join(STATIC_DIR, "dist") TEMPLATES_DIR = os.path.join(BACKEND_DIR, "templates") WEBPACK_STATS_FILE = os.path.join(DIST_DIR, "webpack-stats.json") # Locale LOCALE_DIR = os.path.join(PRIVATE_DIR, "locale")
32.777778
72
0.753898
17a294fca2a2f7688f941043a30db342d62dd39e
3,179
py
Python
examples/android/tflite_convertor/tfltransfer/optimizers/adam.py
g-pichler/flower
e455cdc3678921ece960287a0e1ae5123500c948
[ "Apache-2.0" ]
null
null
null
examples/android/tflite_convertor/tfltransfer/optimizers/adam.py
g-pichler/flower
e455cdc3678921ece960287a0e1ae5123500c948
[ "Apache-2.0" ]
null
null
null
examples/android/tflite_convertor/tfltransfer/optimizers/adam.py
g-pichler/flower
e455cdc3678921ece960287a0e1ae5123500c948
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 The TensorFlow Authors. 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. """Adam optimizer implementation for transfer learning models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import tensorflow.compat.v1 as tfv1 class Adam(object): """Adam optimizer configuration for transfer learning converter.""" def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, eps=1e-8): self._learning_rate = learning_rate self._beta1 = beta1 self._beta2 = beta2 self._eps = eps def generate_optimizer_model(self, parameter_shapes): """Generates a TFLite model that represents an optimizer step. The generated model inputs are current values of the trainable model parameters, followed by their gradients, and then by the current mutable optimizer state. The generated model outputs are the new values of the trainable parameters, followed by the updated mutable optimizer state. Args: parameter_shapes: list of model parameter shapes. Returns: TFLite optimizer model. """ with tfv1.Session(graph=tf.Graph()) as sess: current_values = [ tfv1.placeholder(tf.float32, shape) for shape in parameter_shapes ] gradients = [ tfv1.placeholder(tf.float32, shape) for shape in parameter_shapes ] ms = [tfv1.placeholder(tf.float32, shape) for shape in parameter_shapes] vs = [tfv1.placeholder(tf.float32, shape) for shape in parameter_shapes] step = tfv1.placeholder(tf.float32, ()) new_values = [] new_ms = [] new_vs = [] for cur_param, grad, m, v in zip(current_values, gradients, ms, vs): m = (1 - self._beta1) * grad + self._beta1 * m v = (1 - self._beta2) * (grad**2) + self._beta2 * v mhat = m / (1 - self._beta1 ** (step + 1)) vhat = v / (1 - self._beta2 ** (step + 1)) new_param = cur_param - ( self._learning_rate * mhat / (tf.sqrt(vhat) + self._eps) ) new_values.append(new_param) new_ms.append(m) new_vs.append(v) converter = tfv1.lite.TFLiteConverter.from_session( sess, current_values + gradients + ms + vs + [step], new_values + new_ms + new_vs + [step + 1], ) return converter.convert()
39.246914
84
0.622837
7277cd3e772077b247bbacdecd6e9c2fc12d740c
3,082
py
Python
electroncash/version.py
damascene/Electron-Cash-SLP
3819046ecbd585aa8f5fac1c58550046dd027266
[ "MIT" ]
53
2019-01-14T17:49:47.000Z
2022-03-29T13:51:43.000Z
electroncash/version.py
damascene/Electron-Cash-SLP
3819046ecbd585aa8f5fac1c58550046dd027266
[ "MIT" ]
186
2019-01-10T17:33:15.000Z
2022-02-01T02:14:41.000Z
electroncash/version.py
damascene/Electron-Cash-SLP
3819046ecbd585aa8f5fac1c58550046dd027266
[ "MIT" ]
54
2019-01-23T21:47:10.000Z
2022-01-31T20:44:53.000Z
PACKAGE_VERSION = '3.6.6' # version of the client package, this is used by update_checker.py PRE_RELEASE_TAG = '3.6.7-dev6' # title bar tag used for pre-releases, doesn't affect update_checker.py PROTOCOL_VERSION = '1.4' # protocol version requested EXTENSIONS = { 'SLP': "1" } # The hash of the Electrum mnemonic seed must begin with this SEED_PREFIX = '01' # Standard wallet, Electrum seed def seed_prefix(seed_type): assert seed_type in ('standard', 'electrum') return SEED_PREFIX import re _RX_NORMALIZER = re.compile(r'(\.0+)*$') _RX_VARIANT_TOKEN_PARSE = re.compile(r'^(\d+)(.+)$') def get_extensions(): extension_string = '' for extension in EXTENSIONS: extension_string = ' ' + extension + '/' + EXTENSIONS[extension] return extension_string def normalize_version(v): """Used for PROTOCOL_VERSION normalization, e.g '1.4.0' -> (1,4) """ return tuple(int(x) for x in _RX_NORMALIZER.sub('', v.strip()).split(".")) def parse_package_version(pvstr): """ Basically returns a tuple of the normalized version plus the 'variant' string at the end. Eg '3.3.0' -> (3, 3, ''), '3.2.2CS' -> (3, 2, 2, 'CS'), etc. Some more examples: '3.3.5CS' -> (3, 3, 5, 'CS') '3.4.5_iOS' -> (3, 4, 5, '_iOS') '3.3.5' -> (3, 3, 5, '') '3.3' -> (3, 3, '') '3.3.0' -> (3, 3, '') ' 3.2.2.0 ILikeSpaces ' -> (3, 2, 2, 'ILikeSpaces') Note how 0 fields at the end of the version get normalized with the 0 lopped off: '3.3.0' -> (3, 3, '') '3.5.0.0.0' -> (3, 5, '') '3.5.0.0.0_iOS' -> (3, 5, '_iOS') ... and, finally: The last element is *always* going to be present as a string, the 'variant'. The 'variant' will be the empty string '' if this is the default Electron Cash. If you don't like this heterogeneity of types in a tuple, take the retVal[:-1] slice of the array to toss it (or just use normalize_version above). """ def raise_(e=None): exc = ValueError('Failed to parse package version for: "{}"'.format(pvstr)) if e: raise exc from e else: raise exc toks = [x.strip() for x in pvstr.split(".")] if not toks: raise_() if toks[-1].isdigit(): # Missing 'variant' at end.. add the default '' variant. toks.append('') else: # had 'variant' at end, parse it. m = _RX_VARIANT_TOKEN_PARSE.match(toks[-1]) if m: # pop off end and... toks[-1:] = [m.group(1), # add the digit portion back (note it's still a str at this point) m.group(2).strip()] # add the leftovers as the actual variant else: raise_() try: # make sure everything but the last element is an int. toks[:-1] = [int(x) for x in toks[:-1]] except ValueError as e: raise_(e) # .. and.. finally: Normalize it! (lopping off zeros at the end) toks[:-1] = normalize_version('.'.join(str(t) for t in toks[:-1])) return tuple(toks)
39.012658
103
0.580143
99219709e7d369c4a5f2446fc74d84a7b5bd4026
1,412
py
Python
things2/MusicXML/app.py
mvasilkov/scrapheap
53e30b88879ab8e4d80867b0ec7fa631ce46e55e
[ "MIT" ]
null
null
null
things2/MusicXML/app.py
mvasilkov/scrapheap
53e30b88879ab8e4d80867b0ec7fa631ce46e55e
[ "MIT" ]
null
null
null
things2/MusicXML/app.py
mvasilkov/scrapheap
53e30b88879ab8e4d80867b0ec7fa631ce46e55e
[ "MIT" ]
null
null
null
from functools import cmp_to_key from math import floor from magenta.music import constants from magenta.music.musicxml_parser import Tempo from magenta.music.musicxml_reader import musicxml_file_to_sequence_proto def _parse(self): self.qpm = constants.DEFAULT_QUARTERS_PER_MINUTE self.time_position = self.state.time_position Tempo._parse = _parse TEMPO_MUL = 120 / 115 track = musicxml_file_to_sequence_proto('a.xml') @cmp_to_key def compare_notes(a, b): if a.start_time == b.start_time: return b.pitch - a.pitch return a.start_time - b.start_time out = open('out.js', 'w', encoding='utf-8') print('function play(n) {', file=out) print(' switch(n) {', file=out) # for a in track.notes: # call = ( # f' playNote({a.pitch}, {a.start_time}, {a.end_time})' # ) # {a.numerator}/{a.denominator} # print(call, file=out) bars = {} for a in track.notes: n = floor(a.start_time) if n in bars: bars[n].append(a) else: bars[n] = [a] for n in sorted(bars.keys()): print(f' case {n}: // bar {n + 1}', file=out) for a in sorted(bars[n], key=compare_notes): call = ( f' playNote({a.pitch}, n + {a.start_time - n}, n + {a.end_time - n})' ) # {a.numerator}/{a.denominator} print(call, file=out) print(' break', file=out) print(' }', file=out) print('}', file=out)
24.344828
88
0.624646
9879c2c06585ca3949d518269fa79e91f022c684
544
py
Python
backend/innovations/models.py
Yandjatg/ragproject
36acdd5a8d2f9593ca5b7da272346bddba8fa9bd
[ "MIT" ]
null
null
null
backend/innovations/models.py
Yandjatg/ragproject
36acdd5a8d2f9593ca5b7da272346bddba8fa9bd
[ "MIT" ]
null
null
null
backend/innovations/models.py
Yandjatg/ragproject
36acdd5a8d2f9593ca5b7da272346bddba8fa9bd
[ "MIT" ]
null
null
null
from django.db import models # Create your models here. class Innovation(models.Model): image = models.ImageField(max_length=1000) title = models.CharField(max_length=100) description = models.TextField() def get_image(self): return self.image def __str__(self): return self.image def get_title(self): return self.title def __str__(self): return self.title def get_description(self): return self.description def __str__(self): return self.description
19.428571
46
0.665441
5afff0d51d55ea5a77e9fa866cfbd85b6718a5aa
2,553
py
Python
workflow/utils_link_pred.py
skojaku/residual2vec
ea10caae3c2671953fbc295358040baa36ee1547
[ "MIT" ]
2
2022-01-20T18:03:11.000Z
2022-03-04T08:21:42.000Z
workflow/utils_link_pred.py
skojaku/residual2vec
ea10caae3c2671953fbc295358040baa36ee1547
[ "MIT" ]
null
null
null
workflow/utils_link_pred.py
skojaku/residual2vec
ea10caae3c2671953fbc295358040baa36ee1547
[ "MIT" ]
null
null
null
import numpy as np from scipy import sparse def fit_glove_bias(A, emb): N = A.shape[0] row_sum = np.array(A.sum(axis=1)).reshape(-1).astype(float) col_sum = np.array(A.sum(axis=0)).reshape(-1).astype(float) emb_sum = np.array(emb @ np.array(np.sum(emb, axis=0)).reshape((-1, 1))).reshape(-1) row_sum -= emb_sum col_sum -= emb_sum a = np.zeros(N) b = np.zeros(N) adam_a = ADAM() adam_b = ADAM() for it in range(1000): grad_a = row_sum - np.sum(b) * a grad_b = col_sum - np.sum(a) * b anew = adam_a.update(a, grad_a, 0) bnew = adam_b.update(b, grad_b, 0) if it % 20 == 0: dif = np.mean(np.abs(a - anew) + np.abs(b - bnew)) / 2 dif /= np.maximum(np.mean(np.abs(a) + np.abs(b)) / 2, 1e-8) if dif < 1e-2: break a = anew.copy() b = bnew.copy() return a, b class ADAM: def __init__(self): self.beta1 = 0.9 self.beta2 = 0.999 self.eta = 0.001 self.t = 0 self.mt = None self.vt = None self.eps = 1e-8 def update(self, theta, grad, lasso_penalty, positiveConstraint=False): """Ascending.""" if self.mt is None: self.mt = np.zeros(grad.shape) self.vt = np.zeros(grad.shape) self.t = self.t + 1 self.mt = self.beta1 * self.mt + (1 - self.beta1) * grad self.vt = self.beta2 * self.vt + (1 - self.beta2) * np.multiply(grad, grad) mthat = self.mt / (1 - np.power(self.beta1, self.t)) vthat = self.vt / (1 - np.power(self.beta2, self.t)) new_grad = mthat / (np.sqrt(vthat) + self.eps) return self._prox( theta + self.eta * new_grad, lasso_penalty * self.eta, positiveConstraint ) def _prox(self, x, lam, positiveConstraint): """Soft thresholding operator. Parameters ---------- x : float Variable. lam : float Lasso penalty. Returns ------- y : float Thresholded value of x. """ if positiveConstraint: b = ((lam) > 0).astype(int) return np.multiply(b, np.maximum(x - lam, np.zeros(x.shape))) + np.multiply( 1 - b, np.multiply(np.sign(x), np.maximum(np.abs(x) - lam, np.zeros(x.shape))), ) else: return np.multiply( np.sign(x), np.maximum(np.abs(x) - lam, np.zeros(x.shape)) )
27.159574
88
0.50803
8cf5739399037582786f7c3654f9b970d97da878
1,107
py
Python
models/problem_3c_unscaled.py
taoyilee/ml_final_project
0ac5ee3938d70e9ffcae8e186e0ef1a621391980
[ "Unlicense" ]
null
null
null
models/problem_3c_unscaled.py
taoyilee/ml_final_project
0ac5ee3938d70e9ffcae8e186e0ef1a621391980
[ "Unlicense" ]
null
null
null
models/problem_3c_unscaled.py
taoyilee/ml_final_project
0ac5ee3938d70e9ffcae8e186e0ef1a621391980
[ "Unlicense" ]
null
null
null
import numpy as np import pickle from homework4.problem_3 import sample_train_knn if __name__ == "__main__": X = np.genfromtxt('data/X_train.txt', delimiter=None) Y = np.genfromtxt('data/Y_train.txt', delimiter=None)[:, np.newaxis] raw_data = np.concatenate((X, Y), axis=1) trn_p = 20 dev_p = 5 resamping = 10 k = list(range(1, 50, 2)) print(k) alpha = np.linspace(0, 5, len(k)) alpha = alpha.round(2) print(alpha) training_auc = np.zeros((resamping, len(alpha), len(k)), dtype=float) validating_auc = np.zeros((resamping, len(alpha), len(k)), dtype=float) for i in range(resamping): for j, alphai in enumerate(alpha): training_auc[i, j], validating_auc[i, j] = sample_train_knn(k, raw_data, trn_p, dev_p, rescale=False, alpha=alphai) with open(f"learners/training_auc_3c_unscaled.pickle", "wb") as f: pickle.dump(training_auc, f) with open(f"learners/validating_auc_3c_unscaled.pickle", "wb") as f: pickle.dump(validating_auc, f)
36.9
113
0.620596
6f962ae4dfec841c5e2e19e5dc5acc216ce3e30b
2,264
py
Python
internal/notes/builtin-SAVE/packages/py-pyflakes/package.py
HPCToolkit/hpctest
5ff4455582bf39e75530a31badcf6142081b386b
[ "BSD-3-Clause" ]
1
2019-01-17T20:07:19.000Z
2019-01-17T20:07:19.000Z
internal/notes/builtin-SAVE/packages/py-pyflakes/package.py
HPCToolkit/hpctest
5ff4455582bf39e75530a31badcf6142081b386b
[ "BSD-3-Clause" ]
null
null
null
internal/notes/builtin-SAVE/packages/py-pyflakes/package.py
HPCToolkit/hpctest
5ff4455582bf39e75530a31badcf6142081b386b
[ "BSD-3-Clause" ]
2
2019-08-06T18:13:57.000Z
2021-11-05T18:19:49.000Z
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class PyPyflakes(PythonPackage): """A simple program which checks Python source files for errors.""" homepage = "https://github.com/PyCQA/pyflakes" url = "https://github.com/PyCQA/pyflakes/archive/1.3.0.tar.gz" version('1.3.0', 'a76173deb7a84fe860c0b60e2fbcdfe2') version('1.2.3', '2ac2e148a5c46b6bb06c4785be76f7cc') version('1.2.2', 'fe759b9381a6500e67a2ddbbeb5161a4') version('1.2.1', '444a06b256e0a70e41c11698b7190e84') version('1.2.0', '5d1c87bf09696c4c35dc3103f2a1185c') version('1.1.0', '4e18bf78c0455ebcd41e5d6104392c88') version('1.0.0', 'e2ea22a825c5100f12e54b71771cde71') version('0.9.2', 'd02d5f68e944085fd6ec163a34737a96') version('0.9.1', '8108d2248e93ca6a315fa2dd31ee9bb1') version('0.9.0', '43c2bcee88606bde55dbf25a253ef886') # Most Python packages only require py-setuptools as a build dependency. # However, py-pyflakes requires py-setuptools during runtime as well. depends_on('py-setuptools', type=('build', 'run'))
47.166667
78
0.694788
020f74c2ff9908146b7a1e81636c9efdc20b0af9
37,387
py
Python
mysql-dst/mysql-cluster/ndb/mcc/request_handler.py
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
9
2020-12-17T01:59:13.000Z
2022-03-30T16:25:08.000Z
mysql-dst/mysql-cluster/ndb/mcc/request_handler.py
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
1
2021-07-30T12:06:33.000Z
2021-07-31T10:16:09.000Z
mysql-dst/mysql-cluster/ndb/mcc/request_handler.py
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
1
2021-08-01T13:47:07.000Z
2021-08-01T13:47:07.000Z
# Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ The core of the configurator backend. Implements the BaseHTTPRequestHandler that will process HTTP requests received by the BaseHTTPServer to create the configurator backend web server. Also contains functions and classes needed to implement the Json-based communication protocol used to communicate with the frontend. """ import traceback import SocketServer import BaseHTTPServer import json import mimetypes import pprint import sys import types import ssl import copy import socket import time import os import os.path import logging import optparse import webbrowser import tempfile import threading import random import stat import errno import contextlib # import base64 from cryptography.fernet import Fernet from cryptography.hazmat.primitives import hashes from cryptography.hazmat.backends import default_backend # import util import config_parser import mcc_config #from Crypto.Cipher import AES #from Crypto.Hash import SHA256 from clusterhost import produce_ABClusterHost _logger = logging.getLogger(__name__) configFile = None passphrase = None class ShutdownException(Exception): """Exception thrown when shutdown command arrives""" pass class ReplyJsonEncoder(json.JSONEncoder): """Specialized encoder for which will serialize the folliowing types, in addition to those handled by JSONEncoder: TypeTypes - as an html-friendly version their str() output TracebackType - as a list of elements (returned by traceback.extrace_tb Any class with the __dict__ attribute is serialized as a dict to a json object. """ def default(self, obj): """Overrides the default function in JSONEncoder. Specialized for TypeTypes, TracebackTypes and dict-like types. All other types are passed to JSONEncoder.default().""" if isinstance(obj, types.TypeType): return str(obj).replace('<','&lt;').replace('>', '&gt;') if isinstance(obj, types.TracebackType): return traceback.extract_tb(obj) if hasattr(obj, '__dict__'): assert isinstance(vars(obj), dict), str(type(obj)) + ' dict attr has type '+str(type(vars(obj))) return vars(obj) # Ordinary json serialization return json.JSONEncoder.default(self, obj) def handle_req(req): """Primary dispatcher function for messages from the client-frontend. Uses introspection to look for a function named handle_<command name> and invokes that to process the message. req - incoming message (web server request) from the frontend """ h = globals()[ 'handle_'+req['head']['cmd']] return h(req, req['body']) def make_rep(req, body=None): """Utility which creates a reply object based on the headers in the request object.""" rep = { 'head': { 'seq': req['head']['seq'] +1, 'cmd': req['head']['cmd'], 'rSeq': req['head']['seq'] }} _logger.warning('make_rep rep: ' + str(rep)) if body: rep['body'] = body _logger.warning('make_rep body') return rep def is_host_local(HostDesignation): if (HostDesignation == 'localhost' or HostDesignation == '127.0.0.1'): _logger.warning('Host is local (1-1).') return True # Check if proper IP address is provided for localhost: ips = socket.gethostbyname_ex(socket.gethostname())[2] for ipadr in ips: if ipadr == HostDesignation: _logger.warning('Host is local (1-2).') return True return False def get_cred(HostNm, body): """Get the credentials from the message in the form of a (user, pwd) tuple. If there is no ssh object present, or keyBased is present and True, return (User, passphrase, key_file) block.""" try: if ((not body.has_key('ssh') or util.get_val(body['ssh'], 'keyBased', False)) and (not is_host_local(HostNm))): # It's key-based, implement new logic. {keyBased: true, key: "", key_user: "", key_passp: "", key_file: ""}; _logger.warning('get_cred, new logic 1.') return (True, body['ssh']['key_user'], body['ssh']['key_passp'], body['ssh']['key_file']) except KeyError: _logger.warning('get_cred, KeyError handler.') if ((not body.has_key('ssh') or util.get_val(body['ssh'], 'keyBased', False)) and (not is_host_local(HostNm))): # It's key-based, implement new logic. {keyBased: true, key: "", key_user: "", key_passp: "", key_file: ""}; _logger.warning('get_cred, new logic 2.') return (True, body['ssh']['key_user'], body['ssh']['key_passp'], body['ssh']['key_file']) _logger.warning('get_cred, old(ish) code.') if (is_host_local(HostNm)): return (False, "", "", None) else: return (False, body['ssh']['user'], body['ssh']['pwd'], None) def get_key(password): _logger.warning('Getting key from passp.') digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) #digest.update(bytes(password, "utf8")) does not work... digest.update(bytes(password)) return base64.urlsafe_b64encode(digest.finalize()) def encrypt(key, token): f = Fernet(get_key(key)) _logger.warning('Encrypting.') return f.encrypt(bytes(token)) def decrypt(key, token): f = Fernet(get_key(key)) _logger.warning('Decrypting.') return f.decrypt(bytes(token)) def handle_hostInfoReq(req, body): """Handler function for hostInfoReq commands. Will connect to the specified host through a remote.ClusterHost object to retrieve information. req - top level message object body - shortcut to the body part of the message """ (key_based, user, pwd, key_file) = get_cred(body['hostName'], body) with produce_ABClusterHost(body['hostName'], key_based, user, pwd, key_file) as ch: return make_rep(req, { 'host': {'name': ch.host }, 'hostRes': {'ram':ch.ram, 'cores': ch.cores, 'uname': ch.hostInfo.uname, 'installdir': ch.installdir, 'datadir': ch.hostInfo.pm.join(ch.homedir, 'MySQL_Cluster'), 'diskfree': ch.hostInfo.disk_free, 'fqdn': socket.getfqdn(ch.host), 'osver': ch.hostInfo.osver, 'osflavor': ch.hostInfo.osflavor, 'docker_info': ch.hostInfo.docker_info}}) def handle_hostDockerReq(req, body): """Handler function for hostDockerReq command. Will connect to the specified host through a remote.ClusterHost object to retrieve information. req - top level message object body - shortcut to the body part of the message """ (key_based, user, pwd, key_file) = get_cred(body['hostName'], body) with produce_ABClusterHost(body['hostName'], key_based, user, pwd, key_file) as ch: return make_rep(req, { 'host': {'name': ch.host }, 'hostRes': {'DockerInfo':ch.hostInfo.docker_info}}) def start_proc(proc, body): """Start individual process as specified in startClusterReq command. proc - the process object in the message body - the whole message """ f = proc['file'] (key_based, user, pwd, key_file) = get_cred(f['hostName'], body) with produce_ABClusterHost(f['hostName'], key_based, user, pwd, key_file) as ch: pc = proc['procCtrl'] params = proc['params'] if f.has_key('autoComplete'): _logger.warning('AUTOCOMPLETE key is there') if isinstance(f['autoComplete'], list): _logger.warning('AUTOCOMPLETE key is A LIST') executable = ch.auto_complete(f['path'], f['autoComplete'], f['name']) else: _logger.warning('AUTOCOMPLETE key is NOT A LIST') executable = ch.auto_complete(f['path'], ['bin', 'sbin', 'scripts', '', ch.path_module.join('..','scripts')], f['name']) else: _logger.warning('NO AUTOCOMPLETE key') executable = ch.path_module.join(f['path'], f['name']) stdinFile = None if f.has_key('stdinFile'): assert (ch.file_exists(f['stdinFile'])), 'File ' + f['stdinFile'] + " does not exist on host " + ch.host stdinFile = f['stdinFile'] _logger.debug('Attempting to launch '+executable+' on '+ch.host+ ' with pc='+str(pc)) _logger.warning('Attempting to launch '+executable+' on '+ch.host+ ' with pc='+str(pc)) cmdv = util.params_to_cmdv(executable, params) _logger.warning('CMDV is '+str(cmdv)) if proc.has_key('isCommand'): return ch.execute_command(cmdv, stdinFile) return ch.exec_cmdv(cmdv, pc, stdinFile) def handle_executeCommandReq(req, body): """Handler function for execCommandReq messages. Runs the process specified in by the command property.""" if body['command'].has_key('isCommand'): return make_rep(req, start_proc(body['command'], body)) return make_rep(req, {'out': start_proc(body['command'], body) }) def handle_createFileReq(req, body): """Handler function for createFileReq commands. Creates a file on the remote host with content from the message. req - top level message object body - shortcut to the body part of the message There is a problem with this function on Windows: Since pathname = ch.path_module.join(pathname, f['name']) DIRECTORY pathname instead of file PATH/NAME is created leading to Access violation :-/ """ f = body['file'] (key_based, user, pwd, key_file) = get_cred(f['hostName'], body) with produce_ABClusterHost(f['hostName'], key_based, user, pwd, key_file) as ch: pathname = f['path'] if f.has_key('name'): pathname = ch.path_module.join(pathname, f['name']) assert not (f.has_key('autoComplete') and f['autoComplete']) assert not (not (f.has_key('overwrite') and f['overwrite']) and ch.file_exists(pathname)), 'File '+pathname+' already exists on host '+ch.host ch.mkdir_p(f['path']) with ch.open(pathname, 'w+') as rf: rf.write(body['contentString']) with ch.open(pathname) as rf: assert rf.read() == body['contentString'] else: ch.mkdir_p(f['path']) _logger.debug('pathname ' + pathname + ' created') return make_rep(req) def handle_appendFileReq(req, body): """Handler function for appendFileReq commands. Opens two files on the remote host, copies from source and appends to destination. req - top level message object body - shortcut to the body part of the message """ assert (body.has_key('sourceFile') and body.has_key('destinationFile')) sf = body['sourceFile'] df = body['destinationFile'] assert (sf.has_key('path') and sf.has_key('name') and sf.has_key('hostName')) assert (df.has_key('path') and df.has_key('name') and df.has_key('hostName')) (key_based, user, pwd, key_file) = get_cred(sf['hostName'], body) with produce_ABClusterHost(sf['hostName'], key_based, user, pwd, key_file) as ch: sp = ch.path_module.join(sf['path'], sf['name']) dp = ch.path_module.join(df['path'], df['name']) assert (ch.file_exists(dp)), 'File ' + dp + ' does not exist on host ' + ch.host content = None with ch.open(sp) as sourceFile: content = sourceFile.read() assert (ch.file_exists(sp)), 'File ' + sp + ' does not exist on host ' + ch.host with ch.open(dp, 'a+') as destinationFile: destinationFile.write(content) return make_rep(req) def handle_checkFileReq(req, body): """Handler function for checkFileReq commands. Check if a file exists on a remote host. req - top level message object body - shortcut to the body part of the message """ f = body['file'] (key_based, user, pwd, key_file) = get_cred(f['hostName'], body) with produce_ABClusterHost(f['hostName'], key_based, user, pwd, key_file) as ch: sp = ch.path_module.join(f['path'], f['name']) _logger.warning('pathname ' + sp + ' in checking') assert (ch.file_exists(sp)), 'File ' + sp + ' does not exist on host ' + ch.host _logger.debug('pathname ' + sp + ' checked') return make_rep(req) def handle_listDirectoryReq(req, body): """Handler function for listDirectoryReq command. req - top level message object body - shortcut to the body part of the message """ # This is what new session starts with so reset globals from previous run. global passphrase global configFile passphrase = None configFile = None _logger.warning('Passphrase & ConfigFileName reset.') f = body['file'] results = [] path = f['path'] ext = f['ext'] (key_based, user, pwd, key_file) = get_cred(f['hostName'], body) with produce_ABClusterHost(f['hostName'], key_based, user, pwd, key_file) as ch: if (path == "~"): path = ch.homedir #os.path.expanduser(path) path = os.path.join(path, '') #Add last /... Well, IF MCC is not running on localhost, this will fail. Will fix later if needs be. results += [each for each in os.listdir(path) if (each.endswith(ext) and os.path.getsize(path+each) > 10)] return make_rep(req, { 'host': {'name': ch.host }, 'hostRes': {'listDirectory': results, 'realpath': path.replace("\\","/")}}) #Will return / instead of \ on Windows. repr(path) would return \\ def handle_fileExistsReq(req, body): """Handler function for fileExistsReq command. req - top level message object body - shortcut to the body part of the message Plain file exists on host or not. """ path = body['path'] filename = body['fname'] resStr = "" (key_based, user, pwd, key_file) = get_cred(body['hostName'], body) with produce_ABClusterHost(body['hostName'], key_based, user, pwd, key_file) as ch: _logger.warning('Produced ABC (FER).') if (path == "~"): path = ch.homedir sp = ch.path_module.join(path, filename) _logger.warning('pathname ' + sp + ' in checking.') resStr = ch.file_exists(sp) if not(resStr is None): result = 1 else: result = 0 _logger.warning('FER result is ' + str(result) + '.') return make_rep(req, { 'host': {'name': ch.host }, 'hostRes': {'fname': filename, 'exists': result}}) def handle_createCfgFileReq(req, body): """Handler function for createCfgFileReq command. req - top level message object body - shortcut to the body part of the message Plain file create on host. """ global passphrase global configFile path = body['path'] #if passphrase is None: passphrase = body['phr'] configFile = body['fname'] (key_based, user, pwd, key_file) = get_cred(body['hostName'], body) with produce_ABClusterHost(body['hostName'], key_based, user, pwd, key_file) as ch: if (path == "~"): path = ch.homedir _logger.warning('path is ' + path + ' and name is ' + configFile + '.') pathname = ch.path_module.join(path, configFile) if (body.has_key('contentString')): with ch.open(pathname, 'w+') as rf: rf.write(body['contentString']) with ch.open(pathname) as rf: assert rf.read() == body['contentString'] #encrypt(getKey(passphrase), pathname) #""" output_file = pathname + ".encrypted" with open(pathname, 'r') as inputfile: inp = inputfile.read() res = encrypt(passphrase, inp) with open(output_file, 'wb') as outf: outf.write(res) #Remove plain text file. if os.path.isfile(pathname): os.remove(pathname) else: #Show an error. print("Encrypt error: Original file %s not found" % pathname) #Rename new file to old name. old_file = output_file #name.mcc.encrypted. new_file = pathname #name.mcc os.rename(old_file, new_file) #""" _logger.warning('File ' + pathname + ' created.') return make_rep(req, { 'host': {'name': ch.host }, 'hostRes': {'fname': configFile, 'created': 1}}) def handle_readCfgFileReq(req, body): """Handler function for readCfgFileReq command. req - top level message object body - shortcut to the body part of the message Plain file read on host. Body: hostName path fname phr Ignore passphrase for now. """ path = body['path'] #name = body['fname'] global passphrase global configFile #if passphrase is None: passphrase = body['phr'] #if configFile is None: configFile = body['fname'] (key_based, user, pwd, key_file) = get_cred(body['hostName'], body) with produce_ABClusterHost(body['hostName'], key_based, user, pwd, key_file) as ch: _logger.warning('Inside produce_ABClusterHost, readcfgfilereq.') if (path == "~"): path = ch.homedir pathname = ch.path_module.join(path, configFile) _logger.warning('pathname ' + pathname + ' in opening.') with open(pathname, 'rb') as rencf: inp = rencf.read() res = decrypt(passphrase, inp) _logger.warning('File ' + pathname + ' read.') return make_rep(req, { 'host': {'name': ch.host }, 'hostRes': {'fname': configFile, 'contentString': res}}) def handle_shutdownServerReq(req, body): """x""" if body.has_key('deathkey') and body['deathkey'] == deathkey: raise ShutdownException("Shutdown request received") time.sleep(util.get_val(body, 'sleeptime', 0)) return make_rep(req, 'incorrect death key') def handle_getLogTailReq(req, body): """Handler function for getLogTailReq commands. Opens a file on the remote host and adds content to reply req - top level message object body - shortcut to the body part of the message """ sf = body['logFile'] assert (sf.has_key('path') and sf.has_key('name') and sf.has_key('hostName')) (key_based, user, pwd, key_file) = get_cred(sf['hostName'], body) with produce_ABClusterHost(sf['hostName'], key_based, user, pwd, key_file) as ch: sp = ch.path_module.join(sf['path'], sf['name']) assert (ch.file_exists(sp)), 'File ' + sp + ' does not exist on host ' + ch.host with ch.open(sp) as logFile: return make_rep(req, {'tail': logFile.read()}) from util import _parse_until_delim, parse_properties def parse_reply(ctx): """Return False unless ctx['str'] is an mgmd reply. Assign first line to ctx['reply_type], parse property list and return True otherwise.""" return _parse_until_delim(ctx, 'reply_type', '\n') and parse_properties(ctx,': ') class mgmd_reply(dict): def __init__(self, s=None): if (s): ctx = {'str': s, 'properties':self} parse_reply(ctx) self.reply_type = ctx['reply_type'] def __str__(self): return self.reply_type+'\n'+'\n'.join(['{0}: {1}'.format(str(k), str(self[k])) for k in self.keys()])+'\n' def handle_runMgmdCommandReq(req, body): """Handler function for runMgmdCommandReq commands. Opens a new connection to mgmd, sends command, parses reply and wraps reply in mcc Rep object.""" hostname = body['hostName'].encode('ascii', 'ignore') port = body['port'] # If none is listening, this will lead to Error 10061 (Can't connect to MySQL server) # so need to test first. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = s.connect_ex((hostname, port)) s.close() if result == 0: with util.socket_shutter(socket.create_connection((hostname, port))) as mgmd: mgmd.sendall(body['mgmd_command']+'\n\n') s = mgmd.recv(4096) status = mgmd_reply(s) sd = {} for nk in status.keys(): if 'node.' in nk: (x, n, k) = nk.split('.') if not sd.has_key(n): sd[n] = {} sd[n][k] = status[nk] return make_rep(req, { 'reply_type': status.reply_type, 'reply_properties':sd}) else: #, 'reply_properties':'None listening @ '+str(hostname)+'::' + str(port) return make_rep(req, { 'reply_type': 'ERROR'}) def handle_getConfigIni(req, body): cf = body['configFile'] assert (cf.has_key('path') and cf.has_key('name') and cf.has_key('hostName')) (key_based, user, pwd, key_file) = get_cred(cf['hostName'], body) with produce_ABClusterHost(cf['hostName'], key_based, user, pwd, key_file) as ch: sp = ch.path_module.join(sf['path'], sf['name']) assert (ch.file_exists(sp)), 'File ' + sp + ' does not exist on host ' + ch.host with ch.open(sp) as ini: return make_rep(req, {'config': config_parser.parse_cluster_config_ini_(ini)}) def handle_getNdbConfig(req, body): (key_based, user, pwd, key_file) = get_cred(body['hostName'], body) with produce_ABClusterHost(body['hostName'], key_based, user, pwd, key_file) as ch: ndb_config = ch.path_module.join(body['installpath'], 'ndb_config') return make_rep(req, { 'ndb_config': json.dumps(util.xml_to_python(ch.exec_cmdv([ndb_config, '--configinfo', '--xml']))) }) def log_thread_name(): """Utility for dumping thread id in the log.""" cur_thread = threading.current_thread() _logger.debug("cur_thread="+str(cur_thread.name)) class ConfiguratorHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handler class for web server requests to the configurator backend. To be used with a BaseHTTPServer.HTTPServer to create a working server.""" def _send_as_json(self, obj): self.send_response(200) self.send_header('Content-type', 'text/json') self.end_headers() for possible_encoding in ["utf-8", "cp1252"]: try: # obj can contain messages from the OS that could be encoded # in cp1252 character set. json_str = json.dumps(obj, indent=2, cls=ReplyJsonEncoder, encoding=possible_encoding) break except UnicodeDecodeError: self.server.logger.debug('%s encoding failed', possible_encoding) self.server.logger.warning('%s encoding failed', possible_encoding) pass if json_str is None: raise UnicodeDecodeError self.server.logger.debug('Will send: %s', json.dumps(obj, indent=2, cls=ReplyJsonEncoder, encoding=possible_encoding)) json.dump(obj, self.wfile, cls=ReplyJsonEncoder, encoding=possible_encoding) def _do_file_req(self, rt): """Handles file requests. Attempts to guess the MIME type and set the Content-Type accordingly.""" try: log_thread_name() if self.path == '/': self.path = '/'+mcc_config.MCC_BROWSER_START_PAGE self.server.logger.debug(rt+' fdir='+self.server.opts['fdir']+ " path="+os.path.normpath(self.path)) #Make sure to remove options if there are any. fn = os.path.join(self.server.opts['fdir'], os.path.normpath(self.path[1:]).split("?")[0]) try: os.stat(fn) except OSError as ose: self.server.logger.exception(rt + ' '+self.path+ ' failed') if ose.errno == errno.ENOENT: self.send_error(404, self.path+'=> file://'+ose.filename+' does not exist') return raise self.send_response(200) (ct, enc) = mimetypes.guess_type(self.path) if (ct): self.send_header('Content-type', ct) if (enc): self.send_header('Content-Encoding', enc) self.end_headers() if rt == 'GET': with open(fn, "rb") as f: self.wfile.write(f.read()+'\r\n\r\n') except: self.server.logger.exception(rt + ' '+self.path+ ' failed') self.send_error(500,'Unexpected exception occured while processing: '+rt+' '+self.path+'\n'+traceback.format_exc()) # Some other number def do_HEAD(self): """Handles HEAD requests by returning the headers without the body if file can be stated.""" self._do_file_req('HEAD') def do_GET(self): """Handles GET requests by returning the specified file.""" self._do_file_req('GET') def do_POST(self): """Handles POST requests, in the form of json-serialized command (request) objects, from the frontend.""" log_thread_name() try: # Assume all post requests are json assert 'application/json' in self.headers['Content-Type'] msg = json.loads(self.rfile.read(int(self.headers['Content-Length']))) dbgmsg = copy.deepcopy(msg) if (dbgmsg['body']['ssh'].has_key('pwd')): dbgmsg['body']['ssh']['pwd'] = '*' * len(dbgmsg['body']['ssh']['pwd']) if (dbgmsg['body']['ssh'].has_key('key_passp')): dbgmsg['body']['ssh']['key_passp'] = '*' * len(dbgmsg['body']['ssh']['key_passp']) self.server.logger.debug('--> ' + dbgmsg['head']['cmd'] + ':') self.server.logger.debug(pprint.pformat(dbgmsg)) rep = make_rep(msg) try: rep = handle_req(msg) except ShutdownException: self.server.shutdown() except: #traceback.print_exc() self.server.logger.exception('POST request failed:') (etype, eobj, etb) = sys.exc_info() rep['stat'] = { 'errMsg': util.html_rep(eobj), 'exType': etype, 'exObj': eobj, 'exTrace': etb } self.server.logger.debug('<-- ' + rep['head']['cmd'] + ':') self.server.logger.debug(pprint.pformat(rep)) self.server.logger.warning('<-- ' + rep['head']['cmd'] + ':') self._send_as_json(rep) except: traceback.print_exc() self.server.logger.critical('Internal server error:') self.server.logger.exception('Unexpected exception:') self.send_error(500, 'Server Exception\n'+traceback.format_exc()+'while processeing request:\n'+str(self.headers)) def log_message(self, fmt, *args): """Overrides the default implementation which logs to stderr""" self.server.logger.info(msg=(fmt%args)) class ConfiguratorServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): """Specialization of HTTPServer which adds ssl wrapping, shutdown on close and MT (by also inheriting SocketServer.ThreadingMixIn.""" def __init__(self, opts): # Cannot use super() here, as BaseServer is not a new-style class SocketServer.TCPServer.__init__(self, (opts['server'], opts['port']), ConfiguratorHandler) self.opts = opts self.logger = logging.getLogger(str(self.__class__)) def get_request(self): """Override get_request from SocketServer.TCPServer so that we can wrap the socket in an ssl socket when using ssl.""" sock,addr = SocketServer.TCPServer.get_request(self) if util.get_val(self.opts, 'ssl', False): if self.opts['ca_certs']: cert_reqs = ssl.CERT_REQUIRED else: cert_reqs = ssl.CERT_NONE ssl_sock = ssl.wrap_socket(sock, certfile=self.opts['certfile'], keyfile=self.opts['keyfile'], cert_reqs=cert_reqs, ca_certs=self.opts['ca_certs'], server_side=True) #self.logger.debug('ssl_sock.getpeercert()='+str(ssl_sock.getpeercert()) return ssl_sock, addr return sock, addr def close_request(self, request): """Override to make sure shutdown gets called on request socket.""" try: request.shutdown(socket.SHUT_RDWR) except: pass finally: SocketServer.TCPServer.close_request(self, request) configdir = None basedir = None deathkey = None from util import is_port_available def main(prefix, cfgdir): """Server's main-function which parses the command line and starts up the server accordingly. """ global configdir global basedir true_port_val = 0 configdir = cfgdir basedir = prefix def_server_name = 'localhost' if hasattr(webbrowser, 'WindowsDefault') and isinstance(webbrowser.get(), webbrowser.WindowsDefault): # If on windows and using IE we do this to avoid IE9 bug (doesn't affect other versions of IE, there is no easy way to test def_server_name = socket.gethostname() cmdln_parser = optparse.OptionParser() cmdln_parser.add_option('-N', '--server_name', action='store', type='string', default=def_server_name, help='server name: [default: %default ]') cmdln_parser.add_option('-p', '--port', action='store', type='int', dest='port', default=8081, help='port for the webserver: [default: %default]') cmdln_parser.add_option('-n', '--no-browser', action='store_true', help='do not open the server\'s start page in a browser.') cmdln_parser.add_option('-s', '--browser-start-page', action='store', type='string', dest='browser_start_page', default=mcc_config.MCC_BROWSER_START_PAGE, help='start page for browser: [default: %default]') cmdln_parser.add_option('-d', '--debug-level', action='store', type='string', default='WARNING', help='Python logging module debug level (DEBUG, INFO, WARNING, ERROR or CRITICAL). [default: %default]') cmdln_parser.add_option('-o', '--server-log-file', action='store', type='string', default=os.path.join(tempfile.gettempdir(),'ndb_setup-'+str(os.getpid())+'.log'), help='log requests to this file. The value - means log to stderr: [default: %default]') # option for level/logcfg file cmdln_parser.add_option('-H', '--use-http', action='store_true', help='use http for communication with browser.') cmdln_parser.add_option('-S', '--use-https', action='store_true', help='use https to secure communication with browser.') cmdln_parser.add_option('-c', '--cert-file', action='store', type='string', default=os.path.join(cfgdir, 'cfg.pem'), help='file containing X509 certificate which identifies the server (possibly self-signed): [default: %default]') cmdln_parser.add_option('-k', '--key-file', action='store', type='string', help='file containing private key when if not included in cert-file: [default: %default]') cmdln_parser.add_option('-a', '--ca-certs-file', action='store', type='string', help='file containing list of client certificates allowed to connect to the server [default: %default (no client authentication)]') (options, arguments) = cmdln_parser.parse_args() dbglvl = getattr(logging, options.debug_level, logging.DEBUG) fmt = '%(asctime)s: %(levelname)s [%(funcName)s;%(filename)s:%(lineno)d]: %(message)s ' if options.server_log_file == '-': logging.basicConfig(level=dbglvl, format=fmt) else: logging.basicConfig(level=dbglvl, format=fmt, filename=options.server_log_file) for port_val in range(options.port, options.port + 20): if is_port_available(options.server_name, port_val): true_port_val = port_val break if true_port_val == 0: # no available port in range :-/ print("No available port in range[{},{}]!".format(options.port, options.port + 20)) sys.exit() options.port = true_port_val srvopts = { 'server' : options.server_name, 'port': options.port, 'cdir': cfgdir, 'fdir': os.path.join(cfgdir, 'frontend') } if not options.use_http: options.use_https = True if options.use_https: srvopts['ssl'] = True srvopts['certfile'] = options.cert_file srvopts['keyfile'] = options.key_file srvopts['ca_certs'] = options.ca_certs_file flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY hpath = os.path.expanduser('~') global pidf pidf = os.path.join(hpath, 'mcc.pid') try: file_handle = os.open(pidf, flags) except OSError as e: if e.errno == errno.EEXIST: # Failed as the file already exists. file_handle = open(pidf) # , os.O_RDONLY) print 'mcc.pid file found at '+os.path.realpath(file_handle.name)+'. Please remove before restarting process.' file_handle.close() sys.exit("Web server already running!") else: # Something unexpected went wrong so reraise the exception. raise else: # No exception, so the file must have been created successfully. with os.fdopen(file_handle, 'w') as file_obj: # Using `os.fdopen` converts the handle to an object that acts like a # regular Python file object, and the `with` context manager means the # file will be automatically closed when we're done with it. file_obj.write("MCC running.") file_obj.close() print 'Starting web server on port ' + repr(options.port) url_host = options.server_name if url_host == '': url_host = 'localhost' #Here we should send list of config files too. results = [] resStr = "" path = os.path.expanduser('~') path = os.path.join(path, '') results += [each for each in os.listdir(path) if (each.endswith('.mcc') and os.path.getsize(path+each) > 10)] resStr = '&'.join(results) #Check there is anything. if len(results): resStr = "?" + resStr + "#" else: resStr = "" if options.use_https: if not resStr: url = 'https://{0}:{opt.port}/{opt.browser_start_page}'.format(url_host, opt=options) else: url = 'https://{0}:{opt.port}/{opt.browser_start_page}{1}'.format(url_host, resStr, opt=options) else: if not resStr: url = 'http://{0}:{opt.port}/{opt.browser_start_page}'.format(url_host, opt=options) else: url = 'http://{0}:{opt.port}/{opt.browser_start_page}{1}'.format(url_host, resStr, opt=options) print("URL is {}.".format(url)) httpsrv = None global deathkey deathkey = random.randint(100000, 1000000) print 'deathkey='+str(deathkey) print 'Press CTRL+C to stop web server.' # dkf = open('deathkey.txt','w') # dkf.write(str(deathkey)) # dkf.close() # os.chmod('deathkey.txt', stat.S_IRUSR) try: httpsrv = ConfiguratorServer(srvopts) if not options.no_browser: try: webbrowser.open_new(url) except: logging.exception('Failed to control browser: ') print 'Could not control your browser. Try to opening '+url+' to launch the application.' else: print 'The application should now be running in your browser.\n(Alternatively you can navigate to '+url+' to start it)' else: print 'Navigate to '+url+' to launch the application.' httpsrv.serve_forever() except KeyboardInterrupt: print '^C received, shutting down web server' except: traceback.print_exc() finally: if httpsrv: httpsrv.socket.close() #os.remove('deathkey.txt') print 'Removing ' + pidf os.remove(pidf)
42.582005
233
0.612272
7215ab298bc393b5930ec6bfd82c79f1b96918f2
1,033
py
Python
tests/scheduling/conftest.py
JeshuaT/PsyNeuLink
912f691028e848659055430f37b6c15273c762f1
[ "Apache-2.0" ]
67
2018-01-05T22:18:44.000Z
2022-03-27T11:27:31.000Z
tests/scheduling/conftest.py
JeshuaT/PsyNeuLink
912f691028e848659055430f37b6c15273c762f1
[ "Apache-2.0" ]
1,064
2017-12-01T18:58:27.000Z
2022-03-31T22:22:24.000Z
tests/scheduling/conftest.py
JeshuaT/PsyNeuLink
912f691028e848659055430f37b6c15273c762f1
[ "Apache-2.0" ]
25
2017-12-01T20:27:07.000Z
2022-03-08T21:49:39.000Z
import psyneulink as pnl import pytest def pytest_assertrepr_compare(op, left, right): if isinstance(left, list) and isinstance(right, list) and op == '==': return [ 'Time Step output matching:', 'Actual output:', str(left), 'Expected output:', str(right) ] @pytest.helpers.register def setify_expected_output(expected_output): type_set = type(set()) for i in range(len(expected_output)): if type(expected_output[i]) is not type_set: try: iter(expected_output[i]) expected_output[i] = set(expected_output[i]) except TypeError: expected_output[i] = set([expected_output[i]]) return expected_output @pytest.fixture def three_node_linear_composition(): A = pnl.TransferMechanism(name='A') B = pnl.TransferMechanism(name='B') C = pnl.TransferMechanism(name='C') comp = pnl.Composition() comp.add_linear_processing_pathway([A, B, C]) return comp.nodes, comp
27.918919
73
0.632139
f5996a9c6eb5884f59766af3217d924ec3eab701
7,600
py
Python
databuilder/publisher/elasticsearch_publisher.py
pemmasanikrishna/amundsendatabuilder
f29bb3baeb61f383750b4492538a79415daa149b
[ "Apache-2.0" ]
null
null
null
databuilder/publisher/elasticsearch_publisher.py
pemmasanikrishna/amundsendatabuilder
f29bb3baeb61f383750b4492538a79415daa149b
[ "Apache-2.0" ]
null
null
null
databuilder/publisher/elasticsearch_publisher.py
pemmasanikrishna/amundsendatabuilder
f29bb3baeb61f383750b4492538a79415daa149b
[ "Apache-2.0" ]
null
null
null
import json import logging import textwrap from typing import List # noqa: F401 from pyhocon import ConfigTree # noqa: F401 from elasticsearch.exceptions import NotFoundError from databuilder.publisher.base_publisher import Publisher LOGGER = logging.getLogger(__name__) class ElasticsearchPublisher(Publisher): """ Elasticsearch Publisher uses Bulk API to load data from JSON file. A new index is created and data is uploaded into it. After the upload is complete, index alias is swapped to point to new index from old index and traffic is routed to new index. Old index is deleted after the alias swap is complete """ FILE_PATH_CONFIG_KEY = 'file_path' FILE_MODE_CONFIG_KEY = 'mode' ELASTICSEARCH_CLIENT_CONFIG_KEY = 'client' ELASTICSEARCH_DOC_TYPE_CONFIG_KEY = 'doc_type' ELASTICSEARCH_NEW_INDEX_CONFIG_KEY = 'new_index' ELASTICSEARCH_ALIAS_CONFIG_KEY = 'alias' ELASTICSEARCH_MAPPING_CONFIG_KEY = 'mapping' # Specifying default mapping for elasticsearch index # Documentation: https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping.html # Setting type to "text" for all fields that would be used in search # Using Simple Analyzer to convert all text into search terms # https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-simple-analyzer.html # Standard Analyzer is used for all text fields that don't explicitly specify an analyzer # https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-standard-analyzer.html # TODO use amundsencommon for this when this project is updated to py3 DEFAULT_ELASTICSEARCH_INDEX_MAPPING = textwrap.dedent( """ { "mappings":{ "table":{ "properties": { "name": { "type":"text", "analyzer": "simple", "fields": { "raw": { "type": "keyword" } } }, "schema": { "type":"text", "analyzer": "simple", "fields": { "raw": { "type": "keyword" } } }, "display_name": { "type": "keyword" }, "last_updated_timestamp": { "type": "date", "format": "epoch_second" }, "description": { "type": "text", "analyzer": "simple" }, "column_names": { "type":"text", "analyzer": "simple", "fields": { "raw": { "type": "keyword" } } }, "column_descriptions": { "type": "text", "analyzer": "simple" }, "tags": { "type": "keyword" }, "badges": { "type": "keyword" }, "cluster": { "type": "text" }, "database": { "type": "text", "analyzer": "simple", "fields": { "raw": { "type": "keyword" } } }, "key": { "type": "keyword" }, "total_usage":{ "type": "long" }, "unique_usage": { "type": "long" } } } } } """ ) def __init__(self): # type: () -> None super(ElasticsearchPublisher, self).__init__() def init(self, conf): # type: (ConfigTree) -> None self.conf = conf self.file_path = self.conf.get_string(ElasticsearchPublisher.FILE_PATH_CONFIG_KEY) self.file_mode = self.conf.get_string(ElasticsearchPublisher.FILE_MODE_CONFIG_KEY, 'w') self.elasticsearch_type = self.conf.get_string(ElasticsearchPublisher.ELASTICSEARCH_DOC_TYPE_CONFIG_KEY) self.elasticsearch_client = self.conf.get(ElasticsearchPublisher.ELASTICSEARCH_CLIENT_CONFIG_KEY) self.elasticsearch_new_index = self.conf.get(ElasticsearchPublisher.ELASTICSEARCH_NEW_INDEX_CONFIG_KEY) self.elasticsearch_alias = self.conf.get(ElasticsearchPublisher.ELASTICSEARCH_ALIAS_CONFIG_KEY) self.elasticsearch_mapping = self.conf.get(ElasticsearchPublisher.ELASTICSEARCH_MAPPING_CONFIG_KEY, ElasticsearchPublisher.DEFAULT_ELASTICSEARCH_INDEX_MAPPING) self.file_handler = open(self.file_path, self.file_mode) def _fetch_old_index(self): # type: () -> List[str] """ Retrieve all indices that currently have {elasticsearch_alias} alias :return: list of elasticsearch indices """ try: indices = self.elasticsearch_client.indices.get_alias(self.elasticsearch_alias).keys() return indices except NotFoundError: LOGGER.warn("Received index not found error from Elasticsearch. " + "The index doesn't exist for a newly created ES. It's OK on first run.") # return empty list on exception return [] def publish_impl(self): # type: () -> None """ Use Elasticsearch Bulk API to load data from file to a {new_index}. After upload, swap alias from {old_index} to {new_index} in a atomic operation to route traffic to {new_index} """ actions = [json.loads(l) for l in self.file_handler.readlines()] # ensure new data exists if not actions: LOGGER.warning("received no data to upload to Elasticsearch!") return # Convert object to json for elasticsearch bulk upload # Bulk load JSON format is defined here: # https://www.elastic.co/guide/en/elasticsearch/reference/6.2/docs-bulk.html bulk_actions = [] for action in actions: index_row = dict(index=dict(_index=self.elasticsearch_new_index, _type=self.elasticsearch_type)) bulk_actions.append(index_row) bulk_actions.append(action) # create new index with mapping self.elasticsearch_client.indices.create(index=self.elasticsearch_new_index, body=self.elasticsearch_mapping) # bulk upload data self.elasticsearch_client.bulk(bulk_actions) # fetch indices that have {elasticsearch_alias} as alias elasticsearch_old_indices = self._fetch_old_index() # update alias to point to the new index actions = [{"add": {"index": self.elasticsearch_new_index, "alias": self.elasticsearch_alias}}] # delete old indices delete_actions = [{"remove_index": {"index": index}} for index in elasticsearch_old_indices] actions.extend(delete_actions) update_action = {"actions": actions} # perform alias update and index delete in single atomic operation self.elasticsearch_client.indices.update_aliases(update_action) def get_scope(self): # type: () -> str return 'publisher.elasticsearch'
37.073171
117
0.557632
6bc62d51d418de6b1a5198f4a44843bf94a80638
5,884
py
Python
linequ.py
wangzqzero/calculator
94bf0c454672b88262ed87d090908a5ed1518fd3
[ "MIT" ]
null
null
null
linequ.py
wangzqzero/calculator
94bf0c454672b88262ed87d090908a5ed1518fd3
[ "MIT" ]
null
null
null
linequ.py
wangzqzero/calculator
94bf0c454672b88262ed87d090908a5ed1518fd3
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'linequ.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets import numpy as np try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_LinEquation(object): def solve(self): try: a11 = float(self.a1.text()) b11 = float(self.b1.text()) c11 = float(self.c1.text()) a22 = float(self.a2.text()) b22 = float(self.b2.text()) c22 = float(self.c2.text()) a = np.array([[a11, b11],[a22,b22]]) b = np.array([c11, c22]) [x,y]=np.linalg.solve(a,b) print(x) print(y) x=str(x) y=str(y) self.ansx.setText(x) self.ansy.setText(y) except np.linalg.LinAlgError: print("Math Error :Unique solution not possible , enter valid input") self.ansx.setText("Math Error : Unique solution not possible") self.ansy.setText("Math Error : Unique solution not possible") def setupUi(self, LinEquation): LinEquation.setObjectName("LinEquation") LinEquation.resize(470, 630) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(LinEquation.sizePolicy().hasHeightForWidth()) LinEquation.setSizePolicy(sizePolicy) LinEquation.setMinimumSize(QtCore.QSize(470, 630)) LinEquation.setMaximumSize(QtCore.QSize(470, 630)) self.label = QtWidgets.QLabel(LinEquation) self.label.setGeometry(QtCore.QRect(40, 20, 351, 41)) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(LinEquation) self.label_2.setGeometry(QtCore.QRect(80, 90, 251, 41)) self.label_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_2.setWordWrap(True) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(LinEquation) self.label_3.setGeometry(QtCore.QRect(10, 160, 141, 31)) self.label_3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_3.setWordWrap(True) self.label_3.setObjectName("label_3") self.label_4 = QtWidgets.QLabel(LinEquation) self.label_4.setGeometry(QtCore.QRect(10, 230, 121, 41)) self.label_4.setWordWrap(True) self.label_4.setObjectName("label_4") self.a1 = QtWidgets.QLineEdit(LinEquation) self.a1.setGeometry(QtCore.QRect(160, 160, 61, 41)) self.a1.setObjectName("a1") self.b1 = QtWidgets.QLineEdit(LinEquation) self.b1.setGeometry(QtCore.QRect(250, 160, 61, 41)) self.b1.setObjectName("b1") self.c1 = QtWidgets.QLineEdit(LinEquation) self.c1.setGeometry(QtCore.QRect(340, 160, 61, 41)) self.c1.setObjectName("c1") self.a2 = QtWidgets.QLineEdit(LinEquation) self.a2.setGeometry(QtCore.QRect(160, 230, 61, 41)) self.a2.setObjectName("a2") self.b2 = QtWidgets.QLineEdit(LinEquation) self.b2.setGeometry(QtCore.QRect(250, 230, 61, 41)) self.b2.setObjectName("b2") self.c2 = QtWidgets.QLineEdit(LinEquation) self.c2.setGeometry(QtCore.QRect(340, 230, 61, 41)) self.c2.setObjectName("c2") self.label_6 = QtWidgets.QLabel(LinEquation) self.label_6.setGeometry(QtCore.QRect(10, 370, 61, 41)) self.label_6.setObjectName("label_6") self.label_7 = QtWidgets.QLabel(LinEquation) self.label_7.setGeometry(QtCore.QRect(10, 440, 71, 51)) self.label_7.setObjectName("label_7") self.ansx = QtWidgets.QLineEdit(LinEquation) self.ansx.setGeometry(QtCore.QRect(100, 365, 301, 51)) self.ansx.setReadOnly(True) self.ansx.setObjectName("ansx") self.ansy = QtWidgets.QLineEdit(LinEquation) self.ansy.setGeometry(QtCore.QRect(100, 440, 301, 51)) self.ansy.setReadOnly(True) self.ansy.setObjectName("ansy") self.pushButton = QtWidgets.QPushButton(LinEquation) self.pushButton.setGeometry(QtCore.QRect(150, 310, 171, 41)) self.pushButton.setObjectName("pushButton") self.pushButton.clicked.connect(self.solve) self.retranslateUi(LinEquation) QtCore.QMetaObject.connectSlotsByName(LinEquation) def retranslateUi(self, LinEquation): _translate = QtCore.QCoreApplication.translate LinEquation.setWindowTitle(_translate("LinEquation", "Form")) self.label.setText(_translate("LinEquation", "Solution Equation Group")) self.label_2.setText(_translate("LinEquation", "The form of the equation is as follows a1x + b1y = c1 and a2x + b2y = c2")) self.label_3.setText(_translate("LinEquation", "please enter a1, b1 and c1")) self.label_4.setText(_translate("LinEquation", "please enter a2, b2 and c2")) self.label_6.setText(_translate("LinEquation", "x = ")) self.label_7.setText(_translate("LinEquation", "y = ")) self.pushButton.setText(_translate("LinEquation", "Calculate"))
45.612403
131
0.664684
0e56bfa5abf98af84585e76c8b35ae98684b280d
49,914
py
Python
tests/test_invariants_and_dependencies.py
IMTMarburg/pypipegraph2
182f04481f0b0b6b1c05cfbe23549714af5cfbcc
[ "MIT" ]
null
null
null
tests/test_invariants_and_dependencies.py
IMTMarburg/pypipegraph2
182f04481f0b0b6b1c05cfbe23549714af5cfbcc
[ "MIT" ]
null
null
null
tests/test_invariants_and_dependencies.py
IMTMarburg/pypipegraph2
182f04481f0b0b6b1c05cfbe23549714af5cfbcc
[ "MIT" ]
null
null
null
import os import gzip from pathlib import Path from loguru import logger import stat import time import hashlib import shutil import pytest import pypipegraph2 as ppg from .shared import write, read, append, Dummy, counter, force_load class Undepickable(object): def __getstate__(self): return {"shu": 123} # must not return falsey value def __setstate__(self, state): self.sha = state["shu"] import pickle raise pickle.UnpicklingError("SHU") @pytest.mark.usefixtures("create_out_dir") @pytest.mark.usefixtures("ppg2_per_test") class TestInvariant: def sentinel_count(self): sentinel = "out/sentinel" try: op = open(sentinel, "r") count = int(op.read()) op.close() except IOError: count = 1 op = open(sentinel, "w") op.write("%i" % (count + 1)) op.close() return count def test_filegen_jobs_detect_code_change(self): of = "out/a" def do_write(of): append(of, "shu" * self.sentinel_count()) ppg.FileGeneratingJob(of, do_write) ppg.run() assert read(of) == "shu" ppg.new() ppg.FileGeneratingJob(of, do_write) ppg.run() assert read(of) == "shu" # has not been run again... def do_write2(of): append(of, "sha") ppg.new() ppg.FileGeneratingJob(of, do_write2) ppg.run() assert read(of) == "sha" # has been run again ;). def test_filegen_jobs_ignores_code_change(self): of = "out/a" def do_write(of): counter("A") append(of, "shu" * self.sentinel_count()) job = ppg.FileGeneratingJob(of, do_write) ppg.run() assert read(of) == "shu" assert read("A") == "1" ppg.new() job = ppg.FileGeneratingJob(of, do_write) ppg.run() assert read(of) == "shu" # has not been run again, for no change assert read("A") == "1" ppg.new() def do_write2(of): counter("A") append(of, "sha") job = ppg.FileGeneratingJob(of, do_write2, depend_on_function=False) ppg.run() assert read(of) == "sha" # has been run again - number of invariants changed! assert read("A") == "2" ppg.new() job = ppg.FileGeneratingJob(of, do_write2) ppg.run() assert read(of) == "sha" # Readding the invariant does trigger again assert read("A") == "3" def test_parameter_dependency(self): of = "out/a" def do_write(of): append(of, "shu" * self.sentinel_count()) job = ppg.FileGeneratingJob(of, do_write) param_dep = ppg.ParameterInvariant("myparam", (1, 2, 3)) job.depends_on(param_dep) ppg.run() assert read(of) == "shu" ppg.new() job = ppg.FileGeneratingJob(of, do_write) param_dep = ppg.ParameterInvariant("myparam", (1, 2, 3)) job.depends_on(param_dep) ppg.run() assert read(of) == "shu" # has not been run again... ppg.new() job = ppg.FileGeneratingJob(of, do_write) param_dep = ppg.ParameterInvariant("myparam", (1, 2, 3, 4)) job.depends_on(param_dep) ppg.run() assert read(of) == "shushu" # has been run again ;). def test_parameter_invariant_adds_hidden_job_id_prefix(self): param = "A" jobA = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", param)) jobB = ppg.ParameterInvariant("out/A", param) jobA.depends_on(jobB) ppg.run() assert read("out/A") == param def test_depends_on_func(self): a = ppg.FileGeneratingJob("out/A", lambda of: write("a")) b, a_again = a.depends_on_func("a123", lambda: 123) assert b.job_id.startswith("FI" + a.job_id + "_") assert ppg.global_pipegraph.has_edge(b, a) assert a_again is a def test_depends_on_file(self): a = ppg.FileGeneratingJob("out/A", lambda of: write("a")) write("shu", "hello") b = a.depends_on_file("shu") assert b.self is a assert ppg.global_pipegraph.has_edge(b.invariant, a) def test_depends_on_params(self): a = ppg.FileGeneratingJob("out/A", lambda of: write("a")) b = a.depends_on_params(23) assert b.invariant.job_id == "PIout/A" # assert b.invariant.parameters == 23 assert ppg.global_pipegraph.has_edge(b.invariant, a) assert b.self is a def test_parameter_invariant_twice_different_values(self): ppg.ParameterInvariant("a", (1, 2, 3)) with pytest.raises(ValueError): ppg.ParameterInvariant("a", (1, 2, 4)) def test_filetime_dependency(self): of = "out/a" def do_write(of): append(of, "shu" * self.sentinel_count()) ftfn = "out/ftdep" write(ftfn, "hello") write(of, "hello") job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert ( read(of) == "shu" ) # job get's run though there is a file, because the FileInvariant was not stored before... ppg.new() job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert read(of) == "shu" # job does not get rerun... time.sleep(1) # so linux actually advances the file time in the next line write(ftfn, "hello") # same content, different time ppg.new() job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert ( read(of) == "shu" ) # job does not get rerun - filetime invariant is now filechecksum invariant... def test_file_did_not_exist(self): ppg.FileInvariant("shu") with pytest.raises(ppg.JobsFailed): ppg.run() assert "did not exist" in str(ppg.global_pipegraph.last_run_result["shu"].error) def test_filechecksum_dependency_raises_on_too_short_a_filename(self): ppg.global_pipegraph.allow_short_filenames = False with pytest.raises(ValueError): ppg.FileInvariant("a") with pytest.raises(ValueError): ppg.FileInvariant("sh") ppg.FileInvariant("shu") def test_filechecksum_dependency(self): of = "out/a" def do_write(of): append(of, "shu" * self.sentinel_count()) ftfn = "out/ftdep" write(ftfn, "hello") # import stat # logging.info('file time after creating %s'% os.stat(ftfn)[stat.ST_MTIME]) write(of, "hello") job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert ( read(of) == "shu" ) # job get's run though there is a file, because the FileInvariant was not stored before... ppg.new() job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert read(of) == "shu" # job does not get rerun... time.sleep(1) # so linux actually advances the file time in the next line # logging.info("NOW REWRITE") write(ftfn, "hello") # same content, different time ppg.new() job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert read(of) == "shu" # job does not get rerun... # time.sleep(1) #we don't care about the time, size should be enough... write(ftfn, "hello world!!") # different time time.sleep(1) # give the file system a second to realize the change. ppg.new() job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert read(of) == "shushu" # job does get rerun def test_input_file_was_renamed(self): of = "out/B" def do_write(of): append(of, "shu" * self.sentinel_count()) ftfn = "out/ftdep" write(ftfn, "hello") # import stat # logging.info('file time after creating %s'% os.stat(ftfn)[stat.ST_MTIME]) write(of, "hello") job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert ( read(of) == "shu" ) # job get's run though there is a file, because the FileInvariant was not stored before... ppg.new() job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert read(of) == "shu" # job does not get rerun... os.mkdir("out/moved_here") shutil.move(ftfn, os.path.join("out/moved_here", "ftdep")) ppg.new() job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(os.path.join("out/moved_here", "ftdep")) job.depends_on(dep) assert read(of) == "shu" # job does not get rerun... ppg.run() assert read(of) == "shu" # job does not get rerun... @pytest.mark.skip() # I have no idea why this was useful. Possibly the PrebuildJobs support? def test_file_invariant_with_md5sum(self): of = "out/a" def do_write(of): append(of, "shu" * self.sentinel_count()) ftfn = "out/ftdep" write(ftfn, "hello") # import stat # logging.info('file time after creating %s'% os.stat(ftfn)[stat.ST_MTIME]) write(of, "hello") job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert ( read(of) == "shu" ) # job get's run though there is a file, because the FileInvariant was not stored before... with open(ftfn + ".md5sum", "wb") as op: op.write(hashlib.md5(b"hello world").hexdigest().encode("utf-8")) write(ftfn, "hello world") # different content t = time.time() # now make os.utime(ftfn, (t, t)) os.utime(ftfn + ".md5sum", (t, t)) time.sleep(1) # give the file system a second to realize the change. ppg.new() job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert ( read(of) == "shushu" ) # job get's run though there is a file, because the md5sum changed. with open(ftfn + ".md5sum", "wb") as op: op.write(hashlib.md5(b"hello world").hexdigest().encode("utf-8")) write(ftfn, "hello") # different content, but the md5sum is stil the same! t = time.time() # now make os.utime(ftfn, (t, t)) os.utime(ftfn + ".md5sum", (t, t)) time.sleep(1) # give the file system a second to realize the change. ppg.new() job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert read(of) == "shushu" # job does not get rerun, md5sum did not change... t = time.time() - 100 # force a file time mismatch os.utime( ftfn, (t, t) ) # I must change the one on the actual file, otherwise the 'size+filetime is the same' optimization bytes me ppg.new() job = ppg.FileGeneratingJob(of, do_write) dep = ppg.FileInvariant(ftfn) job.depends_on(dep) ppg.run() assert ( read(of) == "shushushu" ) # job does get rerun, md5sum and file time mismatch assert os.stat(ftfn)[stat.ST_MTIME] == os.stat(ftfn + ".md5sum")[stat.ST_MTIME] def test_invariant_dumping_on_job_failure(self): def w(of): write("out/A", "A") append("out/B", "B") def func_c(of): append("out/C", "C") func_dep = ppg.FunctionInvariant("func_c", func_c) fg = ppg.FileGeneratingJob("out/A", w, depend_on_function=False) fg.depends_on(func_dep) ppg.run() assert read("out/A") == "A" assert read("out/B") == "B" ppg.new() def func_c1(of): append("out/C", "D") def w2(of): raise ValueError() # so there is an error in a job... func_dep = ppg.FunctionInvariant("func_c", func_c1) # so this invariant changes fg = ppg.FileGeneratingJob( "out/A", w2, depend_on_function=False ) # and this job crashes fg.depends_on(func_dep) with pytest.raises(ppg.JobsFailed): ppg.run() assert not (os.path.exists("out/A")) # since it was removed, and not recreated assert read("out/B") == "B" ppg.new() func_dep = ppg.FunctionInvariant( "func_c", func_c1 ) # no invariant change this time fg = ppg.FileGeneratingJob( "out/A", w, depend_on_function=False ) # but this was not done the last time... fg.depends_on(func_dep) ppg.run() assert read("out/A") == "A" assert read("out/B") == "BB" def test_invariant_dumping_on_graph_exception(self, mocker): # when an exception occurs not within a job # but within the pipegraph itself (e.g. when the user hit's CTRL-C # during history dumping # which we simulate here import pickle def w(of): write("out/A", "A") append("out/B", "B") def func_c(of): append("out/C", "C") func_dep = ppg.FunctionInvariant("func_c", func_c) fg = ppg.FileGeneratingJob("out/A", w, depend_on_function=False) fg.depends_on(func_dep) ppg.run() assert read("out/A") == "A" assert read("out/B") == "B" ppg.new(run_mode=ppg.RunMode.CONSOLE) # ppg.new() def func_c1(of): append("out/C", "D") def w2(of): write("out/A", "A2") raise ValueError() # so there is an error in a job... func_dep = ppg.FunctionInvariant("func_c", func_c1) # so this invariant changes fg = ppg.FileGeneratingJob( "out/A", w2, depend_on_function=False ) # and this job crashes fg.depends_on(func_dep) # so a get's deleted, and rebuild fg2 = ppg.FileGeneratingJob( "out/C", lambda of: counter("out/c") and append(of, "C") ) old_pickle_dumps = pickle.dumps raised_ki = [False] def new_pickle_dump(obj, protocol=None): if obj == "out/A" and not raised_ki[0]: raised_ki[0] = True raise KeyboardInterrupt("simulated") else: return old_pickle_dumps(obj, protocol) mocker.patch("pickle.dumps", new_pickle_dump) ki_raised = False assert not hasattr(ppg.global_pipegraph, "last_run_result") with pytest.raises(ppg.JobsFailed): ppg.run() assert isinstance(ppg.global_pipegraph.do_raise[0], KeyboardInterrupt) assert len(ppg.global_pipegraph.do_raise) == 2 assert hasattr(ppg.global_pipegraph, "last_run_result") assert os.path.exists("out/A") # The file get's written. assert read("out/B") == "B" assert read("out/C") == "C" assert read("out/c") == "1" # mocker.stopall() ppg.new() func_dep = ppg.FunctionInvariant( "func_c", func_c1 ) # no invariant change this time # but we had no stored input/output for A, right? # so it get's rerun fg = ppg.FileGeneratingJob( "out/A", w, depend_on_function=False ) # but this was not done the last time... fg.depends_on(func_dep) fg2 = ppg.FileGeneratingJob( "out/C", lambda of: counter("out/c") and append(of, "C") ) ppg.run() assert read("out/A") == "A" assert read("out/B") == "BB" assert read("out/C") == "C" # assert read("out/c") == "1" # c did not get rerun def test_sig_int_is_ignored_in_console_mode(self): ppg.new(run_mode=ppg.RunMode.CONSOLE) def sigint(): import signal counter("a") os.kill(os.getpid(), signal.SIGINT) counter("A") job = ppg.DataLoadingJob("A", sigint) force_load(job) ppg.run() assert read("a") == "1" assert read("A") == "1" def test_input_output_dumping_dies_for_some_reason(self, ppg2_per_test, mocker): import pickle raised_ki = [False] old_pickle_dumps = pickle.dumps def new_pickle_dump(obj, protocol=None): if obj == "A" and not raised_ki[0]: raised_ki[0] = True raise ValueError("simulated") else: return old_pickle_dumps(obj, protocol) mocker.patch("pickle.dumps", new_pickle_dump) ppg.FileGeneratingJob("A", lambda of: counter("a") and write(of, "A")) ppg.FileGeneratingJob("B", lambda of: counter("b") and write(of, "B")) with pytest.raises(ppg.RunFailedInternally): ppg.run() assert read("A") == "A" assert read("B") == "B" assert read("a") == "1" assert read("b") == "1" ppg.run() assert read("A") == "A" assert read("B") == "B" assert read("a") == "2" assert read("b") == "1" # we had captured B so it's all good def test_FileInvariant_cant_have_dependencies(self): # invariants are always roots of the DAG - they can't have any dependencies themselves write("out/shu", "shu") job = ppg.FileInvariant("out/shu") jobB = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "a")) with pytest.raises(ppg.JobContractError): job.depends_on(jobB) def test_FunctionInvariant_cant_have_dependencies(self): # invariants are always roots of the DAG - they can't have any dependencies themselves job = ppg.FunctionInvariant("shu", lambda: 55) jobB = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "a")) with pytest.raises(ppg.JobContractError): job.depends_on(jobB) def test_ParameterInvariant_cant_have_dependencies(self): # invariants are always roots of the DAG - they can't have any dependencies themselves job = ppg.ParameterInvariant("out/shu", ("123",)) jobB = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "a")) with pytest.raises(ppg.JobContractError): job.depends_on(jobB) def test_invariant_loading_issues_on_value_catastrophic(self): a = ppg.DataLoadingJob("a", lambda: 5) b = ppg.FileGeneratingJob( "out/b", lambda of: write("out/b", "b"), depend_on_function=False ) b.depends_on(a) write("out/b", "a") import pickle Path(ppg.global_pipegraph.get_history_filename()).parent.mkdir(parents=True) with gzip.GzipFile(ppg.global_pipegraph.get_history_filename(), "wb") as op: pickle.dump(a.job_id, op, pickle.HIGHEST_PROTOCOL) op.write(b"This breaks") with pytest.raises(ppg.JobsFailed): ppg.run() assert read("out/b") == "a" # job was not run def test_invariant_loading_issues_on_value_undepickableclass(self): import tempfile import pickle # make sure Undepickable is Undepickable with tempfile.TemporaryFile("wb+") as tf: o = Undepickable() pickle.dump(o, tf, pickle.HIGHEST_PROTOCOL) with pytest.raises(pickle.UnpicklingError): tf.seek(0, 0) pickle.load(tf) a = ppg.ParameterInvariant("a", 5) b = ppg.FileGeneratingJob( "out/b", lambda of: write("out/b", "b"), depend_on_function=False ) c = ppg.ParameterInvariant("c", 23) b.depends_on(a) write("out/b", "a") Path(ppg.global_pipegraph.get_history_filename()).parent.mkdir(parents=True) with gzip.GzipFile(ppg.global_pipegraph.get_history_filename(), "wb") as op: pickle.dump(a.job_id, op, pickle.HIGHEST_PROTOCOL) pickle.dump(Undepickable(), op, pickle.HIGHEST_PROTOCOL) pickle.dump(c.job_id, op, pickle.HIGHEST_PROTOCOL) pickle.dump(({}, {"c": str(c.parameters)}), op, pickle.HIGHEST_PROTOCOL) with pytest.raises(ppg.JobsFailed): ppg.run() assert read("out/b") == "b" # job was run # assert a.job_id in ppg.global_pipegraph.invariant_loading_issues # assert ppg.global_pipegraph.invariant_status["PIc"] == 23 def test_invariant_loading_issues_on_key(self): a = ppg.DataLoadingJob("a", lambda: 5) b = ppg.FileGeneratingJob( "out/b", lambda of: write("out/b", "b"), depend_on_function=False ) b.depends_on(a) write("out/b", "a") Path(ppg.global_pipegraph.get_history_filename()).parent.mkdir(parents=True) with gzip.GzipFile(ppg.global_pipegraph.get_history_filename(), "wb") as op: op.write(b"key breaks already") op.write(b"This breaks") with pytest.raises(ppg.JobsFailed): ppg.run() assert read("out/b") == "a" # job was not run def test_file_invariant_swapping(self, ppg2_per_test): Path("a").write_text("a") Path("b").write_text("b") def out(of): counter("counter") of.write_text(Path("a").read_text() + Path("b").read_text()), job = ppg.FileGeneratingJob("c", out, depend_on_function=False) job.depends_on_file("a") job.depends_on_file("b") ppg.run() assert read("c") == "ab" assert read("counter") == "1" ppg.run() assert read("counter") == "1" ppg2_per_test.new() job = ppg.FileGeneratingJob("c", out, depend_on_function=False) job.depends_on_file("b") job.depends_on_file("a") ppg.run() assert read("counter") == "1" def test_file_invariant_replaced(self): Path("a.tsv").write_text("a") a = ppg.FileInvariant("a.tsv") def func(of): counter("J") of.write_text("j") j = ppg.FileGeneratingJob("j", func) j.depends_on(a) ppg.run() assert read("j") == "j" assert read("J") == "1" ppg.run() assert read("J") == "1" ppg.new() Path("b.tsv").write_text("b") b = ppg.FileInvariant("b.tsv") j = ppg.FileGeneratingJob("j", func) j.depends_on(b) ppg.run() assert read("J") == "2" def first_value(d): return list(d.values())[0] @pytest.mark.usefixtures("ppg2_per_test") class TestFunctionInvariant: # most of the function invariant testing is handled by other test classes. # but these are more specialized. def test_generator_expressions(self): def get_func(r): def shu(): return sum(i + 0 for i in r) return shu def get_func2(r): def shu(): return sum(i + 0 for i in r) return shu def get_func3(r): def shu(): return sum(i + 1 for i in r) return shu a = ppg.FunctionInvariant("a", get_func(100)) b = ppg.FunctionInvariant( "b", get_func2(100) ) # that invariant should be the same c = ppg.FunctionInvariant( "c", get_func3(100) ) # and this invariant should be different av = a.run(None, None) bv = b.run(None, None) cv = c.run(None, None) assert a.run(None, None) assert ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(bv) ) assert not ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(cv) ) def test_lambdas(self): def get_func(x): def inner(): arg = lambda y: x + x + x # noqa:E731 return arg(1) return inner def get_func2(x): def inner(): arg = lambda y: x + x + x # noqa:E731 return arg(1) return inner def get_func3(x): def inner(): arg = lambda y: x + x # noqa:E731 return arg(1) return inner a = ppg.FunctionInvariant("a", get_func(100)) b = ppg.FunctionInvariant( "b", get_func2(100) ) # that invariant should be the same c = ppg.FunctionInvariant( "c", get_func3(100) ) # and this invariant should be different av = a.run(None, None) bv = b.run(None, None) cv = c.run(None, None) self.maxDiff = 20000 assert a.run(None, None) assert ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(bv) ) assert not ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(cv) ) def test_inner_functions(self): def get_func(x): def inner(): return 23 return inner def get_func2(x): def inner(): return 23 return inner def get_func3(x): def inner(): return 23 + 5 return inner a = ppg.FunctionInvariant("a", get_func(100)) b = ppg.FunctionInvariant( "b", get_func2(100) ) # that invariant should be the same c = ppg.FunctionInvariant( "c", get_func3(100) ) # and this invariant should be different av = a.run(None, None) bv = b.run(None, None) cv = c.run(None, None) assert a.run(None, None) assert ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(bv) ) assert not ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(cv) ) def test_nested_inner_functions(self): def get_func(x): def inner(): def shu(): return 23 return shu return inner def get_func2(x): def inner(): def shu(): return 23 return shu return inner def get_func3(x): def inner(): def shu(): return 23 + 5 return shu return inner a = ppg.FunctionInvariant("a", get_func(100)) b = ppg.FunctionInvariant( "b", get_func2(100) ) # that invariant should be the same c = ppg.FunctionInvariant( "c", get_func3(100) ) # and this invariant should be different av = a.run(None, None) bv = b.run(None, None) cv = c.run(None, None) assert a.run(None, None) assert ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(bv) ) assert not ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(cv) ) def test_inner_functions_with_parameters(self): def get_func(x): def inner(): return x return inner a = ppg.FunctionInvariant("a", get_func(100)) b = ppg.FunctionInvariant( "b", get_func(100) ) # that invariant should be the same c = ppg.FunctionInvariant( "c", get_func(2000) ) # and this invariant should be different av = a.run(None, None) bv = b.run(None, None) cv = c.run(None, None) assert a.run(None, None) assert ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(bv) ) assert not ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(cv) ) def test_passing_non_function_raises(self): with pytest.raises(TypeError): ppg.FunctionInvariant("out/a", "shu") def test_passing_none_as_function_is_ok(self, create_out_dir): job = ppg.FunctionInvariant("out/a", None) str(job) jobB = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "A")) jobB.depends_on(job) ppg.run() assert read("out/A") == "A" def test_passing_non_string_as_jobid(self): with pytest.raises(TypeError): ppg.FunctionInvariant(5, lambda: 1) def test_cant_have_dependencies(self): # invariants are always roots of the DAG - they can't have any dependencies themselves def shu(): pass job = ppg.FunctionInvariant("shu", shu) jobB = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "a")) with pytest.raises(ppg.JobContractError): job.depends_on(jobB) def test_raises_on_duplicate_with_different_functions(self): def shu(): return "a" ppg.FunctionInvariant("A", shu) ppg.FunctionInvariant("A", shu) # ok. with pytest.raises(ppg.JobRedefinitionError): ppg.FunctionInvariant("A", lambda: "b") # raises ValueError def sha(): def shu(): return "b" return shu ppg.FunctionInvariant("B", sha()) ppg.FunctionInvariant("B", sha()) def test_instance_functions_ok(self, create_out_dir): class shu: def __init__(self, letter): self.letter = letter def get_job(self): job = ppg.FileGeneratingJob( "out/" + self.letter, lambda of: append(of, "A") ) job.depends_on(ppg.FunctionInvariant("shu.sha", self.sha)) return job def sha(self): return 55 * 23 x = shu("A") x.get_job() ppg.run() assert read("out/A") == "A" append("out/A", "A") ppg.new() x.get_job() y = shu("B") j1 = y.get_job() j2 = y.get_job() assert ppg.FunctionInvariant.functions_equal( j1.generating_function, j2.generating_function ) # assert j1 is j2 # todo: interactive/notebook differences def test_buildin_function(self): a = ppg.FunctionInvariant("a", open) assert "<built-in" in str(a) def test_function_invariant_non_function(self): class CallMe: def __call__(self): raise ValueError() a = ppg.FunctionInvariant("a", CallMe) with pytest.raises( ValueError ): # todo: is this the right behaviour? can't we just forward to __call__ as the invariant? a.run(None, None) def test_closure_capturing(self): def func(da_list): def f(): return da_list return f a = ppg.FunctionInvariant("a", func([1, 2, 3])) b = ppg.FunctionInvariant( "b", func([1, 2, 3]) ) # that invariant should be the same c = ppg.FunctionInvariant( "c", func([1, 2, 3, 4]) ) # and this invariant should be different av = a.run(None, None) bv = b.run(None, None) cv = c.run(None, None) assert a.run(None, None) assert ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(bv) ) assert not ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(cv) ) def test_function_to_str_builtin(self): assert ppg.FunctionInvariant.function_to_str(open) == "<built-in function open>" def test_closure_capturing_dict(self): def func(da_list): def f(): return da_list return f a = ppg.FunctionInvariant("a", func({"1": "a", "3": "b", "2": "c"})) b = ppg.FunctionInvariant( "b", func({"1": "a", "3": "b", "2": "c"}) ) # that invariant should be the same c = ppg.FunctionInvariant( "c", func({"1": "a", "3": "b", "2": "d"}) ) # and this invariant should be different av = a.run(None, None) bv = b.run(None, None) cv = c.run(None, None) assert a.run(None, None) assert ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(bv) ) assert not ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(cv) ) def test_closure_capturing_set(self): def func(da_list): def f(): return da_list return f import random x = set(["1", "2", "3", "4", "5", "6", "7", "8"]) a = ppg.FunctionInvariant("a", func(x)) x2 = list(x) random.shuffle(x2) x2 = set(x2) b = ppg.FunctionInvariant("b", func(x2)) # that invariant should be the same c = ppg.FunctionInvariant( "c", func({"3", "2"}) ) # and this invariant should be different av = a.run(None, None) bv = b.run(None, None) cv = c.run(None, None) assert a.run(None, None) assert ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(bv) ) assert not ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(cv) ) def test_closure_capturing_frozen_set(self): def func(da_list): def f(): return da_list return f import random x = frozenset(["1", "2", "3", "4", "5", "6", "7", "8"]) a = ppg.FunctionInvariant("a", func(x)) x2 = list(x) random.shuffle(x2) x2 = frozenset(x2) b = ppg.FunctionInvariant("b", func(x2)) # that invariant should be the same c = ppg.FunctionInvariant( "c", func(frozenset({"3", "2"})) ) # and this invariant should be different av = a.run(None, None) bv = b.run(None, None) cv = c.run(None, None) assert a.run(None, None) assert ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(bv) ) assert not ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(cv) ) def test_function_invariants_are_equal_if_dis_identical_or_source_identical(self): python_version = (3, 99) a = {"source": "hello", python_version: ("dis", "closure")} b = a.copy() b["source"] = "hello_world" c = a.copy() c[python_version] = ("disB", "closure") assert ppg.FunctionInvariant.compare_hashes(None, a, a, python_version) assert ppg.FunctionInvariant.compare_hashes( None, a, b, python_version ) # same dis ,different source assert not ppg.FunctionInvariant.compare_hashes( None, a, c, python_version ) # different dis, same source def test_source_file_mtime_change_without_hash_change(self): import sys def inner(): pass python_version = tuple(sys.version_info)[:2] # we only care about major.minor a = ppg.FunctionInvariant("a", inner) calc = a.run(None, None) changed = calc.copy() changed["FIa"]["source_file"]["mtime"] = -1 changed["FIa"]["source_file"]["dis"] = "find me" calc2 = a.run(None, changed) assert calc2["FIa"]["source_file"]["dis"] == "find me" @pytest.mark.usefixtures("create_out_dir") @pytest.mark.usefixtures("ppg2_per_test") class TestDependency: def test_simple_chain(self): o = Dummy() def load_a(): return "shu" jobA = ppg.AttributeLoadingJob("a", o, "myattr", load_a) ofB = "out/B" def do_write_b(ofB): write(ofB, o.myattr) jobB = ppg.FileGeneratingJob(ofB, do_write_b).depends_on(jobA) ofC = "out/C" def do_write_C(ofC): write(ofC, o.myattr) ppg.FileGeneratingJob(ofC, do_write_C).depends_on(jobA) ofD = "out/D" def do_write_d(ofD): write(ofD, read(ofC) + read(ofB)) ppg.FileGeneratingJob(ofD, do_write_d).depends_on([jobA, jobB]) def test_failed_job_kills_those_after(self): ofA = "out/A" def write_a(ofA): append(ofA, "hello") jobA = ppg.FileGeneratingJob(ofA, write_a) ofB = "out/B" def write_b(ofB): raise ValueError("shu") jobB = ppg.FileGeneratingJob(ofB, write_b) jobB.depends_on(jobA) ofC = "out/C" def write_c(ofC): write(ofC, "hello") jobC = ppg.FileGeneratingJob(ofC, write_c) jobC.depends_on(jobB) with pytest.raises(ppg.JobsFailed): ppg.run() assert os.path.exists(ofA) # which was before the error assert not (os.path.exists(ofB)) # which was on the error assert not (os.path.exists(ofC)) # which was after the error ppg.new() jobA = ppg.FileGeneratingJob(ofA, write_a) jobC = ppg.FileGeneratingJob(ofC, write_c) def write_b_ok(ofB): write(ofB, "BB") jobB = ppg.FileGeneratingJob(ofB, write_b_ok) jobB.depends_on(jobA) jobC.depends_on(jobB) ppg.run() assert os.path.exists(ofA) assert read(ofA) == "hello" # run only once! assert os.path.exists(ofB) assert os.path.exists(ofC) def test_done_filejob_does_not_gum_up_execution(self): ofA = "out/A" write(ofA, "1111") def write_a(ofA): append(ofA, "hello") jobA = ppg.FileGeneratingJob(ofA, write_a, depend_on_function=False) ofB = "out/B" def write_b(ofB): append(ofB, "hello") jobB = ppg.FileGeneratingJob(ofB, write_b) jobB.depends_on(jobA) ofC = "out/C" def write_c(ofC): write(ofC, "hello") jobC = ppg.FileGeneratingJob(ofC, write_c) jobC.depends_on(jobB) assert os.path.exists(ofA) ppg.run() assert os.path.exists(ofB) assert os.path.exists(ofC) assert ( read(ofA) == "hello" ) # change from ppgA, if it's not our file (we have recorded not output), rerun def test_invariant_violation_redoes_deps_but_not_nondeps(self): def get_job(name): fn = "out/" + name def do_write(of): if os.path.exists(fn + ".sentinel"): d = read(fn + ".sentinel") else: d = "" append(fn + ".sentinel", name) # get's longer all the time... write(fn, d + name) # get's deleted anyhow... return ppg.FileGeneratingJob(fn, do_write) jobA = get_job("A") jobB = get_job("B") jobC = get_job("C") get_job("D") jobC.depends_on(jobB) jobB.depends_on(jobA) dep = ppg.ParameterInvariant("myparam", ("hello",)) jobA.depends_on(dep) ppg.run() assert read("out/A") == "A" assert read("out/B") == "B" assert read("out/C") == "C" ppg.new() jobA = get_job("A") jobB = get_job("B") jobC = get_job("C") get_job("D") jobC.depends_on(jobB) jobB.depends_on(jobA) dep = ppg.ParameterInvariant("myparam", ("hello stranger",)) jobA.depends_on(dep) # now, the invariant has been changed, all jobs rerun... ppg.run() assert read("out/A") == "AA" # thanks to our smart rerun aware job definition.. assert read("out/B") == "BB" assert read("out/C") == "CC" assert read("out/D") == "D" # since that one does not to be rerun... def test_depends_on_accepts_a_list(self): jobA = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "A")) jobB = ppg.FileGeneratingJob("out/B", lambda of: write("out/B", "B")) jobC = ppg.FileGeneratingJob("out/C", lambda of: write("out/C", "C")) jobC.depends_on([jobA, jobB]) ppg.run() assert read("out/A") == "A" assert read("out/B") == "B" assert read("out/C") == "C" def test_job_iter(self): jobA = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "A")) l = list(iter(jobA)) assert l[0] is jobA def test_depends_on_accepts_multiple_values(self): jobA = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "A")) jobB = ppg.FileGeneratingJob("out/B", lambda of: write("out/B", "B")) jobC = ppg.FileGeneratingJob("out/C", lambda of: write("out/C", "C")) jobC.depends_on(jobA, jobB) ppg.run() assert read("out/A") == "A" assert read("out/B") == "B" assert read("out/C") == "C" def test_depends_on_accepts_multiple_values_mixed(self): jobA = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "A")) jobB = ppg.FileGeneratingJob("out/B", lambda of: write("out/B", "B")) jobC = ppg.FileGeneratingJob("out/C", lambda of: write("out/C", "C")) jobC.depends_on(jobA, [jobB]) ppg.run() assert read("out/A") == "A" assert read("out/B") == "B" assert read("out/C") == "C" def test_depends_on_none_ignored(self): jobA = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "A")) jobB = ppg.FileGeneratingJob("out/B", lambda of: write("out/B", "B")) jobC = ppg.FileGeneratingJob("out/C", lambda of: write("out/C", "C")) jobC.depends_on(jobA, [jobB], None, [None]) jobC.depends_on(None) jobC.depends_on() # that's a no-op as well jobC.depends_on([]) # that's a no-op as well ppg.run() assert read("out/A") == "A" assert read("out/B") == "B" assert read("out/C") == "C" def test_depends_on_excludes_on_non_jobs(self): jobA = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "A")) with pytest.raises(KeyError): jobA.depends_on("SHU") def test_depends_on_instant_cycle_check(self): jobA = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "A")) jobB = ppg.FileGeneratingJob("out/b", lambda of: write("out/B", "b")) jobB.depends_on(jobA) with pytest.raises(ppg.NotADag): jobA.depends_on(jobA) with pytest.raises(ppg.NotADag): jobA.depends_on(jobB) def test_depends_on_accepts_a_list_of_lists(self): jobA = ppg.FileGeneratingJob("out/A", lambda of: write("out/A", "A")) jobB = ppg.FileGeneratingJob("out/B", lambda of: write("out/B", "B")) jobC = ppg.FileGeneratingJob( "out/C", lambda of: write("out/C", read("out/A") + read("out/B") + read("out/D")), ) jobD = ppg.FileGeneratingJob("out/D", lambda of: write("out/D", "D")) jobC.depends_on([jobA, [jobB, jobD]]) assert ppg.global_pipegraph.has_edge(jobD, jobC) assert ppg.global_pipegraph.has_edge(jobA, jobC) assert ppg.global_pipegraph.has_edge(jobB, jobC) ppg.run() assert read("out/A") == "A" assert read("out/B") == "B" assert read("out/C") == "ABD" assert read("out/D") == "D" def test_invariant_job_depends_on_raises(self): with pytest.raises(ppg.JobContractError): ppg.jobs._InvariantMixin().depends_on(ppg.Job(["B"])) def test_cached_job_depends_on(self): class Dummy: pass o = Dummy() jobA = ppg.CachedAttributeLoadingJob("cache/A", o, "a", lambda: 23) jobB = ppg.Job(["B"]) jobC = ppg.Job(["C"]) jobD = ppg.Job(["D"]) jobA.calc.depends_on([jobB], jobC, jobD) assert not ppg.global_pipegraph.has_edge(jobB, jobA.load) assert not ppg.global_pipegraph.has_edge(jobC, jobA.load) assert not ppg.global_pipegraph.has_edge(jobD, jobA.load) assert ppg.global_pipegraph.has_edge(jobB, jobA.calc) assert ppg.global_pipegraph.has_edge(jobC, jobA.calc) assert ppg.global_pipegraph.has_edge(jobD, jobA.calc) def test_dependency_placeholder(self): jobA = ppg.FileGeneratingJob( "out/A", lambda of: write("out/A", "A" + read("out/B")) ) jobB = ppg.FileGeneratingJob("out/B", lambda of: write("out/B", "B")) def gen_deps(): logger.info("gen deps called") return [jobB] jobA.depends_on(gen_deps) ppg.run() assert read("out/A") == "AB" def test_dependency_placeholder2(self): jobA = ppg.FileGeneratingJob( "out/A", lambda of: write("out/A", "A" + read("out/B")) ) def gen_deps(): return ppg.FileGeneratingJob("out/B", lambda of: write("out/B", "B")) jobA.depends_on(gen_deps) ppg.run() assert read("out/A") == "AB" def test_dependency_placeholder_nested(self): jobA = ppg.FileGeneratingJob( "out/A", lambda of: write("out/A", "A" + read("out/B") + read("out/C")) ) def gen_deps2(): return ppg.FileGeneratingJob("out/C", lambda of: write("out/C", "C")) def gen_deps(): return ppg.FileGeneratingJob( "out/B", lambda of: write("out/B", "B") ).depends_on(gen_deps2) jobA.depends_on(gen_deps) ppg.run() assert read("out/A") == "ABC" def test_dependency_placeholder_dynamic_auto_invariants(self): jobA = ppg.FileGeneratingJob( "out/A", lambda of: write("out/A", "A" + read("out/B")) ) def check_function_invariant(of): write("out/B", "B") assert ( "FITestDependency.test_dependency_placeholder_dynamic_auto_invariants.<locals>.check_function_invariant" in ppg.global_pipegraph.jobs ) def gen_deps(): jobB = ppg.FileGeneratingJob("out/B", check_function_invariant) print("gen deps called") return [jobB] jobA.depends_on(gen_deps) assert "FIout/B" not in ppg.global_pipegraph.jobs ppg.run() assert read("out/A") == "AB" @pytest.mark.usefixtures("ppg2_per_test") class TestDefinitionErrors: def test_defining_function_invariant_twice(self): a = lambda: 55 # noqa:E731 b = lambda: 66 # noqa:E731 ppg.FunctionInvariant("a", a) ppg.FunctionInvariant("a", a) # that's ok... with pytest.raises(ppg.JobRedefinitionError): ppg.FunctionInvariant("a", b) ppg.new(run_mode=ppg.RunMode.NOTEBOOK) ppg.FunctionInvariant("a", a) j = ppg.FunctionInvariant("a", b) assert j.function is b def test_defining_function_and_parameter_invariant_with_same_name(self): # you can't really, FunctionInvariants are Prefixed with FI, ParameterInvariant with PI a = lambda: 55 # noqa:E731 ppg.FunctionInvariant("PIa", a) ppg.ParameterInvariant("a", "b") def test_defining_function_and_parameter_invariant_with_same_name_reversed(self): a = lambda: 55 # noqa:E731 ppg.ParameterInvariant("a", "b") ppg.FunctionInvariant("PIa", a) def test_parameter_invariant_does_not_accept_function(self): with pytest.raises(TypeError): ppg.ParameterInvariant("a", lambda: 55) @pytest.mark.usefixtures("ppg2_per_test") class TestFunctionInvariantDisChanges_BetweenVersions: def test_function_name_is_irrelevant(self): def test_a(): return 55 def test_b(): return 55 def test_c(): return 56 a = ppg.FunctionInvariant("a", test_a) b = ppg.FunctionInvariant("b", test_b) c = ppg.FunctionInvariant("c", test_c) av = a.run(None, None) bv = b.run(None, None) cv = c.run(None, None) assert ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(bv) ) assert not ppg.FunctionInvariant.compare_hashes( None, first_value(av), first_value(cv) ) def test_docstring_is_irrelevant(self): def test(): """A""" return 55 a = ppg.FunctionInvariant("a", test) # fmt: off def test(): '''B''' return 55 # fmt: on b = ppg.FunctionInvariant("b", test) def test(): "c" return 56 c = ppg.FunctionInvariant("c", test) def test(): "c" return 56 d = ppg.FunctionInvariant("d", test) av = first_value(a.run(None, None)) bv = first_value(b.run(None, None)) cv = first_value(c.run(None, None)) dv = first_value(d.run(None, None)) assert ppg.FunctionInvariant.compare_hashes(None, (av), (bv)) assert ppg.FunctionInvariant.compare_hashes(None, (cv), (dv)) assert not ppg.FunctionInvariant.compare_hashes(None, (av), (cv))
33.033752
120
0.564892
7e4582246ed0faad1c3ef763653d69a41ec247f7
2,076
py
Python
src/python/chaste/core/__init__.py
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-02-04T16:10:53.000Z
2021-07-01T08:03:16.000Z
src/python/chaste/core/__init__.py
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-06-22T08:50:41.000Z
2019-12-15T20:17:29.000Z
src/python/chaste/core/__init__.py
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
3
2017-05-15T21:33:58.000Z
2019-10-27T21:43:07.000Z
#!/usr/bin/env python """Core Module """ __copyright__ = """Copyright (c) 2005-2019, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import warnings # At the moment there are many harmless duplicate registration warnings from boost python. Ignore them until a suitable # way to avoid duplicate registration during wrapper building is found. warnings.filterwarnings("ignore") from chaste.core._chaste_project_PyChaste_core import *
48.27907
119
0.80395
781076b1e4a912f380372b14564f4840db435ada
316
py
Python
paradise/config/docs.py
pfrydlewicz/paradise
bdd2597d259ab7313a140d82de4afce5961b0cb6
[ "MIT" ]
null
null
null
paradise/config/docs.py
pfrydlewicz/paradise
bdd2597d259ab7313a140d82de4afce5961b0cb6
[ "MIT" ]
null
null
null
paradise/config/docs.py
pfrydlewicz/paradise
bdd2597d259ab7313a140d82de4afce5961b0cb6
[ "MIT" ]
null
null
null
""" Configuration for docs """ # source_link = "https://github.com/[org_name]/paradise" # docs_base_url = "https://[org_name].github.io/paradise" # headline = "App that does everything" # sub_heading = "Yes, you got that right the first time, everything" def get_context(context): context.brand_html = "Paradise"
26.333333
68
0.724684
6bd4c8c3fe44ecff059c89fc525dae97a0f4465f
1,305
py
Python
element_feature.py
jingshenSN2/HOIP_bandgap_prediction
fc989c47e20d98490d7d9679cb6f9a6b2b0b9ebc
[ "MIT" ]
4
2020-01-05T09:41:07.000Z
2020-11-04T17:42:19.000Z
element_feature.py
NurcanOrmanli/HOIP_bandgap_prediction
fc989c47e20d98490d7d9679cb6f9a6b2b0b9ebc
[ "MIT" ]
null
null
null
element_feature.py
NurcanOrmanli/HOIP_bandgap_prediction
fc989c47e20d98490d7d9679cb6f9a6b2b0b9ebc
[ "MIT" ]
5
2020-02-19T07:26:41.000Z
2021-09-12T21:18:52.000Z
import pandas as pd def __add_formula(df): formula_list = [] for i in range(len(df)): row = df.iloc[i] abx = str(row['A-site']) + str(row['B-site']) + str(row['X-site']) formula_list.append(abx) df['formula'] = formula_list return df def raw_drop_duplicates(): df = __add_formula(pd.read_csv('HOIP-30.csv', header=0)) df = df.drop_duplicates('formula') df.drop(['formula'], axis=1, inplace=True) df.to_csv('HOIP-30_drop.csv', index=False) def element_feature(): df = pd.read_csv('HOIP-30_drop.csv', header=0) dfA = df[['A-site', 'r_A.eff', 'P_A', 'A_HOMO', 'A_LUMO']] dfB = df[['B-site', 'χ_B', 'r_B_s+p', 'r_B', 'IE_B', 'P_B', 'EA_B', 'IC_B', '1st_IP_B', 'VE_B', 'B_d-electron', 'B_p-electron', 'B_s-electron', 'B_f-electron']] dfX = df[['X-site', 'X_p-electron', '1st_IP_X', 'χ_X', 'P_X', 'IC_X', 'r_X_s+p', 'r_X', 'X_s-electron', 'EA_X', 'X_d-electron', 'X_f-electron']] dfA1 = dfA.drop_duplicates('A-site').sort_values('r_A.eff') dfB1 = dfB.drop_duplicates('B-site').sort_values('B-site') dfX1 = dfX.drop_duplicates('X-site').sort_values('IC_X') dfA1.to_csv('A_feature.csv', index=False) dfB1.to_csv('B_feature.csv', index=False) dfX1.to_csv('X_feature.csv', index=False)
39.545455
115
0.607663
a0b91356b9038b976a391c25d3cbe13662ff460e
12,109
py
Python
setup.py
ContextLogic/sqlalchemy
b7adfe5e4d9baa61169ba79aa5ba8f64f0ff7645
[ "MIT" ]
null
null
null
setup.py
ContextLogic/sqlalchemy
b7adfe5e4d9baa61169ba79aa5ba8f64f0ff7645
[ "MIT" ]
null
null
null
setup.py
ContextLogic/sqlalchemy
b7adfe5e4d9baa61169ba79aa5ba8f64f0ff7645
[ "MIT" ]
1
2021-06-23T09:02:32.000Z
2021-06-23T09:02:32.000Z
"""setup.py Please see README for basic installation instructions. """ import os import re import sys from distutils.command.build_ext import build_ext from distutils.errors import (CCompilerError, DistutilsExecError, DistutilsPlatformError) try: from setuptools import setup, Extension, Feature has_setuptools = True except ImportError: has_setuptools = False from distutils.core import setup, Extension Feature = None try: # Python 3 from distutils.command.build_py import build_py_2to3 as build_py except ImportError: # Python 2 from distutils.command.build_py import build_py cmdclass = {} pypy = hasattr(sys, 'pypy_version_info') jython = sys.platform.startswith('java') py3k = False extra = {} if sys.version_info < (2, 4): raise Exception("SQLAlchemy requires Python 2.4 or higher.") elif sys.version_info >= (3, 0): py3k = True # monkeypatch our preprocessor # onto the 2to3 tool. from sa2to3 import refactor_string from lib2to3.refactor import RefactoringTool RefactoringTool.refactor_string = refactor_string if has_setuptools: extra.update( use_2to3=True, ) else: cmdclass['build_py'] = build_py ext_modules = [ Extension('sqlalchemy.cprocessors', sources=['lib/sqlalchemy/cextension/processors.c']), Extension('sqlalchemy.cresultproxy', sources=['lib/sqlalchemy/cextension/resultproxy.c']) ] ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError) if sys.platform == 'win32' and sys.version_info > (2, 6): # 2.6's distutils.msvc9compiler can raise an IOError when failing to # find the compiler ext_errors += (IOError,) class BuildFailed(Exception): def __init__(self): self.cause = sys.exc_info()[1] # work around py 2/3 different syntax class ve_build_ext(build_ext): # This class allows C extension building to fail. def run(self): try: build_ext.run(self) except DistutilsPlatformError: raise BuildFailed() def build_extension(self, ext): try: build_ext.build_extension(self, ext) except ext_errors: raise BuildFailed() except ValueError: # this can happen on Windows 64 bit, see Python issue 7511 if "'path'" in str(sys.exc_info()[1]): # works with both py 2/3 raise BuildFailed() raise cmdclass['build_ext'] = ve_build_ext def status_msgs(*msgs): print('*' * 75) for msg in msgs: print(msg) print('*' * 75) def find_packages(dir_): packages = [] for pkg in ['sqlalchemy']: for _dir, subdirectories, files in ( os.walk(os.path.join(dir_, pkg)) ): if '__init__.py' in files: lib, fragment = _dir.split(os.sep, 1) packages.append(fragment.replace(os.sep, '.')) return packages v = open(os.path.join(os.path.dirname(__file__), 'lib', 'sqlalchemy', '__init__.py')) VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1) v.close() def run_setup(with_cext): kwargs = extra.copy() if with_cext: if Feature: kwargs['features'] = {'cextensions': Feature( "optional C speed-enhancements", standard=True, ext_modules=ext_modules )} else: kwargs['ext_modules'] = ext_modules setup(name="SQLAlchemy", version=VERSION, description="Database Abstraction Library", author="Mike Bayer", author_email="mike_mp@zzzcomputing.com", url="http://www.sqlalchemy.org", packages=find_packages('lib'), package_dir={'': 'lib'}, license="MIT License", cmdclass=cmdclass, tests_require=['nose >= 0.11'], test_suite="sqla_nose", long_description="""\ SQLAlchemy is: * The Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. SQLAlchemy provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language. * extremely easy to use for all the basic tasks, such as: accessing pooled connections, constructing SQL from Python expressions, finding object instances, and commiting object modifications back to the database. * powerful enough for complicated tasks, such as: eager load a graph of objects and their dependencies via joins; map recursive adjacency structures automatically; map objects to not just tables but to any arbitrary join or select statement; combine multiple tables together to load whole sets of otherwise unrelated objects from a single result set; commit entire graphs of object changes in one step. * built to conform to what DBAs demand, including the ability to swap out generated SQL with hand-optimized statements, full usage of bind parameters for all literal values, fully transactionalized and consistent updates using Unit of Work. * modular. Different parts of SQLAlchemy can be used independently of the rest, including the connection pool, SQL construction, and ORM. SQLAlchemy is constructed in an open style that allows plenty of customization, with an architecture that supports custom datatypes, custom SQL extensions, and ORM plugins which can augment or extend mapping functionality. SQLAlchemy's Philosophy: * SQL databases behave less and less like object collections the more size and performance start to matter; object collections behave less and less like tables and rows the more abstraction starts to matter. SQLAlchemy aims to accomodate both of these principles. * Your classes aren't tables, and your objects aren't rows. Databases aren't just collections of tables; they're relational algebra engines. You don't have to select from just tables, you can select from joins, subqueries, and unions. Database and domain concepts should be visibly decoupled from the beginning, allowing both sides to develop to their full potential. * For example, table metadata (objects that describe tables) are declared distinctly from the classes theyre designed to store. That way database relationship concepts don't interfere with your object design concepts, and vice-versa; the transition from table-mapping to selectable-mapping is seamless; a class can be mapped against the database in more than one way. SQLAlchemy provides a powerful mapping layer that can work as automatically or as manually as you choose, determining relationships based on foreign keys or letting you define the join conditions explicitly, to bridge the gap between database and domain. SQLAlchemy's Advantages: * The Unit Of Work system organizes pending CRUD operations into queues and commits them all in one batch. It then performs a topological "dependency sort" of all items to be committed and deleted and groups redundant statements together. This produces the maxiumum efficiency and transaction safety, and minimizes chances of deadlocks. Modeled after Fowler's "Unit of Work" pattern as well as Java Hibernate. * Function-based query construction allows boolean expressions, operators, functions, table aliases, selectable subqueries, create/update/insert/delete queries, correlated updates, correlated EXISTS clauses, UNION clauses, inner and outer joins, bind parameters, free mixing of literal text within expressions, as little or as much as desired. Query-compilation is vendor-specific; the same query object can be compiled into any number of resulting SQL strings depending on its compilation algorithm. * Database mapping and class design are totally separate. Persisted objects have no subclassing requirement (other than 'object') and are POPO's : plain old Python objects. They retain serializability (pickling) for usage in various caching systems and session objects. SQLAlchemy "decorates" classes with non-intrusive property accessors to automatically log object creates and modifications with the UnitOfWork engine, to lazyload related data, as well as to track attribute change histories. * Custom list classes can be used with eagerly or lazily loaded child object lists, allowing rich relationships to be created on the fly as SQLAlchemy appends child objects to an object attribute. * Composite (multiple-column) primary keys are supported, as are "association" objects that represent the middle of a "many-to-many" relationship. * Self-referential tables and mappers are supported. Adjacency list structures can be created, saved, and deleted with proper cascading, with no extra programming. * Data mapping can be used in a row-based manner. Any bizarre hyper-optimized query that you or your DBA can cook up, you can run in SQLAlchemy, and as long as it returns the expected columns within a rowset, you can get your objects from it. For a rowset that contains more than one kind of object per row, multiple mappers can be chained together to return multiple object instance lists from a single database round trip. * The type system allows pre- and post- processing of data, both at the bind parameter and the result set level. User-defined types can be freely mixed with built-in types. Generic types as well as SQL-specific types are available. """, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: Jython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Database :: Front-Ends", "Operating System :: OS Independent", ], **kwargs ) if pypy or jython or py3k: run_setup(False) status_msgs( "WARNING: C extensions are not supported on " + "this Python platform, speedups are not enabled.", "Plain-Python build succeeded." ) else: try: run_setup(True) except BuildFailed: exc = sys.exc_info()[1] # work around py 2/3 different syntax status_msgs( exc.cause, "WARNING: The C extension could not be compiled, " + "speedups are not enabled.", "Failure information, if any, is above.", "Retrying the build without the C extension now." ) run_setup(False) status_msgs( "WARNING: The C extension could not be compiled, " + "speedups are not enabled.", "Plain-Python build succeeded." )
40.363333
76
0.641506
2ff2f0dd8a537dcfedbc9f68a6755b0407f5eb62
2,136
py
Python
tests/test_mapper.py
CuervoEC/ioet_employee_payment
be52d2f50b26ef3f9550d06194901ed73bc383e7
[ "MIT" ]
null
null
null
tests/test_mapper.py
CuervoEC/ioet_employee_payment
be52d2f50b26ef3f9550d06194901ed73bc383e7
[ "MIT" ]
null
null
null
tests/test_mapper.py
CuervoEC/ioet_employee_payment
be52d2f50b26ef3f9550d06194901ed73bc383e7
[ "MIT" ]
null
null
null
import unittest from calculator.mapper import unwrap_info class MapperTestClass(unittest.TestCase): def setUp(self): self.text = 'RENE=MO10:00-12:00,MO18:00-22:00,TU10:00-12:00' def test_should_return_name_and_schedule_when_valid_text_is_provided(self): name, schedule = unwrap_info(self.text) expected_name = 'RENE' # This data structure needs refactoring, could be more simple expected_schedule = [ ['MONDAY', (600, 720)], ['MONDAY', (1080, 1320)], ['TUESDAY', (600, 720)] ] self.assertEqual(expected_name, name) self.assertEqual(expected_schedule, schedule) def test_should_throw_exception_when_invalid_text_without_equal(self): edge_invalid_text = 'invalid' with self.assertRaises(ValueError): unwrap_info(edge_invalid_text) def test_should_throw_exception_when_invalid_text_with_more_equals(self): edge_invalid_text = 'i==n=d' with self.assertRaises(ValueError, msg='Invalid text was provided.'): unwrap_info(edge_invalid_text) def test_should_return_empty_when_name_and_schedule_not_defined(self): edge_invalid_text = '=' with self.assertRaises(ValueError, msg='Name or schedule is empty.'): unwrap_info(edge_invalid_text) def test_should_throw_exception_when_invalid_schedule_format(self): edge_invalid_schedule = 'RENE=M12:00' with self.assertRaises(ValueError, msg='Invalid schedule format.'): unwrap_info(edge_invalid_schedule) def test_should_throw_exception_when_invalid_day(self): edge_invalid_day = 'RENE=HY10:00-12:00' with self.assertRaises(ValueError, msg='Invalid day.'): unwrap_info(edge_invalid_day) def test_should_throw_exception_when_worked_minutes_are_negative(self): edge_invalid_schedule = 'RENE=MO12:00-10:00' with self.assertRaises(ValueError, msg='Incorrect schedule values. Final hour is greater than initial.'): unwrap_info(edge_invalid_schedule) if __name__ == '__main__': unittest.main()
39.555556
113
0.703184
f476b41d6b6b7bf143a47ef6b91bb7b0e292e304
1,988
py
Python
01-byoc/code/dataloader.py
timchiu9781/Tomofun
3f7abcb7fc1cc8200ec3fdff62bd51fbaada4126
[ "MIT-0" ]
27
2021-06-20T01:40:31.000Z
2022-02-17T12:23:41.000Z
01-byoc/code/dataloader.py
timchiu9781/Tomofun
3f7abcb7fc1cc8200ec3fdff62bd51fbaada4126
[ "MIT-0" ]
2
2021-07-14T06:26:37.000Z
2022-03-12T00:58:44.000Z
01-byoc/code/dataloader.py
timchiu9781/Tomofun
3f7abcb7fc1cc8200ec3fdff62bd51fbaada4126
[ "MIT-0" ]
7
2021-07-03T13:14:28.000Z
2021-07-29T15:23:59.000Z
import numpy as np from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate from torch.utils.data.sampler import SubsetRandomSampler class SoundDataLoader(DataLoader): def __init__(self, dataset, batch_size, shuffle=False, validation_split=0.0, num_workers=0, collate_fn=default_collate, pin_memory=True): self.validation_split = validation_split self.shuffle = shuffle self.batch_idx = 0 self.n_samples = len(dataset) self.sampler, self.valid_sampler = self._split_sampler(self.validation_split) self.init_kwargs = { 'dataset': dataset, 'batch_size': batch_size, 'shuffle': self.shuffle, 'collate_fn': collate_fn, 'num_workers': num_workers, 'pin_memory': pin_memory } super().__init__(sampler=self.sampler, **self.init_kwargs) def _split_sampler(self, split): if split == 0.0: return None, None idx_full = np.arange(self.n_samples) np.random.seed(0) np.random.shuffle(idx_full) if isinstance(split, int): assert split > 0 assert split < self.n_samples, "validation set size is configured to be larger than entire dataset." len_valid = split else: len_valid = int(self.n_samples * split) valid_idx = idx_full[0:len_valid] train_idx = np.delete(idx_full, np.arange(0, len_valid)) train_sampler = SubsetRandomSampler(train_idx) valid_sampler = SubsetRandomSampler(valid_idx) # turn off shuffle option which is mutually exclusive with sampler self.shuffle = False self.n_samples = len(train_idx) return train_sampler, valid_sampler def split_validation(self): if self.valid_sampler is None: return None else: return DataLoader(sampler=self.valid_sampler, **self.init_kwargs)
34.275862
141
0.650905
1d416b1c042f227d678f74298537e80499ca21a3
2,810
py
Python
slack_blockkit/utils/blocks.py
dylanmoring/slack-blockkit
90c8efd6f4d7e0ffe5850955e1b816e647b3c9f9
[ "MIT" ]
10
2020-07-20T03:29:19.000Z
2022-01-09T02:11:53.000Z
slack_blockkit/utils/blocks.py
dylanmoring/slack-blockkit
90c8efd6f4d7e0ffe5850955e1b816e647b3c9f9
[ "MIT" ]
6
2020-07-25T06:08:11.000Z
2022-01-05T17:39:13.000Z
slack_blockkit/utils/blocks.py
dylanmoring/slack-blockkit
90c8efd6f4d7e0ffe5850955e1b816e647b3c9f9
[ "MIT" ]
5
2021-02-14T17:10:35.000Z
2021-06-17T16:09:08.000Z
from slack_blockkit.block_element import BlockElement, ImageElement from slack_blockkit.composition_object import MarkdownTextObject, TextObject from slack_blockkit.layout_block import SectionBlock def get_checkmark(task_completed: bool) -> str: """ Returns a check mark emoji indicating the completed task status. If the task is complete, then a white check mark is returned. If not, an empty white square is. Args: task_completed (bool): Whether or not the task was complete. Returns: str: A checkmark emoji string based on whether or not the task was completed. """ return ":white_check_mark:" if task_completed else ":white_large_square:" def get_information_block(link: str, text: str) -> dict: """ Returns an information block, which is a section with an info icon followed by linked text. Args: link (str): The link the block redirects the user to. text (str): The link text. Returns: dict: A dict in the format of a context block. """ information = ":information_source: *<{link}|{text}>*".format(link=link, text=text) return MarkdownTextObject(text=information).render() def get_text_block_with_accessory(text_object: TextObject, accessory: BlockElement) -> dict: """ Returns a text block with an accessory. Args: text_object (TextObject): The text block object. accessory (LayoutBlock): The accessory object. Returns: dict: The text block with an accessory layout block. """ return SectionBlock(text=text_object, accessory=accessory).render() def get_text_block_with_image(text: str, image_url: str, alt_text: str) -> dict: """ Returns a text block with an image to the right of it. Args: text (str): The text in the text block. image_url (str): The URL to the image. alt_text (str): Alternate text (appears on image hover). Returns: dict: The block as a dict. """ text_object = MarkdownTextObject(text=text) image_element = ImageElement(image_url=image_url, alt_text=alt_text) return get_text_block_with_accessory( text_object=text_object, accessory=image_element ) def get_task_block(text: str, info_link: str, info_text: str) -> list: """ Returns a task block, which is comprised of a paragraph of text followed by an information link at the bottom. Args: text (str): Markdown-supported text to display in the paragraph. info_link (str): The link associated with the task block. info_text (str): The link text. Returns: list: An array of blocks formatted for a block payload. """ return [ MarkdownTextObject(text=text).render(), get_information_block(link=info_link, text=info_text), ]
35.56962
114
0.695018
d17a19c116b5e182be5f474805e8480817ebe703
4,510
py
Python
experiments/heli/baselines.py
sisl/CEEM
6154587fe3cdb92e8b7f70eedb1262caa1553cc8
[ "MIT" ]
5
2020-06-21T16:50:42.000Z
2021-03-14T04:02:01.000Z
experiments/heli/baselines.py
sisl/CEEM
6154587fe3cdb92e8b7f70eedb1262caa1553cc8
[ "MIT" ]
1
2021-03-13T07:46:36.000Z
2021-03-16T05:14:47.000Z
experiments/heli/baselines.py
sisl/CEEM
6154587fe3cdb92e8b7f70eedb1262caa1553cc8
[ "MIT" ]
1
2021-03-30T12:08:20.000Z
2021-03-30T12:08:20.000Z
import os import time import click import numpy as np import torch from ceem import logger, utils from ceem.baseline_utils import LagModel from ceem.data_utils import load_helidata, load_statistics from ceem.exp_utils import * from ceem.nn import LNMLP torch.set_default_dtype(torch.float64) opj = os.path.join device = 'cuda' if torch.cuda.is_available() else 'cpu' hyperparameters = { 1: dict(lr=1e-4, n_epochs=5000, save_file='naive.th', logdir='./data/naive'), 25: dict(lr=1e-4, n_epochs=5000, save_file='h25.th', logdir='./data/H25') } def train_horizon_model(H, datadir): # extract hyperparameters hp = hyperparameters[H] lr = hp['lr'] n_epochs = hp['n_epochs'] save_file = hp['save_file'] logdir = hp['logdir'] # load data utils.set_rng_seed(1) y_mean, y_std, u_mean, u_std = load_statistics(datadir) train_data, train_trgt = load_helidata(datadir, 'train') test_data, test_trgt = load_helidata(datadir, 'test') valid_data, valid_trgt = load_helidata(datadir, 'valid') # Define net neural_net_kwargs = dict(input_size=10 * H, hidden_sizes=[32] * 8, output_size=6, activation='tanh', gain=1.0, ln=False) net = LagModel(neural_net_kwargs, H) logger.setup(logdir, action='d') # Train system = train_net(net, train_data, train_trgt, test_data, test_trgt, valid_data, valid_trgt, y_std, lr, logdir=logdir, H=H, n_epochs=n_epochs) torch.save(system.state_dict(), save_file) def train_net(net, train_data, train_trgt, test_data, test_trgt, valid_data, valid_trgt, y_std, lr, H, logdir, n_epochs=1000): T = train_data.shape[1] opt = torch.optim.Adam(net.parameters(), lr=lr) scheduler_off = 1000. scheduler = torch.optim.lr_scheduler.LambdaLR( opt, lambda epoch: scheduler_off / (scheduler_off + epoch)) best_val_loss = np.inf t0 = time.time() for e in range(n_epochs): logger.logkv('epoch', e) # train ll = [] coord_error = 0 for t in range(T - H + 1): opt.zero_grad() u = train_data[:, t:t + H] y = train_trgt[:, t + H - 1] y_pred = net(u) assert y.size() == y_pred.size() loss = compute_rms(y.unsqueeze(0), y_pred.unsqueeze(0), y_std) loss.backward() opt.step() ll.append(float(loss)) mean_train_loss = np.mean(ll) logger.logkv('log10_train_loss', np.log10(mean_train_loss)) coord_error /= (T - H) scheduler.step() for param_group in opt.param_groups: logger.logkv('log10_lr', np.log10(param_group['lr'])) if e % 100 == 0: # validation ll = [] coord_error = 0 for t in range(T - H): with torch.no_grad(): u = valid_data[:, t:t + H] y = valid_trgt[:, t + H - 1] y_pred = net(u) loss = compute_rms(y.unsqueeze(0), y_pred.unsqueeze(0), y_std) ll.append(float(loss)) mean_val_loss = np.mean(ll) logger.logkv('log10_val_loss', np.log10(mean_val_loss)) coord_error /= (T - H) # Test ll = [] coord_error = 0 for t in range(T - H): with torch.no_grad(): u = test_data[:, t:t + H] y = test_trgt[:, t + H - 1] y_pred = net(u) loss = compute_rms(y.unsqueeze(0), y_pred.unsqueeze(0), y_std) ll.append(float(loss)) mean_test_loss = np.mean(ll) logger.logkv('log10_test_loss', np.log10(mean_test_loss)) # Save if mean_val_loss < best_val_loss: torch.save(net.state_dict(), os.path.join(logdir, 'best_net.th')) best_val_loss = mean_val_loss if time.time() - t0 > 2: t0 = time.time() logger.dumpkvs() return net @click.command() @click.option('--model', type=str, default='naive') @click.option('--datadir', type=click.Path(), default='./datasets/split_normalized') def run(model, datadir): if model == 'naive': train_horizon_model(1, datadir) elif model == 'H25': train_horizon_model(25, datadir) else: raise ValueError(f"No baseline as {model}") if __name__ == "__main__": run()
30.472973
99
0.574501
8fb8daaa16e1701a65110b68a9eadaf96495fab1
1,238
py
Python
jdcloud_sdk/services/kubernetes/models/NodeConfigSpec.py
jdcloud-demo/jdcloud-sdk-python
fddc2af24031c597948b8b8091978ac7e01a2695
[ "Apache-2.0" ]
null
null
null
jdcloud_sdk/services/kubernetes/models/NodeConfigSpec.py
jdcloud-demo/jdcloud-sdk-python
fddc2af24031c597948b8b8091978ac7e01a2695
[ "Apache-2.0" ]
null
null
null
jdcloud_sdk/services/kubernetes/models/NodeConfigSpec.py
jdcloud-demo/jdcloud-sdk-python
fddc2af24031c597948b8b8091978ac7e01a2695
[ "Apache-2.0" ]
null
null
null
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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. # # NOTE: This class is auto generated by the jdcloud code generator program. class NodeConfigSpec(object): def __init__(self, instanceType, systemDiskSize, systemDiskType, version=None, labels=None): """ :param instanceType: 实例类型 :param version: (Optional) 镜像信息 :param systemDiskSize: 云盘系统盘的大小 单位(GB) :param systemDiskType: 云盘系统盘的大小[ssd,premium-hdd] :param labels: (Optional) Node的信息 """ self.instanceType = instanceType self.version = version self.systemDiskSize = systemDiskSize self.systemDiskType = systemDiskType self.labels = labels
34.388889
96
0.709208
e7ddf0a82ae82e9eb38e385aa0ea0647965aa8af
443
py
Python
examples/pytorch/jtnn/jtnn/line_profiler_integration.py
ketyi/dgl
a1b859c29b63a673c148d13231a49504740e0e01
[ "Apache-2.0" ]
9,516
2018-12-08T22:11:31.000Z
2022-03-31T13:04:33.000Z
examples/pytorch/jtnn/jtnn/line_profiler_integration.py
ketyi/dgl
a1b859c29b63a673c148d13231a49504740e0e01
[ "Apache-2.0" ]
2,494
2018-12-08T22:43:00.000Z
2022-03-31T21:16:27.000Z
examples/pytorch/jtnn/jtnn/line_profiler_integration.py
ketyi/dgl
a1b859c29b63a673c148d13231a49504740e0e01
[ "Apache-2.0" ]
2,529
2018-12-08T22:56:14.000Z
2022-03-31T13:07:41.000Z
''' line_profiler integration ''' import os if os.getenv('PROFILE', 0): import line_profiler import atexit profile = line_profiler.LineProfiler() profile_output = os.getenv('PROFILE_OUTPUT', None) if profile_output: from functools import partial atexit.register(partial(profile.dump_stats, profile_output)) else: atexit.register(profile.print_stats) else: def profile(f): return f
22.15
68
0.688488
c99ec695e5955c864749177f1be92b424299ac74
238
py
Python
Aula 13/Desafios/060.py
mateuschaves/curso-python
53b2f3b4bf083ae2ce7ea19dd358f49a36becd9d
[ "MIT" ]
1
2018-07-23T04:03:35.000Z
2018-07-23T04:03:35.000Z
Aula 13/Desafios/060.py
mateuschaves/curso-python
53b2f3b4bf083ae2ce7ea19dd358f49a36becd9d
[ "MIT" ]
null
null
null
Aula 13/Desafios/060.py
mateuschaves/curso-python
53b2f3b4bf083ae2ce7ea19dd358f49a36becd9d
[ "MIT" ]
null
null
null
""" Faça um programa que leia um número qualquer e mostre o seu fatorial """ n = int(input('Informe um número: ')) s = n fatorial = 1 while n > 1: fatorial *= n n -= 1 print('O fatorial de {} é {} !'.format(s, fatorial))
18.307692
52
0.592437
99b729946379628696d46a029150e5d787aedd70
13,135
py
Python
test.py
jernej19/fantasynhl
1b2ee42e82d714f3e3b9b01e1fc0e799e3f77f77
[ "Apache-2.0" ]
null
null
null
test.py
jernej19/fantasynhl
1b2ee42e82d714f3e3b9b01e1fc0e799e3f77f77
[ "Apache-2.0" ]
null
null
null
test.py
jernej19/fantasynhl
1b2ee42e82d714f3e3b9b01e1fc0e799e3f77f77
[ "Apache-2.0" ]
null
null
null
import pandas as pd import numpy as np # Import data to dataframe players = pd.read_csv('players.csv') goalies = pd.read_csv('goalies.csv') # Remove unnecessary columns: players = players.drop(columns=['adjusted_assists', 'adjusted_goals', 'adjusted_goals_against_average', 'adjusted_goals_created', 'adjusted_points', 'corsi_against', 'corsi_for', 'corsi_for_percentage', 'defensive_point_shares', 'defensive_zone_start_percentage', 'even_strength_assists', 'even_strength_goals', 'even_strength_goals_allowed', 'even_strength_save_percentage', 'even_strength_shots_faced', 'fenwick_against', 'fenwick_for', 'fenwick_for_percentage', 'giveaways', 'goal_against_percentage_relative', 'goalie_point_shares', 'goals_against_on_ice', 'goals_created', 'goals_for_on_ice', 'goals_saved_above_average', 'height', 'league', 'minutes', 'offensive_point_shares', 'offensive_zone_start_percentage', 'pdo', 'point_shares', 'power_play_goals_against_on_ice', 'power_play_goals_allowed', 'power_play_goals_for_on_ice', 'power_play_save_percentage', 'power_play_shots_faced', 'quality_start_percentage', 'relative_corsi_for_percentage', 'relative_fenwick_for_percentage', 'save_percentage_on_ice', 'shooting_percentage_on_ice', 'shootout_attempts', 'shootout_goals', 'shootout_misses', 'shootout_percentage', 'short_handed_goals_allowed', 'short_handed_save_percentage', 'short_handed_shots_faced', 'shots_against', 'takeaways', 'ties_plus_overtime_loss', 'time_on_ice_even_strength', 'total_goals_against_on_ice', 'total_goals_for_on_ice', 'weight', 'faceoff_losses', 'faceoff_percentage', 'wins', 'total_shots', 'shutouts', 'quality_starts', 'really_bad_starts', 'save_percentage', 'saves', 'losses', 'goals_against_average', 'goals_against', ]) goalies = goalies.drop(columns=['adjusted_assists', 'adjusted_goals', 'adjusted_goals_against_average', 'adjusted_goals_created', 'adjusted_points', 'corsi_against', 'corsi_for', 'corsi_for_percentage', 'defensive_point_shares', 'defensive_zone_start_percentage', 'even_strength_assists', 'even_strength_goals', 'even_strength_goals_allowed', 'even_strength_save_percentage', 'even_strength_shots_faced', 'fenwick_against', 'fenwick_for', 'fenwick_for_percentage', 'giveaways', 'goal_against_percentage_relative', 'goalie_point_shares', 'goals_against_on_ice', 'goals_created', 'goals_for_on_ice', 'goals_saved_above_average', 'height', 'league', 'minutes', 'offensive_point_shares', 'offensive_zone_start_percentage', 'pdo', 'point_shares', 'power_play_goals_against_on_ice', 'power_play_goals_allowed', 'power_play_goals_for_on_ice', 'power_play_save_percentage', 'power_play_shots_faced', 'quality_start_percentage', 'relative_corsi_for_percentage', 'relative_fenwick_for_percentage', 'save_percentage_on_ice', 'shooting_percentage_on_ice', 'shootout_attempts', 'shootout_goals', 'shootout_misses', 'shootout_percentage', 'short_handed_goals_allowed', 'short_handed_save_percentage', 'short_handed_shots_faced', 'shots_against', 'takeaways', 'ties_plus_overtime_loss', 'time_on_ice_even_strength', 'total_goals_against_on_ice', 'total_goals_for_on_ice', 'weight', 'faceoff_losses', 'faceoff_percentage', 'assists', 'average_time_on_ice', 'blocks_at_even_strength', 'faceoff_wins', 'game_winning_goals', 'games_played', 'goals', 'hits_at_even_strength', 'penalties_in_minutes', 'plus_minus', 'points', 'power_play_assists', 'power_play_goals', 'shooting_percentage', 'short_handed_assists', 'short_handed_goals', 'shots_on_goal' ]) players = players.fillna(0) goalies = goalies.fillna(0) # Replace season values s = players['season'].isin(['Career', 'season']) players.loc[~s, 'season'] = players.groupby(s.ne(s.shift()).cumsum()).cumcount() + 1 l = goalies['season'].isin(['Career', 'season']) goalies.loc[~l, 'season'] = goalies.groupby(l.ne(s.shift()).cumsum()).cumcount() + 1 # Drop Career and season rows players.drop(players[players['season'] == 'Career'].index, inplace=True) players.drop(players[players['season'] == 'season'].index, inplace=True) goalies.drop(goalies[goalies['season'] == 'Career'].index, inplace=True) goalies.drop(goalies[goalies['season'] == 'season'].index, inplace=True) # Change column values to ints changes_players = ['assists', 'blocks_at_even_strength', 'faceoff_wins', 'game_winning_goals', 'goals', 'hits_at_even_strength', 'penalties_in_minutes', 'plus_minus', 'points', 'power_play_assists', 'power_play_goals', 'short_handed_assists', 'short_handed_goals', 'shots_on_goal', 'games_played', 'season'] changes_goalies = ['losses', 'quality_starts', 'really_bad_starts', 'saves', 'shutouts', 'time_on_ice', 'total_shots', 'wins'] for integer in changes_players: players[integer] = pd.to_numeric(players[integer]) for integer in changes_goalies: goalies[integer] = pd.to_numeric(goalies[integer]) ####################### TEST ENVIRONMENT ################################ test = pd.DataFrame() test['goals/game'] = players['goals']/(players['games_played']) test['points/game'] = players['points']/(players['games_played']) test['shots/game'] = players['shots_on_goal']/(players['games_played']) test['gwg'] = players['game_winning_goals']/(players['games_played']) test['assists'] = players['assists']/(players['games_played']) test['ppa'] = players['power_play_assists']/(players['games_played']) test['ppg'] = players['power_play_goals']/(players['games_played']) test['shp'] = (players['short_handed_assists']+players['short_handed_goals'])/(players['games_played']) test['season'] = players['season'] # test['shooting%'] = players['shooting_percentage'] test['plus_minus'] = players['plus_minus'] test['name'] = players['name'] test['hits'] = players['hits_at_even_strength']/(players['games_played']) test['blocks'] = players['blocks_at_even_strength']/(players['games_played']) test['PIM'] = players['penalties_in_minutes']/(players['games_played']) # test['TOI'] = players['average_time_on_ice'] # test['FO%'] = players['faceoff_percentage'] test['FOW'] = players['faceoff_wins']/(players['games_played']) test['games_played'] = players['games_played'] # For loop to predict all players selected_players = [player for player in test['name']] selected_players = list(set(selected_players)) player_prediction = pd.DataFrame() player_prediction_1 = pd.DataFrame() for selected_player in selected_players: ovechkin = test.loc[test.name == selected_player] shots = ovechkin['shots/game'] goals = ovechkin['goals/game'] ppa = ovechkin['ppa'] ppg = ovechkin['ppg'] a = ovechkin['assists'] # sh_per = ovechkin['shooting%'] shp = ovechkin['shp'] fow = ovechkin['FOW'] hits = ovechkin['hits'] blocks = ovechkin['blocks'] pim = ovechkin['PIM'] plusMinus = ovechkin['plus_minus'] season = ovechkin['season'] games_played = ovechkin['games_played'] ovechkin_1 = ovechkin.drop(['name'], 1) #################################################################### if len(ovechkin_1['season']) > 2: weights = season weights.loc[:] = 0.5 weights[-2:] = 7 shots_avg = np.average(shots, weights=weights) goals_avg = np.average(goals, weights=weights) ppa_avg = np.average(ppa, weights=weights) ppg_avg = np.average(ppg, weights=weights) shp_avg = np.average(shp, weights=weights) assists_avg = np.average(a, weights=weights) fow_avg = np.average(fow, weights=weights) hits_avg = np.average(hits, weights=weights) blocks_avg = np.average(blocks, weights=weights) pim_avg = np.average(pim, weights=weights) plusMinus_avg = np.average(plusMinus, weights=weights) player_prediction = player_prediction.append( pd.DataFrame({'name': [selected_player], 'shots on goal': [shots_avg * 82], 'ppa': [ppa_avg * 82], 'goals': [goals_avg*82], 'ppg': [ppg_avg * 82], # 'shooting%': [sh_per.mean()], 'shp': [shp_avg * 82], 'assists': [assists_avg * 82], 'fow': [fow_avg * 82], 'hits': [hits_avg * 82], 'blocks': [blocks_avg * 82], 'plus/minus': [plusMinus_avg], 'PIM': [pim_avg * 82]})) for selected_player in selected_players: ovechkin = test.loc[test.name == selected_player] shots = ovechkin['shots/game'] goals = ovechkin['goals/game'] ppa = ovechkin['ppa'] ppg = ovechkin['ppg'] a = ovechkin['assists'] # sh_per = ovechkin['shooting%'] shp = ovechkin['shp'] fow = ovechkin['FOW'] hits = ovechkin['hits'] blocks = ovechkin['blocks'] pim = ovechkin['PIM'] plusMinus = ovechkin['plus_minus'] season = ovechkin['season'] games_played = ovechkin['games_played'] ovechkin_1 = ovechkin.drop(['name'], 1) if len(ovechkin_1['season']) <= 2: ######### TEST NUMBER 1.05, CHANGE WHEN IT'S CALCULATED!!!!!!! ########## player_prediction_1 = player_prediction_1.append( pd.DataFrame({'name': [selected_player], 'shots on goal': [(shots.mean() * 1.05) * 82], 'ppa': [(ppa.mean() * 1.05) * 82], 'goals': [(goals.mean() * 1.05) * 82], 'ppg': [(ppg.mean() * 1.05) * 82], # 'shooting%': [sh_per.mean()], 'shp': [(shp.mean() * 1.05) * 82], 'assists': [(a.mean() * 1.05) * 82], 'fow': [(fow.mean()*1.05)*82], 'hits': [(hits.mean() * 1.05) * 82], 'blocks': [(blocks.mean() * 1.05) * 82], 'plus/minus': [plusMinus.mean() * 1.05], 'PIM': [(pim.mean() * 1.05) * 82]})) df = pd.concat([player_prediction, player_prediction_1], sort=False) df.to_csv('players_predictions_1.csv', index=False) ################################################# # GOALIE PREDICTIONS ################################################# # goalies_test = pd.DataFrame() # goalies_test['starts'] = goalies['goals']/(players['games_played']) ########### GOALIE STARTS MISSING!!!!!!!!!!!!!!!!!! goalies_test['wins'] = goalies['wins'].astype(int) goalies_test['ga'] = goalies['goals_against'].astype(int) goalies_test['ga'] = goalies_test['ga'].astype(int) goalies_test['gaa'] = goalies['goals_against_average'] goalies_test['gaa'] = goalies_test['gaa'].astype(float) goalies_test['sv'] = goalies['saves'].astype(int) goalies_test['sv%'] = goalies['save_percentage'].astype(float) goalies_test['sho'] = goalies['shutouts'].astype(int) goalies_test['age'] = goalies['age'] goalies_test['name'] = goalies['name'] goalies_test['season'] = goalies['season'] selected_goalies = [player for player in goalies_test['name']] selected_goalies = list(set(selected_goalies)) test_5 = pd.DataFrame() for selected_goalie in selected_goalies: price = goalies_test.loc[goalies_test.name == selected_goalie] wins = price['wins'] ga = price['ga'] gaa = price['gaa'] sv = price['sv'] sv_per = price['sv%'] sho = price['sho'] season = price['season'] price_1 = price.drop(['name'],1) if len(price_1['season']) <= 2: ######### TEST NUMBER 1.05, CHANGE WHEN IT'S CALCULATED!!!!!!! ########## test_5 = test_5.append(pd.DataFrame({'name': [selected_goalie], 'wins': [wins.mean()], 'goals against': [ga.mean()], 'goals against average': [gaa.mean()], 'saves': [sv.mean()], 'save%': [sv_per.mean()], 'shutouts': [sho.mean()]})) #################################################################### else: weights = season weights.loc[:] = 0.5 weights[-2:] = 5 wins_avg = np.average(wins, weights=weights) ga_avg = np.average(ga, weights=weights) gaa_avg = np.average(gaa, weights=weights) saves_avg = np.average(sv, weights=weights) so_avg = np.average(sho, weights=weights) svPer_avg = np.average(sv_per, weights=weights) test_5 = test_5.append(pd.DataFrame({'name': [selected_goalie], 'wins': [wins_avg], 'goals against': [ga_avg], 'goals against average': [gaa_avg], 'saves': [saves_avg], 'save%': [svPer_avg], 'shutouts': [so_avg]})) test_5.to_csv('goalies_predictions_1.csv', index=False)
36.085165
121
0.620708
1efd119ab3a348443e237ec63e09114df858b223
7,698
py
Python
repos/system_upgrade/el7toel8/actors/checkxfs/tests/unit_test.py
adka1408/leapp-repository
be5a9603b57f86c65d395ba6a02b860cacae0fb6
[ "Apache-2.0" ]
null
null
null
repos/system_upgrade/el7toel8/actors/checkxfs/tests/unit_test.py
adka1408/leapp-repository
be5a9603b57f86c65d395ba6a02b860cacae0fb6
[ "Apache-2.0" ]
null
null
null
repos/system_upgrade/el7toel8/actors/checkxfs/tests/unit_test.py
adka1408/leapp-repository
be5a9603b57f86c65d395ba6a02b860cacae0fb6
[ "Apache-2.0" ]
null
null
null
import pytest from leapp.exceptions import StopActorExecutionError from leapp.libraries.actor import library from leapp.libraries.common.testutils import produce_mocked from leapp.libraries.stdlib import api from leapp.models import StorageInfo, FstabEntry, MountEntry, SystemdMountEntry, XFSPresence class run_mocked(object): def __init__(self): self.called = 0 self.args = None def __call__(self, args, split=True): self.called += 1 self.args = args with_ftype = {'stdout': [ "meta-data=/dev/loop0 isize=512 agcount=4, agsize=131072 blks", " = sectsz=512 attr=2, projid32bit=1", " = crc=1 finobt=0 spinodes=0", "data = bsize=4096 blocks=524288, imaxpct=25", " = sunit=0 swidth=0 blks", "naming =version 2 bsize=4096 ascii-ci=0 ftype=1", "log =internal bsize=4096 blocks=2560, version=2", " = sectsz=512 sunit=0 blks, lazy-count=1", "realtime =none extsz=4096 blocks=0, rtextents=0"]} without_ftype = {'stdout': [ "meta-data=/dev/loop0 isize=512 agcount=4, agsize=131072 blks", " = sectsz=512 attr=2, projid32bit=1", " = crc=1 finobt=0 spinodes=0", "data = bsize=4096 blocks=524288, imaxpct=25", " = sunit=0 swidth=0 blks", "naming =version 2 bsize=4096 ascii-ci=0 ftype=0", "log =internal bsize=4096 blocks=2560, version=2", " = sectsz=512 sunit=0 blks, lazy-count=1", "realtime =none extsz=4096 blocks=0, rtextents=0"]} if "/var" in self.args: return without_ftype return with_ftype def test_check_xfs_fstab(monkeypatch): fstab_data_no_xfs = { "fs_spec": "/dev/mapper/fedora-home", "fs_file": "/home", "fs_vfstype": "ext4", "fs_mntops": "defaults,x-systemd.device-timeout=0", "fs_freq": "1", "fs_passno": "2"} mountpoints = library.check_xfs_fstab([FstabEntry(**fstab_data_no_xfs)]) assert not mountpoints fstab_data_xfs = { "fs_spec": "/dev/mapper/rhel-root", "fs_file": "/", "fs_vfstype": "xfs", "fs_mntops": "defaults", "fs_freq": "0", "fs_passno": "0"} mountpoints = library.check_xfs_fstab([FstabEntry(**fstab_data_xfs)]) assert mountpoints == {"/"} def test_check_xfs_mount(monkeypatch): mount_data_no_xfs = { "name": "tmpfs", "mount": "/run/snapd/ns", "tp": "tmpfs", "options": "rw,nosuid,nodev,seclabel,mode=755"} mountpoints = library.check_xfs_mount([MountEntry(**mount_data_no_xfs)]) assert not mountpoints mount_data_xfs = { "name": "/dev/vda1", "mount": "/boot", "tp": "xfs", "options": "rw,relatime,seclabel,attr2,inode64,noquota"} mountpoints = library.check_xfs_mount([MountEntry(**mount_data_xfs)]) assert mountpoints == {"/boot"} def test_check_xfs_systemdmount(monkeypatch): systemdmount_data_no_xfs = { "node": "/dev/sda1", "path": "pci-0000:00:17.0-ata-2", "model": "TOSHIBA_THNSNJ512GDNU_A", "wwn": "0x500080d9108e8753", "fs_type": "ext4", "label": "n/a", "uuid": "5675d309-eff7-4eb1-9c27-58bc5880ec72"} mountpoints = library.check_xfs_systemdmount([SystemdMountEntry(**systemdmount_data_no_xfs)]) assert not mountpoints systemdmount_data_xfs = { "node": "/dev/sda1", "path": "/var", "model": "n/a", "wwn": "n/a", "fs_type": "xfs", "label": "n/a", "uuid": "n/a"} mountpoints = library.check_xfs_systemdmount([SystemdMountEntry(**systemdmount_data_xfs)]) assert mountpoints == {"/var"} def test_is_xfs_without_ftype(monkeypatch): monkeypatch.setattr(library, "run", run_mocked()) assert library.is_xfs_without_ftype("/var") assert ' '.join(library.run.args) == "/usr/sbin/xfs_info /var" assert not library.is_xfs_without_ftype("/boot") assert ' '.join(library.run.args) == "/usr/sbin/xfs_info /boot" def test_check_xfs(monkeypatch): monkeypatch.setattr(library, "run", run_mocked()) def consume_no_xfs_message_mocked(*models): yield StorageInfo() monkeypatch.setattr(api, "consume", consume_no_xfs_message_mocked) monkeypatch.setattr(api, "produce", produce_mocked()) library.check_xfs() assert api.produce.called == 1 assert len(api.produce.model_instances) == 1 assert isinstance(api.produce.model_instances[0], XFSPresence) assert not api.produce.model_instances[0].present assert not api.produce.model_instances[0].without_ftype def consume_ignored_xfs_message_mocked(*models): mount_data = { "name": "/dev/vda1", "mount": "/boot", "tp": "xfs", "options": "rw,relatime,seclabel,attr2,inode64,noquota"} yield StorageInfo(mount=[MountEntry(**mount_data)]) monkeypatch.setattr(api, "consume", consume_ignored_xfs_message_mocked) monkeypatch.setattr(api, "produce", produce_mocked()) library.check_xfs() assert api.produce.called == 1 assert len(api.produce.model_instances) == 1 assert isinstance(api.produce.model_instances[0], XFSPresence) assert not api.produce.model_instances[0].present assert not api.produce.model_instances[0].without_ftype def consume_xfs_with_ftype_message_mocked(*models): fstab_data = { "fs_spec": "/dev/mapper/rhel-root", "fs_file": "/", "fs_vfstype": "xfs", "fs_mntops": "defaults", "fs_freq": "0", "fs_passno": "0"} yield StorageInfo(fstab=[FstabEntry(**fstab_data)]) monkeypatch.setattr(api, "consume", consume_xfs_with_ftype_message_mocked) monkeypatch.setattr(api, "produce", produce_mocked()) library.check_xfs() assert api.produce.called == 1 assert len(api.produce.model_instances) == 1 assert isinstance(api.produce.model_instances[0], XFSPresence) assert api.produce.model_instances[0].present assert not api.produce.model_instances[0].without_ftype def consume_xfs_without_ftype_message_mocked(*models): fstab_data = { "fs_spec": "/dev/mapper/rhel-root", "fs_file": "/var", "fs_vfstype": "xfs", "fs_mntops": "defaults", "fs_freq": "0", "fs_passno": "0"} yield StorageInfo(fstab=[FstabEntry(**fstab_data)]) monkeypatch.setattr(api, "consume", consume_xfs_without_ftype_message_mocked) monkeypatch.setattr(api, "produce", produce_mocked()) library.check_xfs() assert api.produce.called == 1 assert len(api.produce.model_instances) == 1 assert isinstance(api.produce.model_instances[0], XFSPresence) assert api.produce.model_instances[0].present assert api.produce.model_instances[0].without_ftype def consume_no_message_mocked(*models): yield None monkeypatch.setattr(api, "consume", consume_no_message_mocked) monkeypatch.setattr(api, "produce", produce_mocked()) with pytest.raises(StopActorExecutionError): library.check_xfs()
37.735294
97
0.599896
c26a4cf6a1b57ac559442976bf026cb0223dc928
3,167
py
Python
rpi-opencv-video-stream.py
wesmith/streaming-video-rpi
a92ed556d995efc7433e6adbc8a08bbd1b252867
[ "MIT" ]
null
null
null
rpi-opencv-video-stream.py
wesmith/streaming-video-rpi
a92ed556d995efc7433e6adbc8a08bbd1b252867
[ "MIT" ]
null
null
null
rpi-opencv-video-stream.py
wesmith/streaming-video-rpi
a92ed556d995efc7433e6adbc8a08bbd1b252867
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # WS TODO # - (done) run webcam via opencv # - add command-line inputs: camera type, url, port, frame size # - fix the stylesheet # - add change-detection, other algos from importlib import import_module import os from flask import Flask, render_template, Response from flask import jsonify, request # import camera driver if os.environ.get('CAMERA'): Camera = import_module('camera_' +\ os.environ['CAMERA']).Camera else: from camera import Camera # Raspberry Pi camera module (requires picamera package) # from camera_pi import Camera default_button = ['DEFAULT_VALUES', 0] invert = {'INVERT_COLORS': {'YES': 10, 'NO': 11}} flip = {'FLIP_IMAGE':{'HORIZ': 20, 'VERT': 21, '180_DEG': 22, 'NO_FLIP': 23}} gray = {'GRAYSCALE': {'YES': 30, 'NO': 31}} blur = {'BLUR': {'TURN_OFF': 41}} button_vals = {'0': 'DEFAULT', '10': 'INVERT ON', '11': 'INVERT OFF', '20': 'FLIP HORIZ', '21': 'FLIP VERT', '22': 'FLIP 180 DEG', '23': 'NO FLIP', '30': 'GRAYSCALE', '31': 'COLOR', '41': 'NO BLURRING', '42': 'BLURRING ON'} class Message(): def __init__(self, button_vals): self.value = '0' self.mapping = button_vals self.kernel = None msg = Message(button_vals) app = Flask(__name__) @app.route('/') def index(): """Video streaming home page.""" return render_template('index.html', default=default_button, invert=invert, flip=flip, gray=gray, blur=blur) def gen(camera): """Video streaming generator function.""" yield b'--frame\r\n' while True: frame = camera.get_frame() yield b'Content-Type: image/jpeg\r\n\r\n' + frame +\ b'\r\n--frame\r\n' @app.route('/button_input', methods=['POST', 'GET']) def button_inputs(): # update the message to the Camera class from button inputs if request.method == "POST": result_txt = request.form['button_value'] # '999' is the symbol to indicate # blurring-kernel size input if result_txt[-3:] == '999': val = result_txt[:-3] # strip off the symbol print('val: {}'.format(val)) ttt = 'Blurring with kernel size {} x {}'.format(val, val) print(ttt) msg.value = '42' msg.kernel = int(val) return jsonify(output=ttt) else: msg.value = result_txt #print('button value: {}'.format(result_txt)) return jsonify(output=msg.mapping[msg.value]) @app.route('/video_feed') def video_feed(): """ Video streaming route. Put this in the src attribute of an img tag. """ txt = 'multipart/x-mixed-replace; boundary=frame' # WS added passing a message to the Camera class return Response(gen(Camera(message=msg)), mimetype=txt) if __name__ == '__main__': # WS added debug for automatic reloading app.run(host='0.0.0.0', threaded=True, debug=True)
31.356436
70
0.569624
a1617b2dd3d795639251e20b4c18bf90445ad956
3,139
py
Python
color_image.py
hassanmohsin/stl-to-voxel
52b81a8b28e35511deb7c7ff6b300b069a91a64d
[ "MIT" ]
null
null
null
color_image.py
hassanmohsin/stl-to-voxel
52b81a8b28e35511deb7c7ff6b300b069a91a64d
[ "MIT" ]
null
null
null
color_image.py
hassanmohsin/stl-to-voxel
52b81a8b28e35511deb7c7ff6b300b069a91a64d
[ "MIT" ]
null
null
null
import argparse import json import math import matplotlib.pyplot as plt import numpy as np from stltovoxel import get_voxels, file_choices, read_stl class ColorImage(object): def __init__(self, stl_file, voxel_resolution=100): self.stl_file = stl_file self.voxel_resolution = voxel_resolution self.mesh = read_stl(self.stl_file) self.scale, self.shift, self.voxels, self.bounding_box = None, None, None, None self.image_data = None self.image = None self.xray_intensity = 10 self.materials_constant = 0.99 def generate_voxels(self): _, _, self.voxels, self.bounding_box = get_voxels(self.mesh, resolution=self.voxel_resolution) def rotate(self, axis, degree): """ Rotate the mesh :param axis: axis to rotate around; e.g., x-axis= [0.5, 0., 0.], y-axis = [0., 0.5, 0. :param degree: degree of rotation :return: None """ self.mesh.rotate(axis, math.radians(degree)) def get_color_image(self, axis='x', image_file='color_image.png', dpi=300): if not self.voxels: self.generate_voxels() axes = {'x': 0, 'y': 1, 'z': 2} # Object volume traversed by the x-ray xray_volume = np.sum(self.voxels, axis=axes[axis]) # Calculate absorption self.image_data = self.xray_intensity * np.exp(-1 * self.materials_constant * xray_volume) # self.image_data = self.image_data - self.config['xray_intensity'] # Generate the image self.image = plt.imshow(self.image_data) self.image.set_cmap('viridis') plt.axis('off') plt.savefig(image_file, dpi=dpi, bbox_inches='tight', pad_inches=0) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert STL files to false colored 2D image') parser.add_argument('--input', nargs='?', type=lambda s: file_choices('.stl', s), help="Input file (.stl)") parser.add_argument('--vres', type=int, default=100, action='store', help="Voxel resolution") parser.add_argument('--ires', type=int, default=300, action='store', help="Image resolution.") parser.add_argument('--ray-axis', type=str, default='z', action='store', help="Axis of x-ray") parser.add_argument('--rotation-axis', nargs='+', type=float, default=None, action='store', help="Rotation axis, e.g., 0.5 0.5 0 for rotating around x and y axes.") parser.add_argument('--theta', type=float, default=None, action='store', help="Angle of rotation, e.g., 45") parser.add_argument('--output', nargs='?', type=lambda s: file_choices(('.png', '.jpg'), s), help="Output file (.png, .jpg).") args = parser.parse_args() color_image = ColorImage(args.input, args.vres) if args.rotation_axis: if not args.theta: raise ValueError("Please specify the rotation axis.") color_image.rotate(args.rotation_axis, args.theta) color_image.get_color_image(image_file=args.output, dpi=args.ires, axis=args.ray_axis)
45.492754
113
0.635871
120d5144f92162f54bfe4c0066715dbedeaa26a2
5,890
py
Python
normalizing_flows_typed/flow.py
kiwi0fruit/jats-semi-supervised-pytorch
67e9bb85f09f8ef02e17e495784d1d9a71c3adec
[ "MIT" ]
null
null
null
normalizing_flows_typed/flow.py
kiwi0fruit/jats-semi-supervised-pytorch
67e9bb85f09f8ef02e17e495784d1d9a71c3adec
[ "MIT" ]
null
null
null
normalizing_flows_typed/flow.py
kiwi0fruit/jats-semi-supervised-pytorch
67e9bb85f09f8ef02e17e495784d1d9a71c3adec
[ "MIT" ]
null
null
null
""" Code by Jesper Wohlert was forked from https://github.com/wohlert/semi-supervised-pytorch Code by Nicola De Cao was forked from https://github.com/nicola-decao/BNAF MIT License Copyright (c) 2017 Jesper Wohlert, 2019 Nicola De Cao, 2019 Peter Zagubisalo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from typing import Tuple, List, Dict, Union from abc import abstractmethod import torch as tr from torch import Tensor from torch import nn from kiwi_bugfix_typechecker import nn as nn_ from kiwi_bugfix_typechecker import func from .types import ModuleZToXY, SequentialZToXY δ = 1e-8 UModuleZToXY = Union[SequentialZToXY, ModuleZToXY] # noinspection PyAbstractClass class Flow(ModuleZToXY): @abstractmethod def backward(self, z: Tensor) -> Tuple[Tensor, Tensor]: raise NotImplementedError class NormalizingFlows(Flow): flows: List[Flow] def __init__(self, dim: int=None, flows: List[Flow]=None): """ Presents a sequence of normalizing flows as a ``torch.nn.Module``. default value is [PlanarNormalizingFlow(dim) for i in range(16)] Forked from github.com/wohlert/semi-supervised-pytorch """ super(NormalizingFlows, self).__init__() flows_: List[Flow] if (flows is None) and (dim is not None): flows_ = [PlanarNormalizingFlow(dim=dim) for _ in range(16)] elif flows: flows_ = flows else: raise ValueError('Either dim or non empty flows list should be provided.') flows__ = nn.ModuleList(flows_) # noinspection PyTypeChecker self.flows = flows__ # type: ignore def forward_(self, z: Tensor) -> Tuple[Tensor, Tensor]: z, sum_log_abs_det_jacobian = self.flows[0].__call__(z) for flow in self.flows[1:]: z, j = flow.__call__(z) sum_log_abs_det_jacobian = sum_log_abs_det_jacobian + j return z, sum_log_abs_det_jacobian def backward(self, z: Tensor) -> Tuple[Tensor, Tensor]: z, sum_log_abs_det_jacobian = self.flows[-1].backward(z) for flow in reversed(self.flows[:-1]): z, j = flow.backward(z) sum_log_abs_det_jacobian = sum_log_abs_det_jacobian + j return z, sum_log_abs_det_jacobian class SequentialFlow(SequentialZToXY): _modules: Dict[str, UModuleZToXY] def __init__(self, *args: UModuleZToXY): # pylint: disable=useless-super-delegation """ Class that extends ``torch.nn.Sequential`` for computing the output of the function alongside with the log-det-Jacobian of such transformation. Forked from github.com/nicola-decao/BNAF """ super(SequentialFlow, self).__init__(*args) def forward_(self, z: Tensor) -> Tuple[Tensor, Tensor]: """ :return: The output tensor and the log-det-Jacobian of this transformation. """ # log abs det jacobian: ladetj: Union[int, Tensor] = 0 for module in self._modules.values(): fz, ladetj_ = module.__call__(z) ladetj = ladetj_ + ladetj z = fz if not isinstance(ladetj, int): return z, ladetj raise RuntimeError('Presumably empty Sequential') @abstractmethod def backward(self, z: Tensor) -> Tuple[Tensor, Tensor]: raise NotImplementedError class PlanarNormalizingFlow(Flow): def __init__(self, dim: int): """ Planar normalizing flow [Rezende & Mohamed 2015]. Provides a tighter bound on the ELBO by giving more expressive power to the approximate distribution, such as by introducing covariance between terms. Forked from github.com/wohlert/semi-supervised-pytorch """ super(PlanarNormalizingFlow, self).__init__() self.dim = dim self.u = nn_.Parameter(tr.randn(dim)) self.w = nn_.Parameter(tr.randn(dim)) self.b = nn_.Parameter(tr.ones(1)) def forward_(self, z: Tensor) -> Tuple[Tensor, Tensor]: u, w, b = self.u, self.w, self.b # Create uhat such that it is parallel to w uw = tr.dot(u, w) u_hat = u + (func.softplus(uw) - 1 - uw) * tr.transpose(w, 0, -1) / tr.sum(w**2) # m(uw) == softplus(uw) - 1 == log(1 + exp(uw)) - 1 # Equation 21 - Transform z zw__b = tr.mv(z, vec=w) + b # z @ w + b fz = z + (u_hat.view(1, -1) * tr.tanh(zw__b).view(-1, 1)) # Compute the Jacobian using the fact that # tanh(x) dx = 1 - tanh(x)**2 ψ = (-tr.tanh(zw__b)**2 + 1).view(-1, 1) * w.view(1, -1) ψu = tr.mv(ψ, vec=u_hat) # ψ @ u_hat # Return the transformed output along with log determninant of J logabs_detjacobian = tr.log(tr.abs(ψu + 1) + δ) return fz, logabs_detjacobian def backward(self, z: Tensor) -> Tuple[Tensor, Tensor]: raise NotImplementedError
36.358025
89
0.665705
01c8371284c699cb3ee0ef0b56df4ed553330743
142
py
Python
main/factorial/factorial_lambda.py
akshit777/Hello-world
ea38f8fb146f9855bde3614c9683e8b151b1a838
[ "MIT" ]
null
null
null
main/factorial/factorial_lambda.py
akshit777/Hello-world
ea38f8fb146f9855bde3614c9683e8b151b1a838
[ "MIT" ]
null
null
null
main/factorial/factorial_lambda.py
akshit777/Hello-world
ea38f8fb146f9855bde3614c9683e8b151b1a838
[ "MIT" ]
null
null
null
import sys factorial = lambda w: reduce(lambda x,y: x*y, range(1,w+1)) if w > 0 else 1 if w == 0 else None print(factorial(int(sys.argv[1])))
35.5
95
0.669014
4f90a526f956909115d9073dbec8f3a6fe4fe7fc
22,634
py
Python
commpy/modulation.py
Devansh0210/CommPy
c924b38e21d0600bf8072164cb0d9060d2ac2660
[ "BSD-3-Clause" ]
2
2018-11-18T22:10:49.000Z
2019-07-12T08:35:24.000Z
commpy/modulation.py
Devansh0210/CommPy
c924b38e21d0600bf8072164cb0d9060d2ac2660
[ "BSD-3-Clause" ]
null
null
null
commpy/modulation.py
Devansh0210/CommPy
c924b38e21d0600bf8072164cb0d9060d2ac2660
[ "BSD-3-Clause" ]
null
null
null
# Authors: CommPy contributors # License: BSD 3-Clause """ ================================================== Modulation Demodulation (:mod:`commpy.modulation`) ================================================== .. autosummary:: :toctree: generated/ PSKModem -- Phase Shift Keying (PSK) Modem. QAMModem -- Quadrature Amplitude Modulation (QAM) Modem. ofdm_tx -- OFDM Transmit Signal Generation ofdm_rx -- OFDM Receive Signal Processing mimo_ml -- MIMO Maximum Likelihood (ML) Detection. kbest -- MIMO K-best Schnorr-Euchner Detection. best_first_detector -- MIMO Best-First Detection. bit_lvl_repr -- Bit Level Representation. max_log_approx -- Max-Log Approximation. """ from bisect import insort import matplotlib.pyplot as plt from numpy import arange, array, zeros, pi, sqrt, log2, argmin, \ hstack, repeat, tile, dot, shape, concatenate, exp, \ log, vectorize, empty, eye, kron, inf, full, abs, newaxis, minimum, clip, fromiter from numpy.fft import fft, ifft from numpy.linalg import qr, norm from sympy.combinatorics.graycode import GrayCode from commpy.utilities import bitarray2dec, dec2bitarray, signal_power __all__ = ['PSKModem', 'QAMModem', 'ofdm_tx', 'ofdm_rx', 'mimo_ml', 'kbest', 'best_first_detector', 'bit_lvl_repr', 'max_log_approx'] class Modem: """ Creates a custom Modem object. Parameters ---------- constellation : array-like with a length which is a power of 2 Constellation of the custom modem Attributes ---------- constellation : 1D-ndarray of complex Modem constellation. If changed, the length of the new constellation must be a power of 2. Es : float Average energy per symbols. m : integer Constellation length. num_bits_symb : integer Number of bits per symbol. Raises ------ ValueError If the constellation is changed to an array-like with length that is not a power of 2. """ def __init__(self, constellation, reorder_as_gray=True): """ Creates a custom Modem object. """ if reorder_as_gray: m = log2(len(constellation)) gray_code_sequence = GrayCode(m).generate_gray() gray_code_sequence_array = fromiter((int(g, 2) for g in gray_code_sequence), int, len(constellation)) self.constellation = array(constellation)[gray_code_sequence_array.argsort()] else: self.constellation = constellation def modulate(self, input_bits): """ Modulate (map) an array of bits to constellation symbols. Parameters ---------- input_bits : 1D ndarray of ints Inputs bits to be modulated (mapped). Returns ------- baseband_symbols : 1D ndarray of complex floats Modulated complex symbols. """ mapfunc = vectorize(lambda i: self._constellation[bitarray2dec(input_bits[i:i + self.num_bits_symbol])]) baseband_symbols = mapfunc(arange(0, len(input_bits), self.num_bits_symbol)) return baseband_symbols def demodulate(self, input_symbols, demod_type, noise_var=0): """ Demodulate (map) a set of constellation symbols to corresponding bits. Parameters ---------- input_symbols : 1D ndarray of complex floats Input symbols to be demodulated. demod_type : string 'hard' for hard decision output (bits) 'soft' for soft decision output (LLRs) noise_var : float AWGN variance. Needs to be specified only if demod_type is 'soft' Returns ------- demod_bits : 1D ndarray of ints Corresponding demodulated bits. """ if demod_type == 'hard': index_list = abs(input_symbols - self._constellation[:, None]).argmin(0) demod_bits = dec2bitarray(index_list, self.num_bits_symbol) elif demod_type == 'soft': demod_bits = zeros(len(input_symbols) * self.num_bits_symbol) for i in arange(len(input_symbols)): current_symbol = input_symbols[i] for bit_index in arange(self.num_bits_symbol): llr_num = 0 llr_den = 0 for bit_value, symbol in enumerate(self._constellation): if (bit_value >> bit_index) & 1: llr_num += exp((-abs(current_symbol - symbol) ** 2) / noise_var) else: llr_den += exp((-abs(current_symbol - symbol) ** 2) / noise_var) demod_bits[i * self.num_bits_symbol + self.num_bits_symbol - 1 - bit_index] = log(llr_num / llr_den) else: raise ValueError('demod_type must be "hard" or "soft"') return demod_bits def plot_constellation(self): """ Plot the constellation """ plt.scatter(self.constellation.real, self.constellation.imag) for symb in self.constellation: plt.text(symb.real + .2, symb.imag, self.demodulate(symb, 'hard')) plt.title('Constellation') plt.grid() plt.show() @property def constellation(self): """ Constellation of the modem. """ return self._constellation @constellation.setter def constellation(self, value): # Check value input num_bits_symbol = log2(len(value)) if num_bits_symbol != int(num_bits_symbol): raise ValueError('Constellation length must be a power of 2.') # Set constellation as an array self._constellation = array(value) # Update other attributes self.Es = signal_power(self.constellation) self.m = self._constellation.size self.num_bits_symbol = int(num_bits_symbol) class PSKModem(Modem): """ Creates a Phase Shift Keying (PSK) Modem object. Parameters ---------- m : int Size of the PSK constellation. Attributes ---------- constellation : 1D-ndarray of complex Modem constellation. If changed, the length of the new constellation must be a power of 2. Es : float Average energy per symbols. m : integer Constellation length. num_bits_symb : integer Number of bits per symbol. Raises ------ ValueError If the constellation is changed to an array-like with length that is not a power of 2. """ def __init__(self, m): """ Creates a Phase Shift Keying (PSK) Modem object. """ num_bits_symbol = log2(m) if num_bits_symbol != int(num_bits_symbol): raise ValueError('Constellation length must be a power of 2.') super().__init__(exp(1j * arange(0, 2 * pi, 2 * pi / m))) class QAMModem(Modem): """ Creates a Quadrature Amplitude Modulation (QAM) Modem object. Parameters ---------- m : int Size of the PSK constellation. Attributes ---------- constellation : 1D-ndarray of complex Modem constellation. If changed, the length of the new constellation must be a power of 2. Es : float Average energy per symbols. m : integer Constellation length. num_bits_symb : integer Number of bits per symbol. Raises ------ ValueError If the constellation is changed to an array-like with length that is not a power of 2. If the parameter m would lead to an non-square QAM during initialization. """ def __init__(self, m): """ Creates a Quadrature Amplitude Modulation (QAM) Modem object. Parameters ---------- m : int Size of the QAM constellation. Must lead to a square QAM (ie sqrt(m) is an integer). Raises ------ ValueError If m would lead to an non-square QAM. """ num_symb_pam = sqrt(m) if num_symb_pam != int(num_symb_pam): raise ValueError('m must lead to a square QAM.') pam = arange(-num_symb_pam + 1, num_symb_pam, 2) constellation = tile(hstack((pam, pam[::-1])), int(num_symb_pam) // 2) * 1j + pam.repeat(num_symb_pam) super().__init__(constellation) def ofdm_tx(x, nfft, nsc, cp_length): """ OFDM Transmit signal generation """ nfft = float(nfft) nsc = float(nsc) cp_length = float(cp_length) ofdm_tx_signal = array([]) for i in range(0, shape(x)[1]): symbols = x[:, i] ofdm_sym_freq = zeros(nfft, dtype=complex) ofdm_sym_freq[1:(nsc / 2) + 1] = symbols[nsc / 2:] ofdm_sym_freq[-(nsc / 2):] = symbols[0:nsc / 2] ofdm_sym_time = ifft(ofdm_sym_freq) cp = ofdm_sym_time[-cp_length:] ofdm_tx_signal = concatenate((ofdm_tx_signal, cp, ofdm_sym_time)) return ofdm_tx_signal def ofdm_rx(y, nfft, nsc, cp_length): """ OFDM Receive Signal Processing """ num_ofdm_symbols = int(len(y) / (nfft + cp_length)) x_hat = zeros([nsc, num_ofdm_symbols], dtype=complex) for i in range(0, num_ofdm_symbols): ofdm_symbol = y[i * nfft + (i + 1) * cp_length:(i + 1) * (nfft + cp_length)] symbols_freq = fft(ofdm_symbol) x_hat[:, i] = concatenate((symbols_freq[-nsc / 2:], symbols_freq[1:(nsc / 2) + 1])) return x_hat def mimo_ml(y, h, constellation): """ MIMO ML Detection. parameters ---------- y : 1D ndarray of complex floats Received complex symbols (shape: num_receive_antennas x 1) h : 2D ndarray of complex floats Channel Matrix (shape: num_receive_antennas x num_transmit_antennas) constellation : 1D ndarray of complex floats Constellation used to modulate the symbols """ _, n = h.shape m = len(constellation) x_ideal = empty((n, pow(m, n)), complex) for i in range(0, n): x_ideal[i] = repeat(tile(constellation, pow(m, i)), pow(m, n - i - 1)) min_idx = argmin(norm(y[:, None] - dot(h, x_ideal), axis=0)) x_r = x_ideal[:, min_idx] return x_r def kbest(y, h, constellation, K, noise_var=0, output_type='hard', demode=None): """ MIMO K-best Schnorr-Euchner Detection. Reference: Zhan Guo and P. Nilsson, 'Algorithm and implementation of the K-best sphere decoding for MIMO detection', IEEE Journal on Selected Areas in Communications, vol. 24, no. 3, pp. 491-503, Mar. 2006. Parameters ---------- y : 1D ndarray Received complex symbols (length: num_receive_antennas) h : 2D ndarray Channel Matrix (shape: num_receive_antennas x num_transmit_antennas) constellation : 1D ndarray of floats Constellation used to modulate the symbols K : positive integer Number of candidates kept at each step noise_var : positive float Noise variance. *Default* value is 0. output_type : str 'hard': hard output i.e. output is a binary word 'soft': soft output i.e. output is a vector of Log-Likelihood Ratios. *Default* value is 'hard' demode : function with prototype binary_word = demode(point) Function that provide the binary word corresponding to a symbol vector. Returns ------- x : 1D ndarray of constellation points or of Log-Likelihood Ratios. Detected vector (length: num_receive_antennas). raises ------ ValueError If h has more columns than rows. If output_type is something else than 'hard' or 'soft' """ nb_tx, nb_rx = h.shape if nb_rx > nb_tx: raise ValueError('h has more columns than rows') # QR decomposition q, r = qr(h) yt = q.conj().T.dot(y) # Initialization m = len(constellation) nb_can = 1 if isinstance(constellation[0], complex): const_type = complex else: const_type = float X = empty((nb_rx, K * m), dtype=const_type) # Set of current candidates d = tile(yt[:, None], (1, K * m)) # Corresponding distance vector d_tot = zeros(K * m, dtype=float) # Corresponding total distance hyp = empty(K * m, dtype=const_type) # Hypothesis vector # Processing for coor in range(nb_rx - 1, -1, -1): nb_hyp = nb_can * m # Copy best candidates m times X[:, :nb_hyp] = tile(X[:, :nb_can], (1, m)) d[:, :nb_hyp] = tile(d[:, :nb_can], (1, m)) d_tot[:nb_hyp] = tile(d_tot[:nb_can], (1, m)) # Make hypothesis hyp[:nb_hyp] = repeat(constellation, nb_can) X[coor, :nb_hyp] = hyp[:nb_hyp] d[coor, :nb_hyp] -= r[coor, coor] * hyp[:nb_hyp] d_tot[:nb_hyp] += abs(d[coor, :nb_hyp]) ** 2 # Select best candidates argsort = d_tot[:nb_hyp].argsort() nb_can = min(nb_hyp, K) # Update number of candidate # Update accordingly X[:, :nb_can] = X[:, argsort[:nb_can]] d[:, :nb_can] = d[:, argsort[:nb_can]] d[:coor, :nb_can] -= r[:coor, coor, None] * hyp[argsort[:nb_can]] d_tot[:nb_can] = d_tot[argsort[:nb_can]] if output_type == 'hard': return X[:, 0] elif output_type == 'soft': return max_log_approx(y, h, noise_var, X[:, :nb_can], demode) else: raise ValueError('output_type must be "hard" or "soft"') def best_first_detector(y, h, constellation, stack_size, noise_var, demode, llr_max): """ MIMO Best-First Detection. Reference: G. He, X. Zhang, et Z. Liang, "Algorithm and Architecture of an Efficient MIMO Detector With Cross-Level Parallel Tree-Search", IEEE Transactions on Very Large Scale Integration (VLSI) Systems, 2019 Parameters ---------- y : 1D ndarray Received complex symbols (length: num_receive_antennas) h : 2D ndarray Channel Matrix (shape: num_receive_antennas x num_transmit_antennas) constellation : 1D ndarray of floats Constellation used to modulate the symbols stack_size : tuple of integers Size of each stack (length: num_transmit_antennas - 1) noise_var : positive float Noise variance. *Default* value is 0. demode : function with prototype binary_word = demode(point) Function that provide the binary word corresponding to a symbol vector. llr_max : float Max value for LLR clipping Returns ------- x : 1D ndarray of Log-Likelihood Ratios. Detected vector (length: num_receive_antennas). """ class _Node: """ Helper data model that implements __lt__ (aka '<') as required to use bisect.insort. """ def __init__(self, symb_vectors, partial_metrics): """ Recursive initializer that build a sequence of siblings. Inputs are assumed to be ordered based on metric """ if len(partial_metrics) == 1: # There is one node to build self.symb_vector = symb_vectors.reshape(-1) # Insure that self.symb_vector is a 1d-ndarray self.partial_metric = partial_metrics[0] self.best_sibling = None else: # Recursive call to build several nodes self.symb_vector = symb_vectors[:, 0].reshape(-1) # Insure that self.symb_vector is a 1d-ndarray self.partial_metric = partial_metrics[0] self.best_sibling = _Node(symb_vectors[:, 1:], partial_metrics[1:]) def __lt__(self, other): return self.partial_metric < other.partial_metric def expand(self, yt, r, constellation): """ Build all children and return the best one. constellation must be a numpy ndarray.""" # Construct children's symbol vector child_size = self.symb_vector.size + 1 children_symb_vectors = empty((child_size, constellation.size), constellation.dtype) children_symb_vectors[1:] = self.symb_vector[:, newaxis] children_symb_vectors[0] = constellation # Compute children's partial metric and sort children_metric = abs(yt[-child_size] - r[-child_size, -child_size:].dot(children_symb_vectors)) ** 2 children_metric += self.partial_metric ordering = children_metric.argsort() # Build children and return the best one return _Node(children_symb_vectors[:, ordering], children_metric[ordering]) # Extract information from arguments nb_tx, nb_rx = h.shape constellation = array(constellation) m = constellation.size modulation_order = int(log2(m)) # QR decomposition q, r = qr(h) yt = q.conj().T.dot(y) # Initialisation map_metric = inf map_bit_vector = None counter_hyp_metric = full((nb_tx, modulation_order), inf) stacks = tuple([] for _ in range(nb_tx)) # Start process by adding the best root's child in the last stack stacks[-1].append(_Node(empty(0, constellation.dtype), array(0, float, ndmin=1)).expand(yt, r, constellation)) # While there is at least one non-empty stack (exempt the first one) while any(stacks[1:]): # Node processing for idx_next_stack in range(len(stacks) - 1): try: idx_this_stack = idx_next_stack + 1 best_node = stacks[idx_this_stack].pop(0) # Update search radius if map_bit_vector is None: radius = inf # No leaf has been reached yet so we keep all nodes else: bit_vector = demode(best_node.symb_vector).reshape(-1, modulation_order) bit_vector[bit_vector == 0] = -1 # Select the counter hyp metrics that could be affected by this node. Details: eq. (14)-(16) in [1]. try: a2 = counter_hyp_metric[idx_this_stack:][map_bit_vector[idx_this_stack:] != bit_vector].max() except ValueError: a2 = inf # NumPy cannot compute max on an empty matrix radius = max(counter_hyp_metric[:idx_this_stack].max(), a2) # Process best sibling if best_node.best_sibling is not None and best_node.best_sibling.partial_metric <= radius: insort(stacks[idx_this_stack], best_node.best_sibling) # Process children best_child = best_node.expand(yt, r, constellation) if best_child.partial_metric <= radius: insort(stacks[idx_next_stack], best_child) except IndexError: # Raised when popping an empty stack pass # LLR update if there is a new leaf if stacks[0]: if stacks[0][0].partial_metric < map_metric: minimum(counter_hyp_metric, map_metric, out=counter_hyp_metric) map_metric = stacks[0][0].partial_metric map_bit_vector = demode(stacks[0][0].symb_vector).reshape(-1, modulation_order) map_bit_vector[map_bit_vector == 0] = -1 else: minimum(counter_hyp_metric, stacks[0][0].partial_metric, out=counter_hyp_metric) clip(counter_hyp_metric, map_metric - llr_max, map_metric + llr_max, counter_hyp_metric) # Trimming stack according to requested max stack size del stacks[0][0:] # there is no stack for the leafs for idx_next_stack in range(len(stacks) - 1): del stacks[idx_next_stack + 1][stack_size[idx_next_stack]:] return ((map_metric - counter_hyp_metric) * map_bit_vector).reshape(-1) def bit_lvl_repr(H, w): """ Bit-level representation of matrix H with weights w. parameters ---------- H : 2D ndarray (shape : nb_rx, nb_tx) Channel Matrix. w : 1D ndarray of complex (length : beta) Bit level representation weights. The length must be even. return ------ A : 2D nbarray (shape : nb_rx, nb_tx*beta) Channel matrix adapted to the bit-level representation. raises ------ ValueError If beta (the length of w) is not even) """ beta = len(w) if beta % 2 == 0: m, n = H.shape In = eye(n, n) kr = kron(In, w) return dot(H, kr) else: raise ValueError('Beta (length of w) must be even.') def max_log_approx(y, h, noise_var, pts_list, demode): """ Max-log demode parameters ---------- y : 1D ndarray Received symbol vector (length: num_receive_antennas) h : 2D ndarray Channel Matrix (shape: num_receive_antennas x num_transmit_antennas) noise_var : positive float Noise variance pts_list : 2D ndarray of constellation points Set of points to compute max log approximation (points are column-wise). (shape: num_receive_antennas x num_points) demode : function with prototype binary_word = demode(point) Function that provide the binary word corresponding to a symbol vector. return ------ LLR : 1D ndarray of floats Log-Likelihood Ratio for each bit (same length as the return of decode) """ # Decode all pts nb_pts = pts_list.shape[1] bits = demode(pts_list.reshape(-1, order='F')).reshape(nb_pts, -1) # Set of binary words (one word by row) # Prepare LLR computation nb_bits = bits.shape[1] LLR = empty(nb_bits) # Loop for each bit for k in range(nb_bits): # Select pts based on the k-th bit in the corresponding word pts0 = pts_list.compress(bits[:, k] == 0, axis=1) pts1 = pts_list.compress(bits[:, k] == 1, axis=1) # Compute the norms and add inf to handle empty set of points norms0 = hstack((norm(y[:, None] - h.dot(pts0), axis=0) ** 2, inf)) norms1 = hstack((norm(y[:, None] - h.dot(pts1), axis=0) ** 2, inf)) # Compute LLR LLR[k] = min(norms0) - min(norms1) return -LLR / (2 * noise_var)
34.982998
120
0.595785
d99d5c60ef0e9b45215619a43f4f22cbc870cbc9
809
py
Python
a10sdk/core/link/link.py
deepfield/a10sdk-python
bfaa58099f51f085d5e91652d1d1a3fd5c529d5d
[ "Apache-2.0" ]
16
2015-05-20T07:26:30.000Z
2021-01-23T11:56:57.000Z
a10sdk/core/link/link.py
deepfield/a10sdk-python
bfaa58099f51f085d5e91652d1d1a3fd5c529d5d
[ "Apache-2.0" ]
6
2015-03-24T22:07:11.000Z
2017-03-28T21:31:18.000Z
a10sdk/core/link/link.py
deepfield/a10sdk-python
bfaa58099f51f085d5e91652d1d1a3fd5c529d5d
[ "Apache-2.0" ]
23
2015-03-29T15:43:01.000Z
2021-06-02T17:12:01.000Z
from a10sdk.common.A10BaseClass import A10BaseClass class Link(A10BaseClass): """ :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` Class Description:: Link to Configuration Profile. Class link supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` URL for this object:: `https://<Hostname|Ip address>//axapi/v3/link`. """ def __init__(self, **kwargs): self.ERROR_MSG = "" self.required=[] self.b_key = "link" self.a10_url="/axapi/v3/link" self.DeviceProxy = "" self.startup_config = {} for keys, value in kwargs.items(): setattr(self,keys, value)
23.114286
123
0.631644
ba74b25a88f0d28959cd1e8c3b92b4677df40b43
145
py
Python
intro/numpy/solutions/1_1_array_creation.py
junghun73/Learning
8b5a295c42f142a3b2f5fa13fc75434a2ea9235a
[ "CC-BY-4.0" ]
419
2016-03-05T08:50:48.000Z
2022-03-24T15:16:46.000Z
intro/numpy/solutions/1_1_array_creation.py
techeye220/scipy-lecture-notes-zh-CN
cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6
[ "CC-BY-4.0" ]
5
2016-05-21T14:21:12.000Z
2017-10-06T11:09:48.000Z
intro/numpy/solutions/1_1_array_creation.py
techeye220/scipy-lecture-notes-zh-CN
cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6
[ "CC-BY-4.0" ]
233
2016-02-13T09:22:57.000Z
2021-11-11T17:58:44.000Z
import numpy as np a = np.ones((4, 4), dtype=int) a[3,1] = 6 a[2,3] = 2 b = np.zeros((6, 5)) b[1:] = np.diag(np.arange(2, 7)) print a print b
12.083333
32
0.551724